@clerk/clerk-js 6.25.9-canary.v20260724235708 → 6.25.9

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 (42) hide show
  1. package/dist/clerk.browser.js +4 -4
  2. package/dist/clerk.js +3 -3
  3. package/dist/clerk.legacy.browser.js +1 -1
  4. package/dist/clerk.mjs +3 -3
  5. package/dist/clerk.native.js +4 -4
  6. package/dist/clerk.no-rhc.js +3 -3
  7. package/dist/clerk.no-rhc.mjs +3 -3
  8. package/dist/types/core/auth/SessionCookiePoller.d.ts +1 -0
  9. package/dist/types/utils/isTabFocused.d.ts +2 -0
  10. package/package.json +4 -4
  11. /package/dist/{10_clerk.browser_e2f0b6_6.25.9-canary.v20260724235708.js → 10_clerk.browser_0de4f7_6.25.9.js} +0 -0
  12. /package/dist/{10_clerk.legacy.browser_cf3e88_6.25.9-canary.v20260724235708.js → 10_clerk.legacy.browser_576996_6.25.9.js} +0 -0
  13. /package/dist/{121_clerk.native_ee6716_6.25.9-canary.v20260724235708.js → 121_clerk.native_3ffb33_6.25.9.js} +0 -0
  14. /package/dist/{129_clerk.native_ee6716_6.25.9-canary.v20260724235708.js → 129_clerk.native_3ffb33_6.25.9.js} +0 -0
  15. /package/dist/{158_clerk.native_ee6716_6.25.9-canary.v20260724235708.js → 158_clerk.native_3ffb33_6.25.9.js} +0 -0
  16. /package/dist/{188_clerk.native_ee6716_6.25.9-canary.v20260724235708.js → 188_clerk.native_3ffb33_6.25.9.js} +0 -0
  17. /package/dist/{321_clerk.browser_e2f0b6_6.25.9-canary.v20260724235708.js → 321_clerk.browser_0de4f7_6.25.9.js} +0 -0
  18. /package/dist/{321_clerk.legacy.browser_cf3e88_6.25.9-canary.v20260724235708.js → 321_clerk.legacy.browser_576996_6.25.9.js} +0 -0
  19. /package/dist/{321_clerk.native_ee6716_6.25.9-canary.v20260724235708.js → 321_clerk.native_3ffb33_6.25.9.js} +0 -0
  20. /package/dist/{462_clerk.native_ee6716_6.25.9-canary.v20260724235708.js → 462_clerk.native_3ffb33_6.25.9.js} +0 -0
  21. /package/dist/{494_clerk.browser_e2f0b6_6.25.9-canary.v20260724235708.js → 494_clerk.browser_0de4f7_6.25.9.js} +0 -0
  22. /package/dist/{494_clerk.legacy.browser_cf3e88_6.25.9-canary.v20260724235708.js → 494_clerk.legacy.browser_576996_6.25.9.js} +0 -0
  23. /package/dist/{494_clerk.native_ee6716_6.25.9-canary.v20260724235708.js → 494_clerk.native_3ffb33_6.25.9.js} +0 -0
  24. /package/dist/{547_clerk.native_ee6716_6.25.9-canary.v20260724235708.js → 547_clerk.native_3ffb33_6.25.9.js} +0 -0
  25. /package/dist/{569_clerk.native_ee6716_6.25.9-canary.v20260724235708.js → 569_clerk.native_3ffb33_6.25.9.js} +0 -0
  26. /package/dist/{base-account-sdk_clerk.browser_e2f0b6_6.25.9-canary.v20260724235708.js → base-account-sdk_clerk.browser_0de4f7_6.25.9.js} +0 -0
  27. /package/dist/{base-account-sdk_clerk.legacy.browser_cf3e88_6.25.9-canary.v20260724235708.js → base-account-sdk_clerk.legacy.browser_576996_6.25.9.js} +0 -0
  28. /package/dist/{coinbase-wallet-sdk_clerk.browser_e2f0b6_6.25.9-canary.v20260724235708.js → coinbase-wallet-sdk_clerk.browser_0de4f7_6.25.9.js} +0 -0
  29. /package/dist/{coinbase-wallet-sdk_clerk.legacy.browser_cf3e88_6.25.9-canary.v20260724235708.js → coinbase-wallet-sdk_clerk.legacy.browser_576996_6.25.9.js} +0 -0
  30. /package/dist/{cookieSuffix_clerk.browser_e2f0b6_6.25.9-canary.v20260724235708.js → cookieSuffix_clerk.browser_0de4f7_6.25.9.js} +0 -0
  31. /package/dist/{cookieSuffix_clerk.legacy.browser_cf3e88_6.25.9-canary.v20260724235708.js → cookieSuffix_clerk.legacy.browser_576996_6.25.9.js} +0 -0
  32. /package/dist/{cookieSuffix_clerk.native_ee6716_6.25.9-canary.v20260724235708.js → cookieSuffix_clerk.native_3ffb33_6.25.9.js} +0 -0
  33. /package/dist/{query-core-vendors_clerk.browser_e2f0b6_6.25.9-canary.v20260724235708.js → query-core-vendors_clerk.browser_0de4f7_6.25.9.js} +0 -0
  34. /package/dist/{query-core-vendors_clerk.legacy.browser_cf3e88_6.25.9-canary.v20260724235708.js → query-core-vendors_clerk.legacy.browser_576996_6.25.9.js} +0 -0
  35. /package/dist/{stripe-vendors_clerk.browser_e2f0b6_6.25.9-canary.v20260724235708.js → stripe-vendors_clerk.browser_0de4f7_6.25.9.js} +0 -0
  36. /package/dist/{stripe-vendors_clerk.legacy.browser_cf3e88_6.25.9-canary.v20260724235708.js → stripe-vendors_clerk.legacy.browser_576996_6.25.9.js} +0 -0
  37. /package/dist/{vendors_clerk.browser_e2f0b6_6.25.9-canary.v20260724235708.js → vendors_clerk.browser_0de4f7_6.25.9.js} +0 -0
  38. /package/dist/{vendors_clerk.legacy.browser_cf3e88_6.25.9-canary.v20260724235708.js → vendors_clerk.legacy.browser_576996_6.25.9.js} +0 -0
  39. /package/dist/{zxcvbn-common_clerk.browser_e2f0b6_6.25.9-canary.v20260724235708.js → zxcvbn-common_clerk.browser_0de4f7_6.25.9.js} +0 -0
  40. /package/dist/{zxcvbn-common_clerk.legacy.browser_cf3e88_6.25.9-canary.v20260724235708.js → zxcvbn-common_clerk.legacy.browser_576996_6.25.9.js} +0 -0
  41. /package/dist/{zxcvbn-ts-core_clerk.browser_e2f0b6_6.25.9-canary.v20260724235708.js → zxcvbn-ts-core_clerk.browser_0de4f7_6.25.9.js} +0 -0
  42. /package/dist/{zxcvbn-ts-core_clerk.legacy.browser_cf3e88_6.25.9-canary.v20260724235708.js → zxcvbn-ts-core_clerk.legacy.browser_576996_6.25.9.js} +0 -0
package/dist/clerk.js CHANGED
@@ -42,7 +42,7 @@ Try increasing the nonce or find the latest nonce with \`getTransactionCount\`.`
42
42
  `;return a.nonce&&(r+=` nonce: ${a.nonce}
43
43
  `),a.balance&&(r+=` balance: ${a.balance}
44
44
  `),a.code&&(r+=` code: ${a.code}
45
- `),a.state&&(r+=" state:\n",r+=s(a.state)),a.stateDiff&&(r+=" stateDiff:\n",r+=s(a.stateDiff)),r}," State Override:\n").slice(0,-1)}a.d(t,{Hi:()=>n,ft:()=>i,uj:()=>o})},8211(e,t,a){"use strict";a(5425),a(8417);var r=a(4866);function n(e){let t=Object.entries(e).map(([e,t])=>void 0===t||!1===t?null:[e,t]).filter(Boolean),a=t.reduce((e,[t])=>Math.max(e,t.length),0);return t.map(([e,t])=>` ${`${e}:`.padEnd(a+1)} ${t}`).join("\n")}class i extends r.C{constructor(){super("Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.\nUse `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others.",{name:"FeeConflictError"})}}r.C;class s extends r.C{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",n(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}r.C,r.C,r.C,r.C;class o extends r.C{constructor({blockHash:e,blockNumber:t,blockTag:a,hash:r,index:n}){let i="Transaction";a&&void 0!==n&&(i=`Transaction at block time "${a}" at index "${n}"`),e&&void 0!==n&&(i=`Transaction at block hash "${e}" at index "${n}"`),t&&void 0!==n&&(i=`Transaction at block number "${t}" at index "${n}"`),r&&(i=`Transaction with hash "${r}"`),super(`${i} could not be found.`,{name:"TransactionNotFoundError"})}}class l extends r.C{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class c extends r.C{constructor({receipt:e}){super(`Transaction with hash "${e.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=e}}class u extends r.C{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}a.d(t,{Kc:()=>l,Kz:()=>o,Sq:()=>c,Vg:()=>s,WA:()=>u,aO:()=>n,n3:()=>i})},9034(e,t,a){"use strict";a.d(t,{},{I:e=>e,R:e=>e})},4647(e,t,a){"use strict";a.d(t,{n:()=>f});var r=a(8693),n=a(1900),i=a(3879),s=a(5817),o=a(996),l=a(8596),c=a(5578),u=a(5074),d=a(7373);function h(e,t={}){void 0!==t.size&&(0,u.Sl)(e,{size:t.size});let a=(0,d.My)(e,t);return(0,u.ME)(a,t)}var m=a(659),p=a(2968);function f(e,t){let a="string"==typeof t?(0,m.aT)(t):t,f=(0,i.l)(a);if(0===(0,s.E)(a)&&e.length>0)throw new r.O;if((0,s.E)(t)&&32>(0,s.E)(t))throw new r.Iy({data:"string"==typeof t?t:(0,d.My)(t),params:e,size:(0,s.E)(t)});let b=0,y=[];for(let t=0;t<e.length;++t){let a=e[t];f.setPosition(b);let[i,s]=function e(t,a,{staticPosition:i}){let s=(0,p.k)(a.type);if(s){let[r,n]=s;return function(t,a,{length:r,staticPosition:n}){if(!r){let r=n+h(t.readBytes(32)),i=r+32;t.setPosition(r);let s=h(t.readBytes(32)),o=g(a),l=0,c=[];for(let r=0;r<s;++r){t.setPosition(i+(o?32*r:l));let[n,s]=e(t,a,{staticPosition:i});l+=s,c.push(n)}return t.setPosition(n+32),[c,32]}if(g(a)){let i=n+h(t.readBytes(32)),s=[];for(let n=0;n<r;++n){t.setPosition(i+32*n);let[r]=e(t,a,{staticPosition:i});s.push(r)}return t.setPosition(n+32),[s,32]}let i=0,s=[];for(let o=0;o<r;++o){let[r,o]=e(t,a,{staticPosition:n+i});i+=o,s.push(r)}return[s,i]}(t,{...a,type:n},{length:r,staticPosition:i})}if("tuple"===a.type)return function(t,a,{staticPosition:r}){let n=0===a.components.length||a.components.some(({name:e})=>!e),i=n?[]:{},s=0;if(g(a)){let o=r+h(t.readBytes(32));for(let r=0;r<a.components.length;++r){let l=a.components[r];t.setPosition(o+s);let[c,u]=e(t,l,{staticPosition:o});s+=u,i[n?r:l?.name]=c}return t.setPosition(r+32),[i,32]}for(let o=0;o<a.components.length;++o){let l=a.components[o],[c,u]=e(t,l,{staticPosition:r});i[n?o:l?.name]=c,s+=u}return[i,s]}(t,a,{staticPosition:i});if("address"===a.type){let e;return e=t.readBytes(32),[(0,n.o)((0,d.My)((0,o.A1)(e,-20))),32]}if("bool"===a.type)return[function(e,t={}){let a=e;if(void 0!==t.size&&((0,u.Sl)(a,{size:t.size}),a=(0,l.B)(a)),a.length>1||a[0]>1)throw new c.xO(a);return!!a[0]}(t.readBytes(32),{size:32}),32];if(a.type.startsWith("bytes"))return function(e,t,{staticPosition:a}){let[r,n]=t.type.split("bytes");if(!n){let t=h(e.readBytes(32));e.setPosition(a+t);let r=h(e.readBytes(32));if(0===r)return e.setPosition(a+32),["0x",32];let n=e.readBytes(r);return e.setPosition(a+32),[(0,d.My)(n),32]}return[(0,d.My)(e.readBytes(Number.parseInt(n,10),32)),32]}(t,a,{staticPosition:i});if(a.type.startsWith("uint")||a.type.startsWith("int")){var m,f;let e,r,n;return m=t,e=(f=a).type.startsWith("int"),r=Number.parseInt(f.type.split("int")[1]||"256",10),n=m.readBytes(32),[r>48?function(e,t={}){void 0!==t.size&&(0,u.Sl)(e,{size:t.size});let a=(0,d.My)(e,t);return(0,u.uU)(a,t)}(n,{signed:e}):h(n,{signed:e}),32]}if("string"===a.type)return function(e,{staticPosition:t}){let a=h(e.readBytes(32));e.setPosition(t+a);let r=h(e.readBytes(32));if(0===r)return e.setPosition(t+32),["",32];let n=e.readBytes(r,32),i=function(e,t={}){let a=e;return void 0!==t.size&&((0,u.Sl)(a,{size:t.size}),a=(0,l.B)(a,{dir:"right"})),new TextDecoder().decode(a)}((0,l.B)(n));return e.setPosition(t+32),[i,32]}(t,{staticPosition:i});throw new r.j(a.type,{docsPath:"/docs/contract/decodeAbiParameters"})}(f,a,{staticPosition:0});b+=s,y.push(i)}return y}function g(e){let{type:t}=e;if("string"===t||"bytes"===t||t.endsWith("[]"))return!0;if("tuple"===t)return e.components?.some(g);let a=(0,p.k)(e.type);return!!(a&&g({...e,type:a[1]}))}},6769(e,t,a){"use strict";var r=a(7760),n=a(8693),i=a(996),s=a(2764),o=a(4647),l=a(1988);function c(e){let{abi:t,data:a}=e,c=(0,i.di)(a,0,4);if("0x"===c)throw new n.O;let u=[...t||[],r.Mc,r.J9].find(e=>"error"===e.type&&c===(0,s.V)((0,l.B)(e)));if(!u)throw new n.Wq(c,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:u,args:"inputs"in u&&u.inputs&&u.inputs.length>0?(0,o.n)(u.inputs,(0,i.di)(a,4)):void 0,errorName:u.name}}a.d(t,{W:()=>c})},7276(e,t,a){"use strict";var r=a(8693),n=a(996),i=a(2764),s=a(4647),o=a(1988);function l(e){let{abi:t,data:a}=e,l=(0,n.di)(a,0,4),c=t.find(e=>"function"===e.type&&l===(0,i.V)((0,o.B)(e)));if(!c)throw new r.EB(l,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:c.name,args:"inputs"in c&&c.inputs&&c.inputs.length>0?(0,s.n)(c.inputs,(0,n.di)(a,4)):void 0}}a.d(t,{J:()=>l})},5769(e,t,a){"use strict";var r=a(8693),n=a(4647),i=a(5571);let s="/docs/contract/decodeFunctionResult";function o(e){let{abi:t,args:a,functionName:o,data:l}=e,c=t[0];if(o){let e=(0,i.iY)({abi:t,args:a,name:o});if(!e)throw new r.Iz(o,{docsPath:s});c=e}if("function"!==c.type)throw new r.Iz(void 0,{docsPath:s});if(!c.outputs)throw new r.MR(c.name,{docsPath:s});let u=(0,n.n)(c.outputs,l);return u&&u.length>1?u:u&&1===u.length?u[0]:void 0}a.d(t,{e:()=>o})},2968(e,t,a){"use strict";var r=a(8693),n=a(43),i=a(4866),s=a(5578),o=a(7138),l=a(9284),c=a(6207),u=a(5817),d=a(996),h=a(7373),m=a(9974);function p(e,t){if(e.length!==t.length)throw new r.YE({expectedLength:e.length,givenLength:t.length});let a=f(function({params:e,values:t}){let a=[];for(let p=0;p<e.length;p++)a.push(function e({param:t,value:a}){let p=g(t.type);if(p){let[n,i]=p;return function(t,{length:a,param:n}){let i=null===a;if(!Array.isArray(t))throw new r.dm(t);if(!i&&t.length!==a)throw new r.Nc({expectedLength:a,givenLength:t.length,type:`${n.type}[${a}]`});let s=!1,o=[];for(let a=0;a<t.length;a++){let r=e({param:n,value:t[a]});r.dynamic&&(s=!0),o.push(r)}if(i||s){let e=f(o);if(i){let t=(0,h.cK)(o.length,{size:32});return{dynamic:!0,encoded:o.length>0?(0,l.xW)([t,e]):t}}if(s)return{dynamic:!0,encoded:e}}return{dynamic:!1,encoded:(0,l.xW)(o.map(({encoded:e})=>e))}}(a,{length:n,param:{...t,type:i}})}if("tuple"===t.type)return function(t,{param:a}){let r=!1,n=[];for(let i=0;i<a.components.length;i++){let s=a.components[i],o=Array.isArray(t)?i:s.name,l=e({param:s,value:t[o]});n.push(l),l.dynamic&&(r=!0)}return{dynamic:r,encoded:r?f(n):(0,l.xW)(n.map(({encoded:e})=>e))}}(a,{param:t});if("address"===t.type){var b=a;if(!(0,o.P)(b))throw new n.M({address:b});return{dynamic:!1,encoded:(0,c.db)(b.toLowerCase())}}if("bool"===t.type){var y=a;if("boolean"!=typeof y)throw new i.C(`Invalid boolean value: "${y}" (type: ${typeof y}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:(0,c.db)((0,h.$P)(y))}}if(t.type.startsWith("uint")||t.type.startsWith("int")){let e=t.type.startsWith("int"),[,,r="256"]=m.Ge.exec(t.type)??[];return function(e,{signed:t,size:a=256}){if("number"==typeof a){let r=2n**(BigInt(a)-(t?1n:0n))-1n,n=t?-r-1n:0n;if(e>r||e<n)throw new s.Ty({max:r.toString(),min:n.toString(),signed:t,size:a/8,value:e.toString()})}return{dynamic:!1,encoded:(0,h.cK)(e,{size:32,signed:t})}}(a,{signed:e,size:Number(r)})}if(t.type.startsWith("bytes"))return function(e,{param:t}){let[,a]=t.type.split("bytes"),n=(0,u.E)(e);if(!a){let t=e;return n%32!=0&&(t=(0,c.db)(t,{dir:"right",size:32*Math.ceil((e.length-2)/2/32)})),{dynamic:!0,encoded:(0,l.xW)([(0,c.db)((0,h.cK)(n,{size:32})),t])}}if(n!==Number.parseInt(a,10))throw new r.gH({expectedSize:Number.parseInt(a,10),value:e});return{dynamic:!1,encoded:(0,c.db)(e,{dir:"right"})}}(a,{param:t});if("string"===t.type){var w=a;let e=(0,h.i3)(w),t=Math.ceil((0,u.E)(e)/32),r=[];for(let a=0;a<t;a++)r.push((0,c.db)((0,d.di)(e,32*a,(a+1)*32),{dir:"right"}));return{dynamic:!0,encoded:(0,l.xW)([(0,c.db)((0,h.cK)((0,u.E)(e),{size:32})),...r])}}throw new r.nK(t.type,{docsPath:"/docs/contract/encodeAbiParameters"})}({param:e[p],value:t[p]}));return a}({params:e,values:t}));return 0===a.length?"0x":a}function f(e){let t=0;for(let a=0;a<e.length;a++){let{dynamic:r,encoded:n}=e[a];r?t+=32:t+=(0,u.E)(n)}let a=[],r=[],n=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:o}=e[i];s?(a.push((0,h.cK)(t+n,{size:32})),r.push(o),n+=(0,u.E)(o)):a.push(o)}return(0,l.xW)([...a,...r])}function g(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}a.d(t,{h:()=>p,k:()=>g})},8627(e,t,a){"use strict";var r=a(8693),n=a(9284),i=a(2968);let s="/docs/contract/encodeDeployData";function o(e){let{abi:t,args:a,bytecode:o}=e;if(!a||0===a.length)return o;let l=t.find(e=>"type"in e&&"constructor"===e.type);if(!l)throw new r.YW({docsPath:s});if(!("inputs"in l)||!l.inputs||0===l.inputs.length)throw new r.YF({docsPath:s});let c=(0,i.h)(l.inputs,a);return(0,n.aP)([o,c])}a.d(t,{m:()=>o})},9609(e,t,a){"use strict";a.d(t,{p:()=>u});var r=a(9284),n=a(2968),i=a(8693),s=a(2764),o=a(1988),l=a(5571);let c="/docs/contract/encodeFunctionData";function u(e){let{args:t}=e,{abi:a,functionName:u}=1===e.abi.length&&e.functionName?.startsWith("0x")?e:function(e){let{abi:t,args:a,functionName:r}=e,n=t[0];if(r){let e=(0,l.iY)({abi:t,args:a,name:r});if(!e)throw new i.Iz(r,{docsPath:c});n=e}if("function"!==n.type)throw new i.Iz(void 0,{docsPath:c});return{abi:[n],functionName:(0,s.V)((0,o.B)(n))}}(e),d=a[0],h="inputs"in d&&d.inputs?(0,n.h)(d.inputs,t??[]):void 0;return(0,r.aP)([u,h??"0x"])}},1988(e,t,a){"use strict";a.d(t,{A:()=>i,B:()=>n});var r=a(8693);function n(e,{includeName:t=!1}={}){if("function"!==e.type&&"event"!==e.type&&"error"!==e.type)throw new r.d_(e.type);return`${e.name}(${i(e.inputs,{includeName:t})})`}function i(e,{includeName:t=!1}={}){return e?e.map(e=>(function(e,{includeName:t}){return e.type.startsWith("tuple")?`(${i(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")})(e,{includeName:t})).join(t?", ":","):""}},5571(e,t,a){"use strict";var r=a(8693),n=a(7443),i=a(7138),s=a(5028),o=a(2764);function l(e){let t,{abi:a,args:l=[],name:c}=e,u=(0,n.q)(c,{strict:!1}),d=a.filter(e=>u?"function"===e.type?(0,o.V)(e)===c:"event"===e.type&&(0,s.h)(e)===c:"name"in e&&e.name===c);if(0!==d.length){if(1===d.length)return d[0];for(let e of d){if("inputs"in e){if(!l||0===l.length){if(!e.inputs||0===e.inputs.length)return e;continue}if(e.inputs&&0!==e.inputs.length&&e.inputs.length===l.length&&l.every((t,a)=>{let r="inputs"in e&&e.inputs[a];return!!r&&function e(t,a){let r=typeof t,n=a.type;switch(n){case"address":return(0,i.P)(t,{strict:!1});case"bool":return"boolean"===r;case"function":case"string":return"string"===r;default:if("tuple"===n&&"components"in a)return Object.values(a.components).every((a,r)=>e(Object.values(t)[r],a));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n))return"number"===r||"bigint"===r;if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n))return"string"===r||t instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n))return Array.isArray(t)&&t.every(t=>e(t,{...a,type:n.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}(t,r)})){if(t&&"inputs"in t&&t.inputs){let a=function e(t,a,r){for(let n in t){let s=t[n],o=a[n];if("tuple"===s.type&&"tuple"===o.type&&"components"in s&&"components"in o)return e(s.components,o.components,r[n]);let l=[s.type,o.type];if(l.includes("address")&&l.includes("bytes20")||(l.includes("address")&&l.includes("string")||l.includes("address")&&l.includes("bytes"))&&(0,i.P)(r[n],{strict:!1}))return l}}(e.inputs,t.inputs,l);if(a)throw new r.nM({abiItem:e,type:a[0]},{abiItem:t,type:a[1]})}t=e}}}return t||d[0]}}a.d(t,{iY:()=>l})},1900(e,t,a){"use strict";a.d(t,{b:()=>u,o:()=>c});var r=a(43),n=a(659),i=a(8477),s=a(1476),o=a(7138);let l=new s.A(8192);function c(e,t){if(l.has(`${e}.${t}`))return l.get(`${e}.${t}`);let a=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),r=(0,i.S)((0,n.Af)(a),"bytes"),s=(t?a.substring(`${t}0x`.length):a).split("");for(let e=0;e<40;e+=2)r[e>>1]>>4>=8&&s[e]&&(s[e]=s[e].toUpperCase()),(15&r[e>>1])>=8&&s[e+1]&&(s[e+1]=s[e+1].toUpperCase());let o=`0x${s.join("")}`;return l.set(`${e}.${t}`,o),o}function u(e,t){if(!(0,o.P)(e,{strict:!1}))throw new r.M({address:e});return c(e,t)}},7138(e,t,a){"use strict";a.d(t,{P:()=>o});var r=a(1476),n=a(1900);let i=/^0x[a-fA-F0-9]{40}$/,s=new r.A(8192);function o(e,t){let{strict:a=!0}=t??{},r=`${e}.${a}`;if(s.has(r))return s.get(r);let o=!!i.test(e)&&(e.toLowerCase()===e||!a||(0,n.o)(e)===e);return s.set(r,o),o}},5544(e,t,a){"use strict";var r=a(43),n=a(7138);function i(e,t){if(!(0,n.P)(e,{strict:!1}))throw new r.M({address:e});if(!(0,n.P)(t,{strict:!1}))throw new r.M({address:t});return e.toLowerCase()===t.toLowerCase()}a.d(t,{h:()=>i})},3992(e,t,a){"use strict";a.d(t,{offchainLookup:()=>w,offchainLookupSignature:()=>b});var r=a(4547),n=a(9312),i=a(4866),s=a(9034);class o extends i.C{constructor({callbackSelector:e,cause:t,data:a,extraData:r,sender:n,urls:i}){super(t.shortMessage||"An error occurred while fetching for an offchain result.",{cause:t,metaMessages:[...t.metaMessages||[],t.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map(e=>` ${(0,s.I)(e)}`)],` Sender: ${n}`,` Data: ${a}`,` Callback selector: ${e}`,` Extra data: ${r}`].flat(),name:"OffchainLookupError"})}}class l extends i.C{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${(0,s.I)(t)}`,`Response: ${(0,n.A)(e)}`],name:"OffchainLookupResponseMalformedError"})}}class c extends i.C{constructor({sender:e,to:t}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${t}`,`OffchainLookup sender address: ${e}`],name:"OffchainLookupSenderMismatchError"})}}var u=a(1958),d=a(6769),h=a(2968),m=a(5544),p=a(9284),f=a(7443),g=a(5701);let b="0x556f1830",y={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function w(e,{blockNumber:t,blockTag:a,data:n,to:i}){let{args:s}=(0,d.W)({data:n,abi:[y]}),[l,u,f,b,v]=s,{ccipRead:_}=e,x=_&&"function"==typeof _?.request?_.request:k;try{if(!(0,m.h)(i,l))throw new c({sender:l,to:i});let n=u.includes(g.J)?await (0,g.X)({data:f,ccipRequest:x}):await x({data:f,sender:l,urls:u}),{data:s}=await (0,r.T)(e,{blockNumber:t,blockTag:a,data:(0,p.xW)([b,(0,h.h)([{type:"bytes"},{type:"bytes"}],[n,v])]),to:i});return s}catch(e){throw new o({callbackSelector:b,cause:e,data:n,extraData:v,sender:l,urls:u})}}async function k({data:e,sender:t,urls:a}){let r=Error("An unknown error occurred.");for(let i=0;i<a.length;i++){let s=a[i],o=s.includes("{data}")?"GET":"POST",c="POST"===o?{data:e,sender:t}:void 0,d="POST"===o?{"Content-Type":"application/json"}:{};try{let a,i=await fetch(s.replace("{sender}",t.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:d,method:o});if(a=i.headers.get("Content-Type")?.startsWith("application/json")?(await i.json()).data:await i.text(),!i.ok){r=new u.Ci({body:c,details:a?.error?(0,n.A)(a.error):i.statusText,headers:i.headers,status:i.status,url:s});continue}if(!(0,f.q)(a)){r=new l({result:a,url:s});continue}return a}catch(e){r=new u.Ci({body:c,details:e.message,url:s})}}throw r}},7042(e,t,a){"use strict";var r=a(4542);function n({blockNumber:e,chain:t,contract:a}){let i=t?.contracts?.[a];if(!i)throw new r.rj({chain:t,contract:{name:a}});if(e&&i.blockCreated&&i.blockCreated>e)throw new r.rj({blockNumber:e,chain:t,contract:{name:a,blockCreated:i.blockCreated}});return i.address}a.d(t,{M:()=>n})},3879(e,t,a){"use strict";var r=a(1857);let n={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:1/0,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new r.hX({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new r.SK({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new r.B4({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new r.B4({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let a=t??this.position;return this.assertPosition(a+e-1),this.bytes.subarray(a,a+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,255&e),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let a=this.inspectBytes(e);return this.position+=t??e,a},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===1/0)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function i(e,{recursiveReadLimit:t=8192}={}){let a=Object.create(n);return a.bytes=e,a.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),a.positionReadCount=new Map,a.recursiveReadLimit=t,a}a.d(t,{l:()=>i})},9284(e,t,a){"use strict";function r(e){return"string"==typeof e[0]?n(e):function(e){let t=0;for(let a of e)t+=a.length;let a=new Uint8Array(t),r=0;for(let t of e)a.set(t,r),r+=t.length;return a}(e)}function n(e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}a.d(t,{aP:()=>n,xW:()=>r})},7443(e,t,a){"use strict";function r(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}a.d(t,{q:()=>r})},6207(e,t,a){"use strict";var r=a(2691);function n(e,{dir:t,size:a=32}={}){return"string"==typeof e?i(e,{dir:t,size:a}):function(e,{dir:t,size:a=32}={}){if(null===a)return e;if(e.length>a)throw new r.Fl({size:e.length,targetSize:a,type:"bytes"});let n=new Uint8Array(a);for(let r=0;r<a;r++){let i="right"===t;n[i?r:a-r-1]=e[i?r:e.length-r-1]}return n}(e,{dir:t,size:a})}function i(e,{dir:t,size:a=32}={}){if(null===a)return e;let n=e.replace("0x","");if(n.length>2*a)throw new r.Fl({size:Math.ceil(n.length/2),targetSize:a,type:"hex"});return`0x${n["right"===t?"padEnd":"padStart"](2*a,"0")}`}a.d(t,{db:()=>i,eV:()=>n})},5817(e,t,a){"use strict";var r=a(7443);function n(e){return(0,r.q)(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}a.d(t,{E:()=>n})},996(e,t,a){"use strict";var r=a(2691),n=a(7443),i=a(5817);function s(e,t,a,{strict:r}={}){return(0,n.q)(e,{strict:!1})?u(e,t,a,{strict:r}):c(e,t,a,{strict:r})}function o(e,t){if("number"==typeof t&&t>0&&t>(0,i.E)(e)-1)throw new r.ii({offset:t,position:"start",size:(0,i.E)(e)})}function l(e,t,a){if("number"==typeof t&&"number"==typeof a&&(0,i.E)(e)!==a-t)throw new r.ii({offset:a,position:"end",size:(0,i.E)(e)})}function c(e,t,a,{strict:r}={}){o(e,t);let n=e.slice(t,a);return r&&l(n,t,a),n}function u(e,t,a,{strict:r}={}){o(e,t);let n=`0x${e.replace("0x","").slice((t??0)*2,(a??e.length)*2)}`;return r&&l(n,t,a),n}a.d(t,{A1:()=>c,di:()=>s,iN:()=>u})},8596(e,t,a){"use strict";function r(e,{dir:t="left"}={}){let a="string"==typeof e?e.replace("0x",""):e,n=0;for(let e=0;e<a.length-1;e++)if("0"===a["left"===t?e:a.length-e-1].toString())n++;else break;return(a="left"===t?a.slice(n):a.slice(0,a.length-n),"string"==typeof e)?(1===a.length&&"right"===t&&(a=`${a}0`),`0x${a.length%2==1?`0${a}`:a}`):a}a.d(t,{B:()=>r})},5074(e,t,a){"use strict";a.d(t,{IQ:()=>d,ME:()=>u,Nx:()=>c,Sl:()=>o,uU:()=>l});var r=a(5578),n=a(5817),i=a(8596),s=a(659);function o(e,{size:t}){if((0,n.E)(e)>t)throw new r.u({givenSize:(0,n.E)(e),maxSize:t})}function l(e,t={}){let{signed:a}=t;t.size&&o(e,{size:t.size});let r=BigInt(e);if(!a)return r;let n=(e.length-2)/2;return r<=(1n<<8n*BigInt(n)-1n)-1n?r:r-BigInt(`0x${"f".padStart(2*n,"f")}`)-1n}function c(e,t={}){let a=e;if(t.size&&(o(a,{size:t.size}),a=(0,i.B)(a)),"0x00"===(0,i.B)(a))return!1;if("0x01"===(0,i.B)(a))return!0;throw new r.H2(a)}function u(e,t={}){return Number(l(e,t))}function d(e,t={}){let a=(0,s.aT)(e);return t.size&&(o(a,{size:t.size}),a=(0,i.B)(a,{dir:"right"})),new TextDecoder().decode(a)}},659(e,t,a){"use strict";a.d(t,{Af:()=>h,ZJ:()=>c,aT:()=>d});var r=a(4866),n=a(7443),i=a(6207),s=a(5074),o=a(7373);let l=new TextEncoder;function c(e,t={}){var a,r;return"number"==typeof e||"bigint"==typeof e?(a=e,r=t,d((0,o.cK)(a,r))):"boolean"==typeof e?function(e,t={}){let a=new Uint8Array(1);return(a[0]=Number(e),"number"==typeof t.size)?((0,s.Sl)(a,{size:t.size}),(0,i.eV)(a,{size:t.size})):a}(e,t):(0,n.q)(e)?d(e,t):h(e,t)}function u(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function d(e,t={}){let a=e;t.size&&((0,s.Sl)(a,{size:t.size}),a=(0,i.eV)(a,{dir:"right",size:t.size}));let n=a.slice(2);n.length%2&&(n=`0${n}`);let o=n.length/2,l=new Uint8Array(o);for(let e=0,t=0;e<o;e++){let a=u(n.charCodeAt(t++)),i=u(n.charCodeAt(t++));if(void 0===a||void 0===i)throw new r.C(`Invalid byte sequence ("${n[t-2]}${n[t-1]}" in "${n}").`);l[e]=16*a+i}return l}function h(e,t={}){let a=l.encode(e);return"number"==typeof t.size?((0,s.Sl)(a,{size:t.size}),(0,i.eV)(a,{dir:"right",size:t.size})):a}},7373(e,t,a){"use strict";a.d(t,{$P:()=>l,My:()=>c,cK:()=>u,i3:()=>h,nj:()=>o});var r=a(5578),n=a(6207),i=a(5074);let s=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function o(e,t={}){return"number"==typeof e||"bigint"==typeof e?u(e,t):"string"==typeof e?h(e,t):"boolean"==typeof e?l(e,t):c(e,t)}function l(e,t={}){let a=`0x${Number(e)}`;return"number"==typeof t.size?((0,i.Sl)(a,{size:t.size}),(0,n.eV)(a,{size:t.size})):a}function c(e,t={}){let a="";for(let t=0;t<e.length;t++)a+=s[e[t]];let r=`0x${a}`;return"number"==typeof t.size?((0,i.Sl)(r,{size:t.size}),(0,n.eV)(r,{dir:"right",size:t.size})):r}function u(e,t={}){let a,{signed:i,size:s}=t,o=BigInt(e);s?a=i?(1n<<8n*BigInt(s)-1n)-1n:2n**(8n*BigInt(s))-1n:"number"==typeof e&&(a=BigInt(Number.MAX_SAFE_INTEGER));let l="bigint"==typeof a&&i?-a-1n:0;if(a&&o>a||o<l){let t="bigint"==typeof e?"n":"";throw new r.Ty({max:a?`${a}${t}`:void 0,min:`${l}${t}`,signed:i,size:s,value:`${e}${t}`})}let c=`0x${(i&&o<0?(1n<<BigInt(8*s))+BigInt(o):o).toString(16)}`;return s?(0,n.eV)(c,{size:s}):c}let d=new TextEncoder;function h(e,t={}){return c(d.encode(e),t)}},5701(e,t,a){"use strict";a.d(t,{X:()=>g,J:()=>f});var r=a(7674),n=a(7760),i=a(7276),s=a(8693),o=a(9284),l=a(2764),c=a(2968),u=a(1988),d=a(5571);let h="/docs/contract/encodeErrorResult";function m(e){let{abi:t,errorName:a,args:r}=e,n=t[0];if(a){let e=(0,d.iY)({abi:t,args:r,name:a});if(!e)throw new s.yy(a,{docsPath:h});n=e}if("error"!==n.type)throw new s.yy(void 0,{docsPath:h});let i=(0,u.B)(n),m=(0,l.V)(i),p="0x";if(r&&r.length>0){if(!n.inputs)throw new s.ZP(n.name,{docsPath:h});p=(0,c.h)(n.inputs,r)}return(0,o.aP)([m,p])}let p="/docs/contract/encodeFunctionResult",f="x-batch-gateway:true";async function g(e){let{data:t,ccipRequest:a}=e,{args:[o]}=(0,i.J)({abi:r.b2,data:t}),l=[],u=[];return await Promise.all(o.map(async(e,t)=>{try{u[t]=e.urls.includes(f)?await g({data:e.data,ccipRequest:a}):await a(e),l[t]=!1}catch(e){var i;l[t]=!0,u[t]="HttpRequestError"===(i=e).name&&i.status?m({abi:r.b2,errorName:"HttpError",args:[i.status,i.shortMessage]}):m({abi:[n.Mc],errorName:"Error",args:["shortMessage"in i?i.shortMessage:i.message]})}})),function(e){let{abi:t,functionName:a,result:r}=e,n=t[0];if(a){let e=(0,d.iY)({abi:t,name:a});if(!e)throw new s.Iz(a,{docsPath:p});n=e}if("function"!==n.type)throw new s.Iz(void 0,{docsPath:p});if(!n.outputs)throw new s.MR(n.name,{docsPath:p});let i=(()=>{if(0===n.outputs.length)return[];if(1===n.outputs.length)return[r];if(Array.isArray(r))return r;throw new s.dm(r)})();return(0,c.h)(n.outputs,i)}({abi:r.b2,functionName:"query",result:[l,u]})}},7047(e,t,a){"use strict";var r=a(4723),n=a(2607),i=a(4895);function s(e,{docsPath:t,...a}){let o,l=(o=(0,i.l)(e,a))instanceof n.RM?e:o;return new r.zX(l,{docsPath:t,...a})}a.d(t,{d:()=>s})},4895(e,t,a){"use strict";var r=a(4866),n=a(2607);function i(e,t){let a=(e.details||"").toLowerCase(),i=e instanceof r.C?e.walk(e=>e?.code===n.A7.code):e;return i instanceof r.C?new n.A7({cause:e,message:i.details}):n.A7.nodeMessage.test(a)?new n.A7({cause:e,message:e.details}):n.BG.nodeMessage.test(a)?new n.BG({cause:e,maxFeePerGas:t?.maxFeePerGas}):n.jj.nodeMessage.test(a)?new n.jj({cause:e,maxFeePerGas:t?.maxFeePerGas}):n.K0.nodeMessage.test(a)?new n.K0({cause:e,nonce:t?.nonce}):n.Oh.nodeMessage.test(a)?new n.Oh({cause:e,nonce:t?.nonce}):n.vW.nodeMessage.test(a)?new n.vW({cause:e,nonce:t?.nonce}):n.k5.nodeMessage.test(a)?new n.k5({cause:e}):n.lY.nodeMessage.test(a)?new n.lY({cause:e,gas:t?.gas}):n.Fo.nodeMessage.test(a)?new n.Fo({cause:e,gas:t?.gas}):n.uC.nodeMessage.test(a)?new n.uC({cause:e}):n.lN.nodeMessage.test(a)?new n.lN({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas}):new n.RM({cause:e})}a.d(t,{l:()=>i})},8608(e,t,a){"use strict";function r(e,{format:t}){if(!t)return{};let a={};return!function t(r){for(let n of Object.keys(r))n in e&&(a[n]=e[n]),r[n]&&"object"==typeof r[n]&&!Array.isArray(r[n])&&t(r[n])}(t(e||{})),a}a.d(t,{o:()=>r})},2292(e,t,a){"use strict";var r=a(7373);let n={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function i(e,t){let a={};return void 0!==e.authorizationList&&(a.authorizationList=e.authorizationList.map(e=>({address:e.address,r:e.r?(0,r.cK)(BigInt(e.r)):e.r,s:e.s?(0,r.cK)(BigInt(e.s)):e.s,chainId:(0,r.cK)(e.chainId),nonce:(0,r.cK)(e.nonce),...void 0!==e.yParity?{yParity:(0,r.cK)(e.yParity)}:{},...void 0!==e.v&&void 0===e.yParity?{v:(0,r.cK)(e.v)}:{}}))),void 0!==e.accessList&&(a.accessList=e.accessList),void 0!==e.blobVersionedHashes&&(a.blobVersionedHashes=e.blobVersionedHashes),void 0!==e.blobs&&("string"!=typeof e.blobs[0]?a.blobs=e.blobs.map(e=>(0,r.My)(e)):a.blobs=e.blobs),void 0!==e.data&&(a.data=e.data),e.account&&(a.from=e.account.address),void 0!==e.from&&(a.from=e.from),void 0!==e.gas&&(a.gas=(0,r.cK)(e.gas)),void 0!==e.gasPrice&&(a.gasPrice=(0,r.cK)(e.gasPrice)),void 0!==e.maxFeePerBlobGas&&(a.maxFeePerBlobGas=(0,r.cK)(e.maxFeePerBlobGas)),void 0!==e.maxFeePerGas&&(a.maxFeePerGas=(0,r.cK)(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(a.maxPriorityFeePerGas=(0,r.cK)(e.maxPriorityFeePerGas)),void 0!==e.nonce&&(a.nonce=(0,r.cK)(e.nonce)),void 0!==e.to&&(a.to=e.to),void 0!==e.type&&(a.type=n[e.type]),void 0!==e.value&&(a.value=(0,r.cK)(e.value)),a}a.d(t,{Bv:()=>i})},8477(e,t,a){"use strict";var r=a(2645),n=a(7443),i=a(659),s=a(7373);function o(e,t){let a=(0,r.lY)((0,n.q)(e,{strict:!1})?(0,i.ZJ)(e):e);return"bytes"===(t||"hex")?a:(0,s.nj)(a)}a.d(t,{S:()=>o})},5028(e,t,a){"use strict";let r=a(7780).k;a.d(t,{},{h:r})},2764(e,t,a){"use strict";var r=a(996),n=a(7780);a.d(t,{},{V:e=>(0,r.di)((0,n.k)(e),0,4)})},7780(e,t,a){"use strict";a.d(t,{k:()=>c});var r=a(659),n=a(8477),i=a(4339);let s=/^tuple(?<array>(\[(\d*)\])*)$/;function o(e){let t="",a=e.length;for(let r=0;r<a;r++)t+=function e(t){let a=t.type;if(s.test(t.type)&&"components"in t){a="(";let r=t.components.length;for(let n=0;n<r;n++)a+=e(t.components[n]),n<r-1&&(a+=", ");let n=(0,i.Yv)(s,t.type);return a+=`)${n?.array??""}`,e({...t,type:a})}return("indexed"in t&&t.indexed&&(a=`${a} indexed`),t.name)?`${a} ${t.name}`:a}(e[r]),r!==a-1&&(t+=", ");return t}var l=a(4866);function c(e){var t;return t=function(e){let t=!0,a="",r=0,n="",i=!1;for(let s=0;s<e.length;s++){let o=e[s];if(["(",")",","].includes(o)&&(t=!0),"("===o&&r++,")"===o&&r--,t){if(0===r){if(" "===o&&["event","function",""].includes(n))n="";else if(n+=o,")"===o){i=!0;break}continue}if(" "===o){","!==e[s-1]&&","!==a&&",("!==a&&(a="",t=!1);continue}n+=o,a+=o}}if(!i)throw new l.C("Unable to normalize signature.");return n}((()=>"string"==typeof e?e:"function"===e.type?`function ${e.name}(${o(e.inputs)})${e.stateMutability&&"nonpayable"!==e.stateMutability?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${o(e.outputs)})`:""}`:"event"===e.type?`event ${e.name}(${o(e.inputs)})`:"error"===e.type?`error ${e.name}(${o(e.inputs)})`:"constructor"===e.type?`constructor(${o(e.inputs)})${"payable"===e.stateMutability?" payable":""}`:"fallback"===e.type?`fallback() external${"payable"===e.stateMutability?" payable":""}`:"receive() external payable")()),(0,n.S)((0,r.ZJ)(t))}},1476(e,t,a){"use strict";class r extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let e=this.keys().next().value;e&&this.delete(e)}return this}}a.d(t,{A:()=>r})},6182(e,t,a){"use strict";var r=a(4908);let n=new Map;function i({fn:e,id:t,shouldSplitBatch:a,wait:s=0,sort:o}){let l=async()=>{let t=u();c();let a=t.map(({args:e})=>e);0!==a.length&&e(a).then(e=>{o&&Array.isArray(e)&&e.sort(o);for(let a=0;a<t.length;a++){let{resolve:r}=t[a];r?.([e[a],e])}}).catch(e=>{for(let a=0;a<t.length;a++){let{reject:r}=t[a];r?.(e)}})},c=()=>n.delete(t),u=()=>n.get(t)||[],d=e=>n.set(t,[...u(),e]);return{flush:c,async schedule(e){let{promise:t,resolve:n,reject:i}=(0,r.Y)();return(a?.([...u().map(({args:e})=>e),e])&&l(),u().length>0)?d({args:e,resolve:n,reject:i}):(d({args:e,resolve:n,reject:i}),setTimeout(l,s)),t}}}a.d(t,{u:()=>i})},4908(e,t,a){"use strict";function r(){let e=()=>void 0,t=()=>void 0;return{promise:new Promise((a,r)=>{e=a,t=r}),resolve:e,reject:t}}a.d(t,{Y:()=>r})},9974(e,t,a){"use strict";a.d(t,{},{BD:/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,D5:/^(.*)\[([0-9]*)\]$/,Ge:/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/})},2068(e,t,a){"use strict";var r=a(43),n=a(2691),i=a(9322),s=a(7138),o=a(7373);function l(e){if(e&&0!==e.length)return e.reduce((e,{slot:t,value:a})=>{if(66!==t.length)throw new n.NV({size:t.length,targetSize:66,type:"hex"});if(66!==a.length)throw new n.NV({size:a.length,targetSize:66,type:"hex"});return e[t]=a,e},{})}function c(e){if(!e)return;let t={};for(let{address:a,...n}of e){if(!(0,s.P)(a,{strict:!1}))throw new r.M({address:a});if(t[a])throw new i.Hi({address:a});t[a]=function(e){let{balance:t,nonce:a,state:r,stateDiff:n,code:s}=e,c={};if(void 0!==s&&(c.code=s),void 0!==t&&(c.balance=(0,o.cK)(t)),void 0!==a&&(c.nonce=(0,o.cK)(a)),void 0!==r&&(c.state=l(r)),void 0!==n){if(c.state)throw new i.ft;c.stateDiff=l(n)}return c}(n)}return t}a.d(t,{yH:()=>c})},9312(e,t,a){"use strict";a.d(t,{},{A:(e,t,a)=>JSON.stringify(e,(e,a)=>{let r="bigint"==typeof a?a.toString():a;return"function"==typeof t?t(e,r):r},a)})},3291(e,t,a){"use strict";a.d(t,{c:()=>c});var r=a(7946);let n=2n**256n-1n;var i=a(43),s=a(2607),o=a(8211),l=a(7138);function c(e){let{account:t,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,to:d}=e,h=t?(0,r.J)(t):void 0;if(h&&!(0,l.P)(h.address))throw new i.M({address:h.address});if(d&&!(0,l.P)(d))throw new i.M({address:d});if(void 0!==a&&(void 0!==c||void 0!==u))throw new o.n3;if(c&&c>n)throw new s.BG({maxFeePerGas:c});if(u&&c&&u>c)throw new s.lN({maxFeePerGas:c,maxPriorityFeePerGas:u})}},5425(e,t,a){"use strict";var r=a(5923),n=a(3546);function i(e,t="wei"){return(0,n.J)(e,r.eL[t])}a.d(t,{c:()=>i})},8417(e,t,a){"use strict";var r=a(5923),n=a(3546);function i(e,t="wei"){return(0,n.J)(e,r.sz[t])}a.d(t,{Q:()=>i})},3546(e,t,a){"use strict";function r(e,t){let a=e.toString(),r=a.startsWith("-");r&&(a=a.slice(1));let[n,i]=[(a=a.padStart(t,"0")).slice(0,a.length-t),a.slice(a.length-t)];return i=i.replace(/(0+)$/,""),`${r?"-":""}${n||"0"}${i?`.${i}`:""}`}a.d(t,{J:()=>r})},1629(e,t,a){"use strict";let r,n;var i,s=function(e,t,a,r){if("a"===a&&!r)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===a?r:"a"===a?r.call(e):r?r.value:t.get(e)},o=function(e,t,a,r,n){if("m"===r)throw TypeError("Private method is not writable");if("a"===r&&!n)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,a):n?n.value=a:t.set(e,a),a};let l=new Set,c={};function u(){if(n||(n=Object.freeze({register:d,get:h,on:m}),"u"<typeof window))return n;let e=Object.freeze({register:d});try{window.addEventListener("wallet-standard:register-wallet",({detail:t})=>t(e))}catch(e){console.error("wallet-standard:register-wallet event listener could not be added\n",e)}try{window.dispatchEvent(new f(e))}catch(e){console.error("wallet-standard:app-ready event could not be dispatched\n",e)}return n}function d(...e){return(e=e.filter(e=>!l.has(e))).length?(e.forEach(e=>{r=void 0,l.add(e)}),c.register?.forEach(t=>p(()=>t(...e))),function(){e.forEach(e=>{r=void 0,l.delete(e)}),c.unregister?.forEach(t=>p(()=>t(...e)))}):()=>{}}function h(){return r||(r=[...l]),r}function m(e,t){return c[e]?.push(t)||(c[e]=[t]),function(){c[e]=c[e]?.filter(e=>t!==e)}}function p(e){try{e()}catch(e){console.error(e)}}var f=class extends Event{get detail(){return s(this,i,"f")}get type(){return"wallet-standard:app-ready"}constructor(e){super("wallet-standard:app-ready",{bubbles:!1,cancelable:!1,composed:!1}),i.set(this,void 0),o(this,i,e,"f")}preventDefault(){throw Error("preventDefault cannot be called")}stopImmediatePropagation(){throw Error("stopImmediatePropagation cannot be called")}stopPropagation(){throw Error("stopPropagation cannot be called")}};i=new WeakMap,a.d(t,{getWallets:()=>u})},8591(e,t,a){"use strict";a.d(t,{},{t:(...e)=>{}})},6100(e,t,a){"use strict";function r(e,t,a){return"function"==typeof e?e(t):void 0!==e?e:void 0!==a?a:void 0}a.d(t,{vd:()=>i,VK:()=>r,lQ:()=>n.t,zc:()=>s});var n=a(8591);function i(e){return Promise.all(Array.from(e).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}function s(e,t,a){let r,n=new Promise((e,n)=>{r=setTimeout(()=>{let e=Error(`Timed out after ${t}ms`);a?.abort(),n(e)},t),r.unref?.()});return Promise.race([Promise.resolve(e),n]).finally(()=>{clearTimeout(r)})}}},r={};function n(e){var t=r[e];if(void 0!==t)return t.exports;var i=r[e]={exports:{}};return a[e].call(i.exports,i,i.exports,n),i.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,n.t=function(a,r){if(1&r&&(a=this(a)),8&r||"object"==typeof a&&a&&(4&r&&a.__esModule||16&r&&"function"==typeof a.then))return a;var i=Object.create(null);n.r(i);var s={};e=e||[null,t({}),t([]),t(t)];for(var o=2&r&&a;("object"==typeof o||"function"==typeof o)&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach(e=>{s[e]=()=>a[e]});return s.default=()=>a,n.d(i,s),i},n.d=(e,t,a)=>{var r=(t,a)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,[a]:t[r]})};r(t,"get"),r(a,"value")},n.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};(()=>{"use strict";let e,t,a,r,s,o,l,c,u,d,h,m,p;function f(){return"u">typeof window}n.r(i),n.d(i,{Clerk:()=>iE,ClerkAPIResponseError:()=>U,ClerkRuntimeError:()=>q,EmailLinkError:()=>F,EmailLinkErrorCode:()=>L,EmailLinkErrorCodeStatus:()=>W,isClerkAPIResponseError:()=>M,isClerkRuntimeError:()=>O,isEmailLinkError:()=>Q,isKnownError:()=>Z,isMetamaskError:()=>$,isUserLockedError:()=>Y});let g=RegExp("bot|spider|crawl|APIs-Google|AdsBot|Googlebot|mediapartners|Google Favicon|FeedFetcher|Google-Read-Aloud|DuplexWeb-Google|googleweblight|bing|yandex|baidu|duckduck|yahoo|ecosia|ia_archiver|facebook|instagram|pinterest|reddit|slack|twitter|whatsapp|youtube|semrush","i"),b=/^(Cloudflare-Workers|Node\.js|Deno|Bun)\b/i;function y(){if("u">typeof window&&window.navigator)return window.navigator;let e=globalThis;return"function"==typeof e.WorkerGlobalScope&&e.self instanceof e.WorkerGlobalScope&&e.self.navigator&&!b.test(e.self.navigator.userAgent??"")?e.self.navigator:null}function w(){var e;let t=y();return!!t&&!((e=t?.userAgent)&&g.test(e))&&!t?.webdriver}function k(){let e=y();return!!e&&("boolean"!=typeof e.onLine||!!e.onLine)}function v(){return k()&&w()}let _=(e,t,a,r,n)=>{let{notify:i}=n||{},s=e.get(a);s||(s=[],e.set(a,s)),s.push(r),i&&t.has(a)&&r(t.get(a))},x=(e,t,a)=>(e.get(t)||[]).map(e=>e(a)),j=(e,t,a)=>{let r=e.get(t);r&&(a?r.splice(r.indexOf(a)>>>0,1):e.set(t,[]))},z=()=>{let e=new Map,t=new Map,a=new Map;return{on:(...a)=>_(e,t,...a),prioritizedOn:(...e)=>_(a,t,...e),emit:(r,n)=>{t.set(r,n),x(a,r,n),x(e,r,n)},off:(...t)=>j(e,...t),prioritizedOff:(...e)=>j(a,...e),internal:{retrieveListeners:t=>e.get(t)||[]}}},S="status";function I(e){return function(t){let a=t??this;if(!a)throw TypeError(`${e.kind||e.name} type guard requires an error object`);return!!e.kind&&"object"==typeof a&&null!==a&&"constructor"in a&&a.constructor?.kind===e.kind||a instanceof e}}var A,C,E,P=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}]
45
+ `),a.state&&(r+=" state:\n",r+=s(a.state)),a.stateDiff&&(r+=" stateDiff:\n",r+=s(a.stateDiff)),r}," State Override:\n").slice(0,-1)}a.d(t,{Hi:()=>n,ft:()=>i,uj:()=>o})},8211(e,t,a){"use strict";a(5425),a(8417);var r=a(4866);function n(e){let t=Object.entries(e).map(([e,t])=>void 0===t||!1===t?null:[e,t]).filter(Boolean),a=t.reduce((e,[t])=>Math.max(e,t.length),0);return t.map(([e,t])=>` ${`${e}:`.padEnd(a+1)} ${t}`).join("\n")}class i extends r.C{constructor(){super("Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.\nUse `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others.",{name:"FeeConflictError"})}}r.C;class s extends r.C{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",n(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}r.C,r.C,r.C,r.C;class o extends r.C{constructor({blockHash:e,blockNumber:t,blockTag:a,hash:r,index:n}){let i="Transaction";a&&void 0!==n&&(i=`Transaction at block time "${a}" at index "${n}"`),e&&void 0!==n&&(i=`Transaction at block hash "${e}" at index "${n}"`),t&&void 0!==n&&(i=`Transaction at block number "${t}" at index "${n}"`),r&&(i=`Transaction with hash "${r}"`),super(`${i} could not be found.`,{name:"TransactionNotFoundError"})}}class l extends r.C{constructor({hash:e}){super(`Transaction receipt with hash "${e}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class c extends r.C{constructor({receipt:e}){super(`Transaction with hash "${e.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=e}}class u extends r.C{constructor({hash:e}){super(`Timed out while waiting for transaction with hash "${e}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}a.d(t,{Kc:()=>l,Kz:()=>o,Sq:()=>c,Vg:()=>s,WA:()=>u,aO:()=>n,n3:()=>i})},9034(e,t,a){"use strict";a.d(t,{},{I:e=>e,R:e=>e})},4647(e,t,a){"use strict";a.d(t,{n:()=>f});var r=a(8693),n=a(1900),i=a(3879),s=a(5817),o=a(996),l=a(8596),c=a(5578),u=a(5074),d=a(7373);function h(e,t={}){void 0!==t.size&&(0,u.Sl)(e,{size:t.size});let a=(0,d.My)(e,t);return(0,u.ME)(a,t)}var m=a(659),p=a(2968);function f(e,t){let a="string"==typeof t?(0,m.aT)(t):t,f=(0,i.l)(a);if(0===(0,s.E)(a)&&e.length>0)throw new r.O;if((0,s.E)(t)&&32>(0,s.E)(t))throw new r.Iy({data:"string"==typeof t?t:(0,d.My)(t),params:e,size:(0,s.E)(t)});let b=0,y=[];for(let t=0;t<e.length;++t){let a=e[t];f.setPosition(b);let[i,s]=function e(t,a,{staticPosition:i}){let s=(0,p.k)(a.type);if(s){let[r,n]=s;return function(t,a,{length:r,staticPosition:n}){if(!r){let r=n+h(t.readBytes(32)),i=r+32;t.setPosition(r);let s=h(t.readBytes(32)),o=g(a),l=0,c=[];for(let r=0;r<s;++r){t.setPosition(i+(o?32*r:l));let[n,s]=e(t,a,{staticPosition:i});l+=s,c.push(n)}return t.setPosition(n+32),[c,32]}if(g(a)){let i=n+h(t.readBytes(32)),s=[];for(let n=0;n<r;++n){t.setPosition(i+32*n);let[r]=e(t,a,{staticPosition:i});s.push(r)}return t.setPosition(n+32),[s,32]}let i=0,s=[];for(let o=0;o<r;++o){let[r,o]=e(t,a,{staticPosition:n+i});i+=o,s.push(r)}return[s,i]}(t,{...a,type:n},{length:r,staticPosition:i})}if("tuple"===a.type)return function(t,a,{staticPosition:r}){let n=0===a.components.length||a.components.some(({name:e})=>!e),i=n?[]:{},s=0;if(g(a)){let o=r+h(t.readBytes(32));for(let r=0;r<a.components.length;++r){let l=a.components[r];t.setPosition(o+s);let[c,u]=e(t,l,{staticPosition:o});s+=u,i[n?r:l?.name]=c}return t.setPosition(r+32),[i,32]}for(let o=0;o<a.components.length;++o){let l=a.components[o],[c,u]=e(t,l,{staticPosition:r});i[n?o:l?.name]=c,s+=u}return[i,s]}(t,a,{staticPosition:i});if("address"===a.type){let e;return e=t.readBytes(32),[(0,n.o)((0,d.My)((0,o.A1)(e,-20))),32]}if("bool"===a.type)return[function(e,t={}){let a=e;if(void 0!==t.size&&((0,u.Sl)(a,{size:t.size}),a=(0,l.B)(a)),a.length>1||a[0]>1)throw new c.xO(a);return!!a[0]}(t.readBytes(32),{size:32}),32];if(a.type.startsWith("bytes"))return function(e,t,{staticPosition:a}){let[r,n]=t.type.split("bytes");if(!n){let t=h(e.readBytes(32));e.setPosition(a+t);let r=h(e.readBytes(32));if(0===r)return e.setPosition(a+32),["0x",32];let n=e.readBytes(r);return e.setPosition(a+32),[(0,d.My)(n),32]}return[(0,d.My)(e.readBytes(Number.parseInt(n,10),32)),32]}(t,a,{staticPosition:i});if(a.type.startsWith("uint")||a.type.startsWith("int")){var m,f;let e,r,n;return m=t,e=(f=a).type.startsWith("int"),r=Number.parseInt(f.type.split("int")[1]||"256",10),n=m.readBytes(32),[r>48?function(e,t={}){void 0!==t.size&&(0,u.Sl)(e,{size:t.size});let a=(0,d.My)(e,t);return(0,u.uU)(a,t)}(n,{signed:e}):h(n,{signed:e}),32]}if("string"===a.type)return function(e,{staticPosition:t}){let a=h(e.readBytes(32));e.setPosition(t+a);let r=h(e.readBytes(32));if(0===r)return e.setPosition(t+32),["",32];let n=e.readBytes(r,32),i=function(e,t={}){let a=e;return void 0!==t.size&&((0,u.Sl)(a,{size:t.size}),a=(0,l.B)(a,{dir:"right"})),new TextDecoder().decode(a)}((0,l.B)(n));return e.setPosition(t+32),[i,32]}(t,{staticPosition:i});throw new r.j(a.type,{docsPath:"/docs/contract/decodeAbiParameters"})}(f,a,{staticPosition:0});b+=s,y.push(i)}return y}function g(e){let{type:t}=e;if("string"===t||"bytes"===t||t.endsWith("[]"))return!0;if("tuple"===t)return e.components?.some(g);let a=(0,p.k)(e.type);return!!(a&&g({...e,type:a[1]}))}},6769(e,t,a){"use strict";var r=a(7760),n=a(8693),i=a(996),s=a(2764),o=a(4647),l=a(1988);function c(e){let{abi:t,data:a}=e,c=(0,i.di)(a,0,4);if("0x"===c)throw new n.O;let u=[...t||[],r.Mc,r.J9].find(e=>"error"===e.type&&c===(0,s.V)((0,l.B)(e)));if(!u)throw new n.Wq(c,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:u,args:"inputs"in u&&u.inputs&&u.inputs.length>0?(0,o.n)(u.inputs,(0,i.di)(a,4)):void 0,errorName:u.name}}a.d(t,{W:()=>c})},7276(e,t,a){"use strict";var r=a(8693),n=a(996),i=a(2764),s=a(4647),o=a(1988);function l(e){let{abi:t,data:a}=e,l=(0,n.di)(a,0,4),c=t.find(e=>"function"===e.type&&l===(0,i.V)((0,o.B)(e)));if(!c)throw new r.EB(l,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:c.name,args:"inputs"in c&&c.inputs&&c.inputs.length>0?(0,s.n)(c.inputs,(0,n.di)(a,4)):void 0}}a.d(t,{J:()=>l})},5769(e,t,a){"use strict";var r=a(8693),n=a(4647),i=a(5571);let s="/docs/contract/decodeFunctionResult";function o(e){let{abi:t,args:a,functionName:o,data:l}=e,c=t[0];if(o){let e=(0,i.iY)({abi:t,args:a,name:o});if(!e)throw new r.Iz(o,{docsPath:s});c=e}if("function"!==c.type)throw new r.Iz(void 0,{docsPath:s});if(!c.outputs)throw new r.MR(c.name,{docsPath:s});let u=(0,n.n)(c.outputs,l);return u&&u.length>1?u:u&&1===u.length?u[0]:void 0}a.d(t,{e:()=>o})},2968(e,t,a){"use strict";var r=a(8693),n=a(43),i=a(4866),s=a(5578),o=a(7138),l=a(9284),c=a(6207),u=a(5817),d=a(996),h=a(7373),m=a(9974);function p(e,t){if(e.length!==t.length)throw new r.YE({expectedLength:e.length,givenLength:t.length});let a=f(function({params:e,values:t}){let a=[];for(let p=0;p<e.length;p++)a.push(function e({param:t,value:a}){let p=g(t.type);if(p){let[n,i]=p;return function(t,{length:a,param:n}){let i=null===a;if(!Array.isArray(t))throw new r.dm(t);if(!i&&t.length!==a)throw new r.Nc({expectedLength:a,givenLength:t.length,type:`${n.type}[${a}]`});let s=!1,o=[];for(let a=0;a<t.length;a++){let r=e({param:n,value:t[a]});r.dynamic&&(s=!0),o.push(r)}if(i||s){let e=f(o);if(i){let t=(0,h.cK)(o.length,{size:32});return{dynamic:!0,encoded:o.length>0?(0,l.xW)([t,e]):t}}if(s)return{dynamic:!0,encoded:e}}return{dynamic:!1,encoded:(0,l.xW)(o.map(({encoded:e})=>e))}}(a,{length:n,param:{...t,type:i}})}if("tuple"===t.type)return function(t,{param:a}){let r=!1,n=[];for(let i=0;i<a.components.length;i++){let s=a.components[i],o=Array.isArray(t)?i:s.name,l=e({param:s,value:t[o]});n.push(l),l.dynamic&&(r=!0)}return{dynamic:r,encoded:r?f(n):(0,l.xW)(n.map(({encoded:e})=>e))}}(a,{param:t});if("address"===t.type){var b=a;if(!(0,o.P)(b))throw new n.M({address:b});return{dynamic:!1,encoded:(0,c.db)(b.toLowerCase())}}if("bool"===t.type){var y=a;if("boolean"!=typeof y)throw new i.C(`Invalid boolean value: "${y}" (type: ${typeof y}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:(0,c.db)((0,h.$P)(y))}}if(t.type.startsWith("uint")||t.type.startsWith("int")){let e=t.type.startsWith("int"),[,,r="256"]=m.Ge.exec(t.type)??[];return function(e,{signed:t,size:a=256}){if("number"==typeof a){let r=2n**(BigInt(a)-(t?1n:0n))-1n,n=t?-r-1n:0n;if(e>r||e<n)throw new s.Ty({max:r.toString(),min:n.toString(),signed:t,size:a/8,value:e.toString()})}return{dynamic:!1,encoded:(0,h.cK)(e,{size:32,signed:t})}}(a,{signed:e,size:Number(r)})}if(t.type.startsWith("bytes"))return function(e,{param:t}){let[,a]=t.type.split("bytes"),n=(0,u.E)(e);if(!a){let t=e;return n%32!=0&&(t=(0,c.db)(t,{dir:"right",size:32*Math.ceil((e.length-2)/2/32)})),{dynamic:!0,encoded:(0,l.xW)([(0,c.db)((0,h.cK)(n,{size:32})),t])}}if(n!==Number.parseInt(a,10))throw new r.gH({expectedSize:Number.parseInt(a,10),value:e});return{dynamic:!1,encoded:(0,c.db)(e,{dir:"right"})}}(a,{param:t});if("string"===t.type){var w=a;let e=(0,h.i3)(w),t=Math.ceil((0,u.E)(e)/32),r=[];for(let a=0;a<t;a++)r.push((0,c.db)((0,d.di)(e,32*a,(a+1)*32),{dir:"right"}));return{dynamic:!0,encoded:(0,l.xW)([(0,c.db)((0,h.cK)((0,u.E)(e),{size:32})),...r])}}throw new r.nK(t.type,{docsPath:"/docs/contract/encodeAbiParameters"})}({param:e[p],value:t[p]}));return a}({params:e,values:t}));return 0===a.length?"0x":a}function f(e){let t=0;for(let a=0;a<e.length;a++){let{dynamic:r,encoded:n}=e[a];r?t+=32:t+=(0,u.E)(n)}let a=[],r=[],n=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:o}=e[i];s?(a.push((0,h.cK)(t+n,{size:32})),r.push(o),n+=(0,u.E)(o)):a.push(o)}return(0,l.xW)([...a,...r])}function g(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}a.d(t,{h:()=>p,k:()=>g})},8627(e,t,a){"use strict";var r=a(8693),n=a(9284),i=a(2968);let s="/docs/contract/encodeDeployData";function o(e){let{abi:t,args:a,bytecode:o}=e;if(!a||0===a.length)return o;let l=t.find(e=>"type"in e&&"constructor"===e.type);if(!l)throw new r.YW({docsPath:s});if(!("inputs"in l)||!l.inputs||0===l.inputs.length)throw new r.YF({docsPath:s});let c=(0,i.h)(l.inputs,a);return(0,n.aP)([o,c])}a.d(t,{m:()=>o})},9609(e,t,a){"use strict";a.d(t,{p:()=>u});var r=a(9284),n=a(2968),i=a(8693),s=a(2764),o=a(1988),l=a(5571);let c="/docs/contract/encodeFunctionData";function u(e){let{args:t}=e,{abi:a,functionName:u}=1===e.abi.length&&e.functionName?.startsWith("0x")?e:function(e){let{abi:t,args:a,functionName:r}=e,n=t[0];if(r){let e=(0,l.iY)({abi:t,args:a,name:r});if(!e)throw new i.Iz(r,{docsPath:c});n=e}if("function"!==n.type)throw new i.Iz(void 0,{docsPath:c});return{abi:[n],functionName:(0,s.V)((0,o.B)(n))}}(e),d=a[0],h="inputs"in d&&d.inputs?(0,n.h)(d.inputs,t??[]):void 0;return(0,r.aP)([u,h??"0x"])}},1988(e,t,a){"use strict";a.d(t,{A:()=>i,B:()=>n});var r=a(8693);function n(e,{includeName:t=!1}={}){if("function"!==e.type&&"event"!==e.type&&"error"!==e.type)throw new r.d_(e.type);return`${e.name}(${i(e.inputs,{includeName:t})})`}function i(e,{includeName:t=!1}={}){return e?e.map(e=>(function(e,{includeName:t}){return e.type.startsWith("tuple")?`(${i(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")})(e,{includeName:t})).join(t?", ":","):""}},5571(e,t,a){"use strict";var r=a(8693),n=a(7443),i=a(7138),s=a(5028),o=a(2764);function l(e){let t,{abi:a,args:l=[],name:c}=e,u=(0,n.q)(c,{strict:!1}),d=a.filter(e=>u?"function"===e.type?(0,o.V)(e)===c:"event"===e.type&&(0,s.h)(e)===c:"name"in e&&e.name===c);if(0!==d.length){if(1===d.length)return d[0];for(let e of d){if("inputs"in e){if(!l||0===l.length){if(!e.inputs||0===e.inputs.length)return e;continue}if(e.inputs&&0!==e.inputs.length&&e.inputs.length===l.length&&l.every((t,a)=>{let r="inputs"in e&&e.inputs[a];return!!r&&function e(t,a){let r=typeof t,n=a.type;switch(n){case"address":return(0,i.P)(t,{strict:!1});case"bool":return"boolean"===r;case"function":case"string":return"string"===r;default:if("tuple"===n&&"components"in a)return Object.values(a.components).every((a,r)=>e(Object.values(t)[r],a));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n))return"number"===r||"bigint"===r;if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n))return"string"===r||t instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n))return Array.isArray(t)&&t.every(t=>e(t,{...a,type:n.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}(t,r)})){if(t&&"inputs"in t&&t.inputs){let a=function e(t,a,r){for(let n in t){let s=t[n],o=a[n];if("tuple"===s.type&&"tuple"===o.type&&"components"in s&&"components"in o)return e(s.components,o.components,r[n]);let l=[s.type,o.type];if(l.includes("address")&&l.includes("bytes20")||(l.includes("address")&&l.includes("string")||l.includes("address")&&l.includes("bytes"))&&(0,i.P)(r[n],{strict:!1}))return l}}(e.inputs,t.inputs,l);if(a)throw new r.nM({abiItem:e,type:a[0]},{abiItem:t,type:a[1]})}t=e}}}return t||d[0]}}a.d(t,{iY:()=>l})},1900(e,t,a){"use strict";a.d(t,{b:()=>u,o:()=>c});var r=a(43),n=a(659),i=a(8477),s=a(1476),o=a(7138);let l=new s.A(8192);function c(e,t){if(l.has(`${e}.${t}`))return l.get(`${e}.${t}`);let a=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),r=(0,i.S)((0,n.Af)(a),"bytes"),s=(t?a.substring(`${t}0x`.length):a).split("");for(let e=0;e<40;e+=2)r[e>>1]>>4>=8&&s[e]&&(s[e]=s[e].toUpperCase()),(15&r[e>>1])>=8&&s[e+1]&&(s[e+1]=s[e+1].toUpperCase());let o=`0x${s.join("")}`;return l.set(`${e}.${t}`,o),o}function u(e,t){if(!(0,o.P)(e,{strict:!1}))throw new r.M({address:e});return c(e,t)}},7138(e,t,a){"use strict";a.d(t,{P:()=>o});var r=a(1476),n=a(1900);let i=/^0x[a-fA-F0-9]{40}$/,s=new r.A(8192);function o(e,t){let{strict:a=!0}=t??{},r=`${e}.${a}`;if(s.has(r))return s.get(r);let o=!!i.test(e)&&(e.toLowerCase()===e||!a||(0,n.o)(e)===e);return s.set(r,o),o}},5544(e,t,a){"use strict";var r=a(43),n=a(7138);function i(e,t){if(!(0,n.P)(e,{strict:!1}))throw new r.M({address:e});if(!(0,n.P)(t,{strict:!1}))throw new r.M({address:t});return e.toLowerCase()===t.toLowerCase()}a.d(t,{h:()=>i})},3992(e,t,a){"use strict";a.d(t,{offchainLookup:()=>w,offchainLookupSignature:()=>b});var r=a(4547),n=a(9312),i=a(4866),s=a(9034);class o extends i.C{constructor({callbackSelector:e,cause:t,data:a,extraData:r,sender:n,urls:i}){super(t.shortMessage||"An error occurred while fetching for an offchain result.",{cause:t,metaMessages:[...t.metaMessages||[],t.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map(e=>` ${(0,s.I)(e)}`)],` Sender: ${n}`,` Data: ${a}`,` Callback selector: ${e}`,` Extra data: ${r}`].flat(),name:"OffchainLookupError"})}}class l extends i.C{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${(0,s.I)(t)}`,`Response: ${(0,n.A)(e)}`],name:"OffchainLookupResponseMalformedError"})}}class c extends i.C{constructor({sender:e,to:t}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${t}`,`OffchainLookup sender address: ${e}`],name:"OffchainLookupSenderMismatchError"})}}var u=a(1958),d=a(6769),h=a(2968),m=a(5544),p=a(9284),f=a(7443),g=a(5701);let b="0x556f1830",y={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function w(e,{blockNumber:t,blockTag:a,data:n,to:i}){let{args:s}=(0,d.W)({data:n,abi:[y]}),[l,u,f,b,v]=s,{ccipRead:_}=e,x=_&&"function"==typeof _?.request?_.request:k;try{if(!(0,m.h)(i,l))throw new c({sender:l,to:i});let n=u.includes(g.J)?await (0,g.X)({data:f,ccipRequest:x}):await x({data:f,sender:l,urls:u}),{data:s}=await (0,r.T)(e,{blockNumber:t,blockTag:a,data:(0,p.xW)([b,(0,h.h)([{type:"bytes"},{type:"bytes"}],[n,v])]),to:i});return s}catch(e){throw new o({callbackSelector:b,cause:e,data:n,extraData:v,sender:l,urls:u})}}async function k({data:e,sender:t,urls:a}){let r=Error("An unknown error occurred.");for(let i=0;i<a.length;i++){let s=a[i],o=s.includes("{data}")?"GET":"POST",c="POST"===o?{data:e,sender:t}:void 0,d="POST"===o?{"Content-Type":"application/json"}:{};try{let a,i=await fetch(s.replace("{sender}",t.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:d,method:o});if(a=i.headers.get("Content-Type")?.startsWith("application/json")?(await i.json()).data:await i.text(),!i.ok){r=new u.Ci({body:c,details:a?.error?(0,n.A)(a.error):i.statusText,headers:i.headers,status:i.status,url:s});continue}if(!(0,f.q)(a)){r=new l({result:a,url:s});continue}return a}catch(e){r=new u.Ci({body:c,details:e.message,url:s})}}throw r}},7042(e,t,a){"use strict";var r=a(4542);function n({blockNumber:e,chain:t,contract:a}){let i=t?.contracts?.[a];if(!i)throw new r.rj({chain:t,contract:{name:a}});if(e&&i.blockCreated&&i.blockCreated>e)throw new r.rj({blockNumber:e,chain:t,contract:{name:a,blockCreated:i.blockCreated}});return i.address}a.d(t,{M:()=>n})},3879(e,t,a){"use strict";var r=a(1857);let n={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:1/0,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new r.hX({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new r.SK({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new r.B4({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new r.B4({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let a=t??this.position;return this.assertPosition(a+e-1),this.bytes.subarray(a,a+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,255&e),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let a=this.inspectBytes(e);return this.position+=t??e,a},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===1/0)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function i(e,{recursiveReadLimit:t=8192}={}){let a=Object.create(n);return a.bytes=e,a.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),a.positionReadCount=new Map,a.recursiveReadLimit=t,a}a.d(t,{l:()=>i})},9284(e,t,a){"use strict";function r(e){return"string"==typeof e[0]?n(e):function(e){let t=0;for(let a of e)t+=a.length;let a=new Uint8Array(t),r=0;for(let t of e)a.set(t,r),r+=t.length;return a}(e)}function n(e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}a.d(t,{aP:()=>n,xW:()=>r})},7443(e,t,a){"use strict";function r(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}a.d(t,{q:()=>r})},6207(e,t,a){"use strict";var r=a(2691);function n(e,{dir:t,size:a=32}={}){return"string"==typeof e?i(e,{dir:t,size:a}):function(e,{dir:t,size:a=32}={}){if(null===a)return e;if(e.length>a)throw new r.Fl({size:e.length,targetSize:a,type:"bytes"});let n=new Uint8Array(a);for(let r=0;r<a;r++){let i="right"===t;n[i?r:a-r-1]=e[i?r:e.length-r-1]}return n}(e,{dir:t,size:a})}function i(e,{dir:t,size:a=32}={}){if(null===a)return e;let n=e.replace("0x","");if(n.length>2*a)throw new r.Fl({size:Math.ceil(n.length/2),targetSize:a,type:"hex"});return`0x${n["right"===t?"padEnd":"padStart"](2*a,"0")}`}a.d(t,{db:()=>i,eV:()=>n})},5817(e,t,a){"use strict";var r=a(7443);function n(e){return(0,r.q)(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}a.d(t,{E:()=>n})},996(e,t,a){"use strict";var r=a(2691),n=a(7443),i=a(5817);function s(e,t,a,{strict:r}={}){return(0,n.q)(e,{strict:!1})?u(e,t,a,{strict:r}):c(e,t,a,{strict:r})}function o(e,t){if("number"==typeof t&&t>0&&t>(0,i.E)(e)-1)throw new r.ii({offset:t,position:"start",size:(0,i.E)(e)})}function l(e,t,a){if("number"==typeof t&&"number"==typeof a&&(0,i.E)(e)!==a-t)throw new r.ii({offset:a,position:"end",size:(0,i.E)(e)})}function c(e,t,a,{strict:r}={}){o(e,t);let n=e.slice(t,a);return r&&l(n,t,a),n}function u(e,t,a,{strict:r}={}){o(e,t);let n=`0x${e.replace("0x","").slice((t??0)*2,(a??e.length)*2)}`;return r&&l(n,t,a),n}a.d(t,{A1:()=>c,di:()=>s,iN:()=>u})},8596(e,t,a){"use strict";function r(e,{dir:t="left"}={}){let a="string"==typeof e?e.replace("0x",""):e,n=0;for(let e=0;e<a.length-1;e++)if("0"===a["left"===t?e:a.length-e-1].toString())n++;else break;return(a="left"===t?a.slice(n):a.slice(0,a.length-n),"string"==typeof e)?(1===a.length&&"right"===t&&(a=`${a}0`),`0x${a.length%2==1?`0${a}`:a}`):a}a.d(t,{B:()=>r})},5074(e,t,a){"use strict";a.d(t,{IQ:()=>d,ME:()=>u,Nx:()=>c,Sl:()=>o,uU:()=>l});var r=a(5578),n=a(5817),i=a(8596),s=a(659);function o(e,{size:t}){if((0,n.E)(e)>t)throw new r.u({givenSize:(0,n.E)(e),maxSize:t})}function l(e,t={}){let{signed:a}=t;t.size&&o(e,{size:t.size});let r=BigInt(e);if(!a)return r;let n=(e.length-2)/2;return r<=(1n<<8n*BigInt(n)-1n)-1n?r:r-BigInt(`0x${"f".padStart(2*n,"f")}`)-1n}function c(e,t={}){let a=e;if(t.size&&(o(a,{size:t.size}),a=(0,i.B)(a)),"0x00"===(0,i.B)(a))return!1;if("0x01"===(0,i.B)(a))return!0;throw new r.H2(a)}function u(e,t={}){return Number(l(e,t))}function d(e,t={}){let a=(0,s.aT)(e);return t.size&&(o(a,{size:t.size}),a=(0,i.B)(a,{dir:"right"})),new TextDecoder().decode(a)}},659(e,t,a){"use strict";a.d(t,{Af:()=>h,ZJ:()=>c,aT:()=>d});var r=a(4866),n=a(7443),i=a(6207),s=a(5074),o=a(7373);let l=new TextEncoder;function c(e,t={}){var a,r;return"number"==typeof e||"bigint"==typeof e?(a=e,r=t,d((0,o.cK)(a,r))):"boolean"==typeof e?function(e,t={}){let a=new Uint8Array(1);return(a[0]=Number(e),"number"==typeof t.size)?((0,s.Sl)(a,{size:t.size}),(0,i.eV)(a,{size:t.size})):a}(e,t):(0,n.q)(e)?d(e,t):h(e,t)}function u(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function d(e,t={}){let a=e;t.size&&((0,s.Sl)(a,{size:t.size}),a=(0,i.eV)(a,{dir:"right",size:t.size}));let n=a.slice(2);n.length%2&&(n=`0${n}`);let o=n.length/2,l=new Uint8Array(o);for(let e=0,t=0;e<o;e++){let a=u(n.charCodeAt(t++)),i=u(n.charCodeAt(t++));if(void 0===a||void 0===i)throw new r.C(`Invalid byte sequence ("${n[t-2]}${n[t-1]}" in "${n}").`);l[e]=16*a+i}return l}function h(e,t={}){let a=l.encode(e);return"number"==typeof t.size?((0,s.Sl)(a,{size:t.size}),(0,i.eV)(a,{dir:"right",size:t.size})):a}},7373(e,t,a){"use strict";a.d(t,{$P:()=>l,My:()=>c,cK:()=>u,i3:()=>h,nj:()=>o});var r=a(5578),n=a(6207),i=a(5074);let s=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function o(e,t={}){return"number"==typeof e||"bigint"==typeof e?u(e,t):"string"==typeof e?h(e,t):"boolean"==typeof e?l(e,t):c(e,t)}function l(e,t={}){let a=`0x${Number(e)}`;return"number"==typeof t.size?((0,i.Sl)(a,{size:t.size}),(0,n.eV)(a,{size:t.size})):a}function c(e,t={}){let a="";for(let t=0;t<e.length;t++)a+=s[e[t]];let r=`0x${a}`;return"number"==typeof t.size?((0,i.Sl)(r,{size:t.size}),(0,n.eV)(r,{dir:"right",size:t.size})):r}function u(e,t={}){let a,{signed:i,size:s}=t,o=BigInt(e);s?a=i?(1n<<8n*BigInt(s)-1n)-1n:2n**(8n*BigInt(s))-1n:"number"==typeof e&&(a=BigInt(Number.MAX_SAFE_INTEGER));let l="bigint"==typeof a&&i?-a-1n:0;if(a&&o>a||o<l){let t="bigint"==typeof e?"n":"";throw new r.Ty({max:a?`${a}${t}`:void 0,min:`${l}${t}`,signed:i,size:s,value:`${e}${t}`})}let c=`0x${(i&&o<0?(1n<<BigInt(8*s))+BigInt(o):o).toString(16)}`;return s?(0,n.eV)(c,{size:s}):c}let d=new TextEncoder;function h(e,t={}){return c(d.encode(e),t)}},5701(e,t,a){"use strict";a.d(t,{X:()=>g,J:()=>f});var r=a(7674),n=a(7760),i=a(7276),s=a(8693),o=a(9284),l=a(2764),c=a(2968),u=a(1988),d=a(5571);let h="/docs/contract/encodeErrorResult";function m(e){let{abi:t,errorName:a,args:r}=e,n=t[0];if(a){let e=(0,d.iY)({abi:t,args:r,name:a});if(!e)throw new s.yy(a,{docsPath:h});n=e}if("error"!==n.type)throw new s.yy(void 0,{docsPath:h});let i=(0,u.B)(n),m=(0,l.V)(i),p="0x";if(r&&r.length>0){if(!n.inputs)throw new s.ZP(n.name,{docsPath:h});p=(0,c.h)(n.inputs,r)}return(0,o.aP)([m,p])}let p="/docs/contract/encodeFunctionResult",f="x-batch-gateway:true";async function g(e){let{data:t,ccipRequest:a}=e,{args:[o]}=(0,i.J)({abi:r.b2,data:t}),l=[],u=[];return await Promise.all(o.map(async(e,t)=>{try{u[t]=e.urls.includes(f)?await g({data:e.data,ccipRequest:a}):await a(e),l[t]=!1}catch(e){var i;l[t]=!0,u[t]="HttpRequestError"===(i=e).name&&i.status?m({abi:r.b2,errorName:"HttpError",args:[i.status,i.shortMessage]}):m({abi:[n.Mc],errorName:"Error",args:["shortMessage"in i?i.shortMessage:i.message]})}})),function(e){let{abi:t,functionName:a,result:r}=e,n=t[0];if(a){let e=(0,d.iY)({abi:t,name:a});if(!e)throw new s.Iz(a,{docsPath:p});n=e}if("function"!==n.type)throw new s.Iz(void 0,{docsPath:p});if(!n.outputs)throw new s.MR(n.name,{docsPath:p});let i=(()=>{if(0===n.outputs.length)return[];if(1===n.outputs.length)return[r];if(Array.isArray(r))return r;throw new s.dm(r)})();return(0,c.h)(n.outputs,i)}({abi:r.b2,functionName:"query",result:[l,u]})}},7047(e,t,a){"use strict";var r=a(4723),n=a(2607),i=a(4895);function s(e,{docsPath:t,...a}){let o,l=(o=(0,i.l)(e,a))instanceof n.RM?e:o;return new r.zX(l,{docsPath:t,...a})}a.d(t,{d:()=>s})},4895(e,t,a){"use strict";var r=a(4866),n=a(2607);function i(e,t){let a=(e.details||"").toLowerCase(),i=e instanceof r.C?e.walk(e=>e?.code===n.A7.code):e;return i instanceof r.C?new n.A7({cause:e,message:i.details}):n.A7.nodeMessage.test(a)?new n.A7({cause:e,message:e.details}):n.BG.nodeMessage.test(a)?new n.BG({cause:e,maxFeePerGas:t?.maxFeePerGas}):n.jj.nodeMessage.test(a)?new n.jj({cause:e,maxFeePerGas:t?.maxFeePerGas}):n.K0.nodeMessage.test(a)?new n.K0({cause:e,nonce:t?.nonce}):n.Oh.nodeMessage.test(a)?new n.Oh({cause:e,nonce:t?.nonce}):n.vW.nodeMessage.test(a)?new n.vW({cause:e,nonce:t?.nonce}):n.k5.nodeMessage.test(a)?new n.k5({cause:e}):n.lY.nodeMessage.test(a)?new n.lY({cause:e,gas:t?.gas}):n.Fo.nodeMessage.test(a)?new n.Fo({cause:e,gas:t?.gas}):n.uC.nodeMessage.test(a)?new n.uC({cause:e}):n.lN.nodeMessage.test(a)?new n.lN({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas}):new n.RM({cause:e})}a.d(t,{l:()=>i})},8608(e,t,a){"use strict";function r(e,{format:t}){if(!t)return{};let a={};return!function t(r){for(let n of Object.keys(r))n in e&&(a[n]=e[n]),r[n]&&"object"==typeof r[n]&&!Array.isArray(r[n])&&t(r[n])}(t(e||{})),a}a.d(t,{o:()=>r})},2292(e,t,a){"use strict";var r=a(7373);let n={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function i(e,t){let a={};return void 0!==e.authorizationList&&(a.authorizationList=e.authorizationList.map(e=>({address:e.address,r:e.r?(0,r.cK)(BigInt(e.r)):e.r,s:e.s?(0,r.cK)(BigInt(e.s)):e.s,chainId:(0,r.cK)(e.chainId),nonce:(0,r.cK)(e.nonce),...void 0!==e.yParity?{yParity:(0,r.cK)(e.yParity)}:{},...void 0!==e.v&&void 0===e.yParity?{v:(0,r.cK)(e.v)}:{}}))),void 0!==e.accessList&&(a.accessList=e.accessList),void 0!==e.blobVersionedHashes&&(a.blobVersionedHashes=e.blobVersionedHashes),void 0!==e.blobs&&("string"!=typeof e.blobs[0]?a.blobs=e.blobs.map(e=>(0,r.My)(e)):a.blobs=e.blobs),void 0!==e.data&&(a.data=e.data),e.account&&(a.from=e.account.address),void 0!==e.from&&(a.from=e.from),void 0!==e.gas&&(a.gas=(0,r.cK)(e.gas)),void 0!==e.gasPrice&&(a.gasPrice=(0,r.cK)(e.gasPrice)),void 0!==e.maxFeePerBlobGas&&(a.maxFeePerBlobGas=(0,r.cK)(e.maxFeePerBlobGas)),void 0!==e.maxFeePerGas&&(a.maxFeePerGas=(0,r.cK)(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(a.maxPriorityFeePerGas=(0,r.cK)(e.maxPriorityFeePerGas)),void 0!==e.nonce&&(a.nonce=(0,r.cK)(e.nonce)),void 0!==e.to&&(a.to=e.to),void 0!==e.type&&(a.type=n[e.type]),void 0!==e.value&&(a.value=(0,r.cK)(e.value)),a}a.d(t,{Bv:()=>i})},8477(e,t,a){"use strict";var r=a(2645),n=a(7443),i=a(659),s=a(7373);function o(e,t){let a=(0,r.lY)((0,n.q)(e,{strict:!1})?(0,i.ZJ)(e):e);return"bytes"===(t||"hex")?a:(0,s.nj)(a)}a.d(t,{S:()=>o})},5028(e,t,a){"use strict";let r=a(7780).k;a.d(t,{},{h:r})},2764(e,t,a){"use strict";var r=a(996),n=a(7780);a.d(t,{},{V:e=>(0,r.di)((0,n.k)(e),0,4)})},7780(e,t,a){"use strict";a.d(t,{k:()=>c});var r=a(659),n=a(8477),i=a(4339);let s=/^tuple(?<array>(\[(\d*)\])*)$/;function o(e){let t="",a=e.length;for(let r=0;r<a;r++)t+=function e(t){let a=t.type;if(s.test(t.type)&&"components"in t){a="(";let r=t.components.length;for(let n=0;n<r;n++)a+=e(t.components[n]),n<r-1&&(a+=", ");let n=(0,i.Yv)(s,t.type);return a+=`)${n?.array??""}`,e({...t,type:a})}return("indexed"in t&&t.indexed&&(a=`${a} indexed`),t.name)?`${a} ${t.name}`:a}(e[r]),r!==a-1&&(t+=", ");return t}var l=a(4866);function c(e){var t;return t=function(e){let t=!0,a="",r=0,n="",i=!1;for(let s=0;s<e.length;s++){let o=e[s];if(["(",")",","].includes(o)&&(t=!0),"("===o&&r++,")"===o&&r--,t){if(0===r){if(" "===o&&["event","function",""].includes(n))n="";else if(n+=o,")"===o){i=!0;break}continue}if(" "===o){","!==e[s-1]&&","!==a&&",("!==a&&(a="",t=!1);continue}n+=o,a+=o}}if(!i)throw new l.C("Unable to normalize signature.");return n}((()=>"string"==typeof e?e:"function"===e.type?`function ${e.name}(${o(e.inputs)})${e.stateMutability&&"nonpayable"!==e.stateMutability?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${o(e.outputs)})`:""}`:"event"===e.type?`event ${e.name}(${o(e.inputs)})`:"error"===e.type?`error ${e.name}(${o(e.inputs)})`:"constructor"===e.type?`constructor(${o(e.inputs)})${"payable"===e.stateMutability?" payable":""}`:"fallback"===e.type?`fallback() external${"payable"===e.stateMutability?" payable":""}`:"receive() external payable")()),(0,n.S)((0,r.ZJ)(t))}},1476(e,t,a){"use strict";class r extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let e=this.keys().next().value;e&&this.delete(e)}return this}}a.d(t,{A:()=>r})},6182(e,t,a){"use strict";var r=a(4908);let n=new Map;function i({fn:e,id:t,shouldSplitBatch:a,wait:s=0,sort:o}){let l=async()=>{let t=u();c();let a=t.map(({args:e})=>e);0!==a.length&&e(a).then(e=>{o&&Array.isArray(e)&&e.sort(o);for(let a=0;a<t.length;a++){let{resolve:r}=t[a];r?.([e[a],e])}}).catch(e=>{for(let a=0;a<t.length;a++){let{reject:r}=t[a];r?.(e)}})},c=()=>n.delete(t),u=()=>n.get(t)||[],d=e=>n.set(t,[...u(),e]);return{flush:c,async schedule(e){let{promise:t,resolve:n,reject:i}=(0,r.Y)();return(a?.([...u().map(({args:e})=>e),e])&&l(),u().length>0)?d({args:e,resolve:n,reject:i}):(d({args:e,resolve:n,reject:i}),setTimeout(l,s)),t}}}a.d(t,{u:()=>i})},4908(e,t,a){"use strict";function r(){let e=()=>void 0,t=()=>void 0;return{promise:new Promise((a,r)=>{e=a,t=r}),resolve:e,reject:t}}a.d(t,{Y:()=>r})},9974(e,t,a){"use strict";a.d(t,{},{BD:/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,D5:/^(.*)\[([0-9]*)\]$/,Ge:/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/})},2068(e,t,a){"use strict";var r=a(43),n=a(2691),i=a(9322),s=a(7138),o=a(7373);function l(e){if(e&&0!==e.length)return e.reduce((e,{slot:t,value:a})=>{if(66!==t.length)throw new n.NV({size:t.length,targetSize:66,type:"hex"});if(66!==a.length)throw new n.NV({size:a.length,targetSize:66,type:"hex"});return e[t]=a,e},{})}function c(e){if(!e)return;let t={};for(let{address:a,...n}of e){if(!(0,s.P)(a,{strict:!1}))throw new r.M({address:a});if(t[a])throw new i.Hi({address:a});t[a]=function(e){let{balance:t,nonce:a,state:r,stateDiff:n,code:s}=e,c={};if(void 0!==s&&(c.code=s),void 0!==t&&(c.balance=(0,o.cK)(t)),void 0!==a&&(c.nonce=(0,o.cK)(a)),void 0!==r&&(c.state=l(r)),void 0!==n){if(c.state)throw new i.ft;c.stateDiff=l(n)}return c}(n)}return t}a.d(t,{yH:()=>c})},9312(e,t,a){"use strict";a.d(t,{},{A:(e,t,a)=>JSON.stringify(e,(e,a)=>{let r="bigint"==typeof a?a.toString():a;return"function"==typeof t?t(e,r):r},a)})},3291(e,t,a){"use strict";a.d(t,{c:()=>c});var r=a(7946);let n=2n**256n-1n;var i=a(43),s=a(2607),o=a(8211),l=a(7138);function c(e){let{account:t,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,to:d}=e,h=t?(0,r.J)(t):void 0;if(h&&!(0,l.P)(h.address))throw new i.M({address:h.address});if(d&&!(0,l.P)(d))throw new i.M({address:d});if(void 0!==a&&(void 0!==c||void 0!==u))throw new o.n3;if(c&&c>n)throw new s.BG({maxFeePerGas:c});if(u&&c&&u>c)throw new s.lN({maxFeePerGas:c,maxPriorityFeePerGas:u})}},5425(e,t,a){"use strict";var r=a(5923),n=a(3546);function i(e,t="wei"){return(0,n.J)(e,r.eL[t])}a.d(t,{c:()=>i})},8417(e,t,a){"use strict";var r=a(5923),n=a(3546);function i(e,t="wei"){return(0,n.J)(e,r.sz[t])}a.d(t,{Q:()=>i})},3546(e,t,a){"use strict";function r(e,t){let a=e.toString(),r=a.startsWith("-");r&&(a=a.slice(1));let[n,i]=[(a=a.padStart(t,"0")).slice(0,a.length-t),a.slice(a.length-t)];return i=i.replace(/(0+)$/,""),`${r?"-":""}${n||"0"}${i?`.${i}`:""}`}a.d(t,{J:()=>r})},1629(e,t,a){"use strict";let r,n;var i,s=function(e,t,a,r){if("a"===a&&!r)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===a?r:"a"===a?r.call(e):r?r.value:t.get(e)},o=function(e,t,a,r,n){if("m"===r)throw TypeError("Private method is not writable");if("a"===r&&!n)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(e,a):n?n.value=a:t.set(e,a),a};let l=new Set,c={};function u(){if(n||(n=Object.freeze({register:d,get:h,on:m}),"u"<typeof window))return n;let e=Object.freeze({register:d});try{window.addEventListener("wallet-standard:register-wallet",({detail:t})=>t(e))}catch(e){console.error("wallet-standard:register-wallet event listener could not be added\n",e)}try{window.dispatchEvent(new f(e))}catch(e){console.error("wallet-standard:app-ready event could not be dispatched\n",e)}return n}function d(...e){return(e=e.filter(e=>!l.has(e))).length?(e.forEach(e=>{r=void 0,l.add(e)}),c.register?.forEach(t=>p(()=>t(...e))),function(){e.forEach(e=>{r=void 0,l.delete(e)}),c.unregister?.forEach(t=>p(()=>t(...e)))}):()=>{}}function h(){return r||(r=[...l]),r}function m(e,t){return c[e]?.push(t)||(c[e]=[t]),function(){c[e]=c[e]?.filter(e=>t!==e)}}function p(e){try{e()}catch(e){console.error(e)}}var f=class extends Event{get detail(){return s(this,i,"f")}get type(){return"wallet-standard:app-ready"}constructor(e){super("wallet-standard:app-ready",{bubbles:!1,cancelable:!1,composed:!1}),i.set(this,void 0),o(this,i,e,"f")}preventDefault(){throw Error("preventDefault cannot be called")}stopImmediatePropagation(){throw Error("stopImmediatePropagation cannot be called")}stopPropagation(){throw Error("stopPropagation cannot be called")}};i=new WeakMap,a.d(t,{getWallets:()=>u})},8591(e,t,a){"use strict";a.d(t,{},{t:(...e)=>{}})},6100(e,t,a){"use strict";function r(e,t,a){return"function"==typeof e?e(t):void 0!==e?e:void 0!==a?a:void 0}a.d(t,{vd:()=>i,VK:()=>r,lQ:()=>n.t,zc:()=>s});var n=a(8591);function i(e){return Promise.all(Array.from(e).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}function s(e,t,a){let r,n=new Promise((e,n)=>{r=setTimeout(()=>{let e=Error(`Timed out after ${t}ms`);a?.abort(),n(e)},t),r.unref?.()});return Promise.race([Promise.resolve(e),n]).finally(()=>{clearTimeout(r)})}}},r={};function n(e){var t=r[e];if(void 0!==t)return t.exports;var i=r[e]={exports:{}};return a[e].call(i.exports,i,i.exports,n),i.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,n.t=function(a,r){if(1&r&&(a=this(a)),8&r||"object"==typeof a&&a&&(4&r&&a.__esModule||16&r&&"function"==typeof a.then))return a;var i=Object.create(null);n.r(i);var s={};e=e||[null,t({}),t([]),t(t)];for(var o=2&r&&a;("object"==typeof o||"function"==typeof o)&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach(e=>{s[e]=()=>a[e]});return s.default=()=>a,n.d(i,s),i},n.d=(e,t,a)=>{var r=(t,a)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,[a]:t[r]})};r(t,"get"),r(a,"value")},n.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};(()=>{"use strict";let e,t,a,r,s,o,l,c,u,d,h,m,p;function f(){return"u">typeof window}n.r(i),n.d(i,{Clerk:()=>iq,ClerkAPIResponseError:()=>U,ClerkRuntimeError:()=>q,EmailLinkError:()=>F,EmailLinkErrorCode:()=>L,EmailLinkErrorCodeStatus:()=>W,isClerkAPIResponseError:()=>M,isClerkRuntimeError:()=>O,isEmailLinkError:()=>Q,isKnownError:()=>Z,isMetamaskError:()=>$,isUserLockedError:()=>Y});let g=RegExp("bot|spider|crawl|APIs-Google|AdsBot|Googlebot|mediapartners|Google Favicon|FeedFetcher|Google-Read-Aloud|DuplexWeb-Google|googleweblight|bing|yandex|baidu|duckduck|yahoo|ecosia|ia_archiver|facebook|instagram|pinterest|reddit|slack|twitter|whatsapp|youtube|semrush","i"),b=/^(Cloudflare-Workers|Node\.js|Deno|Bun)\b/i;function y(){if("u">typeof window&&window.navigator)return window.navigator;let e=globalThis;return"function"==typeof e.WorkerGlobalScope&&e.self instanceof e.WorkerGlobalScope&&e.self.navigator&&!b.test(e.self.navigator.userAgent??"")?e.self.navigator:null}function w(){var e;let t=y();return!!t&&!((e=t?.userAgent)&&g.test(e))&&!t?.webdriver}function k(){let e=y();return!!e&&("boolean"!=typeof e.onLine||!!e.onLine)}function v(){return k()&&w()}let _=(e,t,a,r,n)=>{let{notify:i}=n||{},s=e.get(a);s||(s=[],e.set(a,s)),s.push(r),i&&t.has(a)&&r(t.get(a))},x=(e,t,a)=>(e.get(t)||[]).map(e=>e(a)),j=(e,t,a)=>{let r=e.get(t);r&&(a?r.splice(r.indexOf(a)>>>0,1):e.set(t,[]))},z=()=>{let e=new Map,t=new Map,a=new Map;return{on:(...a)=>_(e,t,...a),prioritizedOn:(...e)=>_(a,t,...e),emit:(r,n)=>{t.set(r,n),x(a,r,n),x(e,r,n)},off:(...t)=>j(e,...t),prioritizedOff:(...e)=>j(a,...e),internal:{retrieveListeners:t=>e.get(t)||[]}}},S="status";function I(e){return function(t){let a=t??this;if(!a)throw TypeError(`${e.kind||e.name} type guard requires an error object`);return!!e.kind&&"object"==typeof a&&null!==a&&"constructor"in a&&a.constructor?.kind===e.kind||a instanceof e}}var A,C,E,P=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}]
46
46
  Message:${this.message}`}static formatMessage(e,t,a,r){let n="Clerk:",i=RegExp(n.replace(" ","\\s*"),"i");return t=t.replace(i,""),t=`${n} ${t.trim()}
47
47
 
48
48
  (code="${a}")
@@ -58,5 +58,5 @@ Consult the documentation of glob-to-regexp here: https://www.npmjs.com/package/
58
58
  ${t.message}`)}})(eK(e)):e).some(e=>e.test(eK(r.origin))));return i||eT(`Clerk: Redirect URL ${r} is not on one of the allowedRedirectOrigins, falling back to the default redirect URL.`),i}))}};let e$="__clerk_netlify_cache_bust",eY=["__clerk_status","__clerk_created_session","__clerk_invitation_token","__clerk_ticket","__clerk_modal_state","__clerk_handshake","__clerk_handshake_nonce","__clerk_help",e$,en,el,eo];function eQ(e){return new URL(window.location.href).searchParams.get(e)||null}function eX(e){let t=new URL(window.location.href);t.searchParams.has(e)&&(t.searchParams.delete(e),window.history.replaceState(window.history.state,"",t))}function e1(e){let t=new URLSearchParams(window.location.search),a=e||new URLSearchParams;for(let e of eY){let r=t.get(e);r&&a.set(e,r)}return a}let e0={"choose-organization":"choose-organization","reset-password":"reset-password","setup-mfa":"setup-mfa"},e2=e=>`/tasks/${e0[e.key]}`;function e9(e,{navigate:t,baseUrl:a}){let r=e.currentTask;if(r){var n;let e;return t((n={base:a},e=e1(),eL({base:n.base,hashPath:e2(r),searchParams:e},{stringify:!0})))}}let e3=e=>`🔒 Clerk:
59
59
  ${e.trim()}
60
60
  (This notice only appears in development)`,e5=e=>e3(`${e} as a function is not supported in this environment. The value will be ignored. Provide an absolute URL instead.`),e6={proxyUrlAsFunctionNotSupported:e5("proxyUrl"),domainAsFunctionNotSupported:e5("domain"),cannotRenderComponentWhenSessionExists:"The <SignUp/> and <SignIn/> components cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the Home URL instead.",cannotRenderSignUpComponentWhenSessionExists:"The <SignUp/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the value set in `afterSignUp` URL instead.",cannotRenderSignUpComponentWhenTaskExists:"The <SignUp/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenTaskDoesNotExist:"<TaskChooseOrganization/> cannot render unless a session task is pending. Clerk is redirecting to the value set in `redirectUrlComplete` instead.",cannotRenderSignInComponentWhenSessionExists:"The <SignIn/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the `afterSignIn` URL instead.",cannotRenderSignInComponentWhenTaskExists:"The <SignIn/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenUserDoesNotExist:"<UserProfile/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",createCannotRenderComponentWhenOrgDoesNotExist:e=>e3(`<${e}/> cannot render unless an organization is active. Since no organization is currently active, this is no-op.`),cannotRenderAnyOrganizationComponent:e=>e3(`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=>e3(`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/> and <SignUp/> modals are hidden because a user is already signed in and this application is configured for single-session mode. This is expected behavior — no action is needed. To allow rendering while signed in, enable multi-session mode in your Clerk Dashboard.",cannotRenderAPIKeysComponent:"The <APIKeys/> component cannot be rendered when API keys is disabled. Since API keys is disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenUnauthorized:"The <APIKeys/> component cannot be rendered for an organization unless a user has the required permissions. Since the user does not have the necessary permissions, this is no-op.",cannotRenderAPIKeysComponentForUserWhenDisabled:"The <APIKeys/> component cannot be rendered when user API keys are disabled. Since user API keys are disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenDisabled:"The <APIKeys/> component cannot be rendered when organization API keys are disabled. Since organization API keys are disabled, this is no-op.",cannotRenderOAuthConsentComponentWhenUserDoesNotExist:"<OAuthConsent/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderConfigureSSOComponentWhenUserDoesNotExist:"<ConfigureSSO/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderConfigureSSOComponentWhenDisabled:"The <ConfigureSSO/> component cannot be rendered when self-serve SSO is disabled. Visit `https://dashboard.clerk.com` to enable the feature. Since self-serve SSO is disabled, this is no-op.",cannotRenderConfigureSSOComponentWhenEmailAddressDisabled:"The <ConfigureSSO/> component cannot be rendered when email addresses are disabled on the instance. Visit `https://dashboard.clerk.com` to enable email addresses. Since email addresses are disabled, this is no-op."};for(let e of Object.keys(e6)){let t=e6[e];"function"!=typeof t&&(e6[e]=e3(t))}let e8="clerk:beforeunload",e4=["http:","https:","wails:","chrome-extension:"],e7=/^[/\\][/\\]/;function te(e){return/^http(s)?:\/\//.test(e||"")}function tt(e){return e.startsWith("/")}let ta=[".vercel.app"],tr=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","BITBUCKET_BUILD_NUMBER","APPVEYOR","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION","JENKINS_URL","HUDSON_URL","BAMBOO_BUILDKEY","CF_PAGES"],tn=Symbol.for("@clerk/shared.telemetryNoticeShown"),ti=["Attention: Clerk collects telemetry data from its SDKs when connected to development instances.","The data collected is used to inform Clerk's product roadmap.","To learn more, including how to opt-out from the telemetry program, visit: https://clerk.com/docs/telemetry."];var ts=class{#u;#R=864e5;constructor(e){this.#u=e}isEventThrottled(e){let t=Date.now(),a=this.#N(e),r=this.#u.getItem(a);return!!r&&!(t-r>this.#R)||(this.#u.setItem(a,t),!1)}#N(e){let{sk:t,pk:a,payload:r,...n}=e,i={...r,...n};return JSON.stringify(Object.keys({...r,...n}).sort().map(e=>i[e]))}},to=class{#B="clerk_telemetry_throttler";getItem(e){return this.#D()[e]}setItem(e,t){try{let a=this.#D();a[e]=t,localStorage.setItem(this.#B,JSON.stringify(a))}catch(e){e instanceof DOMException&&("QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&localStorage.length>0&&localStorage.removeItem(this.#B)}}removeItem(e){try{let t=this.#D();delete t[e],localStorage.setItem(this.#B,JSON.stringify(t))}catch{}}#D(){try{let e=localStorage.getItem(this.#B);if(!e)return{};return JSON.parse(e)}catch{return{}}}static isSupported(){return"u">typeof window&&!!window.localStorage}},tl=class{#u=new Map;#F=1e4;getItem(e){return this.#u.size>this.#F?void this.#u.clear():this.#u.get(e)}setItem(e,t){this.#u.set(e,t)}removeItem(e){this.#u.delete(e)}};let tc=new Set(["error","warn","info","debug","trace"]);var tu=class{#L;#W;#K={};#H=[];#V=null;constructor(e){this.#L={maxBufferSize:e.maxBufferSize??5,samplingRate:e.samplingRate??1,perEventSampling:e.perEventSampling??!0,disabled:e.disabled??!1,debug:e.debug??!1,endpoint:"https://clerk-telemetry.com"},!e.clerkVersion&&"u"<typeof window?this.#K.clerkVersion="":this.#K.clerkVersion=e.clerkVersion??"",this.#K.sdk=e.sdk,this.#K.sdkVersion=e.sdkVersion,this.#K.publishableKey=e.publishableKey??"";const t=eS(e.publishableKey);t&&(this.#K.instanceType=t.instanceType),e.secretKey&&(this.#K.secretKey=e.secretKey.substring(0,16));const a=to.isSupported()?new to:new tl;this.#W=new ts(a),function(e={}){if(!e.skip)try{if("u">typeof window||void 0!==globalThis.EdgeRuntime||!("u"<typeof process)&&process.env&&tr.some(e=>eb(process.env[e]))||globalThis[tn])return;if("u">typeof console&&"function"==typeof console.log){for(let e of ti)console.log(e);console.log("")}globalThis[tn]=!0}catch{}}({skip:!this.isEnabled})}get isEnabled(){return!("development"!==this.#K.instanceType||this.#L.disabled||"u">typeof process&&process.env&&eb(process.env.CLERK_TELEMETRY_DISABLED)||"u">typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#L.debug||"u">typeof process&&process.env&&eb(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let t=this.#G(e.event,e.payload);if(this.#J(t.event,t),!this.#Z(t,e.eventSamplingRate))return;this.#H.push({kind:"event",value:t}),this.#$()}catch(e){console.error("[clerk/telemetry] Error recording telemetry event",e)}}recordLog(e){try{if(!this.#Y(e))return;let t="string"==typeof e?.level&&tc.has(e.level),a="string"==typeof e?.message&&e.message.trim().length>0,r=null,n=e?.timestamp;if("number"==typeof n||"string"==typeof n){let e=new Date(n);Number.isNaN(e.getTime())||(r=e)}if(!t||!a||null===r){this.isDebug&&"u">typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:t,messageIsValid:a,timestampIsValid:null!==r});return}let i=this.#Q(),s={sdk:i.name,sdkv:i.version,cv:this.#K.clerkVersion??"",lvl:e.level,msg:e.message,ts:r.toISOString(),pk:this.#K.publishableKey||null,payload:this.#X(e.context)};this.#H.push({kind:"log",value:s}),this.#$()}catch(e){console.error("[clerk/telemetry] Error recording telemetry log entry",e)}}#Z(e,t){return this.isEnabled&&!this.isDebug&&this.#ee(e,t)}#Y(e){return!0}#ee(e,t){let a=Math.random();return!!(a<=this.#L.samplingRate&&(!1===this.#L.perEventSampling||void 0===t||a<=t))&&!this.#W.isEventThrottled(e)}#$(){if("u"<typeof window)return void this.#et();if(this.#H.length>=this.#L.maxBufferSize){this.#V&&("u">typeof cancelIdleCallback?cancelIdleCallback(Number(this.#V)):clearTimeout(Number(this.#V))),this.#et();return}this.#V||("requestIdleCallback"in window?this.#V=requestIdleCallback(()=>{this.#et(),this.#V=null}):this.#V=setTimeout(()=>{this.#et(),this.#V=null},0))}#et(){let e=[...this.#H];if(this.#H=[],this.#V=null,0===e.length)return;let t=e.filter(e=>"event"===e.kind).map(e=>e.value),a=e.filter(e=>"log"===e.kind).map(e=>e.value);t.length>0&&fetch(new URL("/v1/event",this.#L.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({events:t})}).catch(()=>void 0),a.length>0&&fetch(new URL("/v1/logs",this.#L.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:a})}).catch(()=>void 0)}#J(e,t){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(t),console.groupEnd()):console.log("[clerk/telemetry]",e,t))}#Q(){let e={name:this.#K.sdk,version:this.#K.sdkVersion};if("u">typeof window){let t=window;if(t.Clerk){let a=t.Clerk;if("object"==typeof a&&null!==a&&"constructor"in a&&"function"==typeof a.constructor&&a.constructor.sdkMetadata){let{name:t,version:r}=a.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==r&&(e.version=r)}}}return e}#G(e,t){let a=this.#Q();return{event:e,cv:this.#K.clerkVersion??"",it:this.#K.instanceType??"",sdk:a.name,sdkv:a.version,...this.#K.publishableKey?{pk:this.#K.publishableKey}:{},...this.#K.secretKey?{sk:this.#K.secretKey}:{},payload:t}}#X(e){if(null==e||"object"!=typeof e)return null;try{let t=JSON.parse(JSON.stringify(e));if(t&&"object"==typeof t&&!Array.isArray(t))return t;return null}catch{return null}}};let td="COMPONENT_MOUNTED",th=new Set(["SignIn","SignUp"]);function tm(e){return function(t,a,r){return{event:e,eventSamplingRate:e===td?th.has(t)?1:.1:.1,payload:{component:t,appearanceProp:!!a?.appearance,theme:!!a?.appearance?.theme,elements:!!a?.appearance?.elements,variables:!!a?.appearance?.variables,...r}}}}function tp(e,t,a){return tm(td)(e,t,a)}function tf(e,t,a){return tm("COMPONENT_OPENED")(e,t,a)}function tg(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}var tb=n(6100);let ty=!1,tw=null,tk=!1,tv=[];function t_(e,t,a,r){ty&&(tv.push({level:e,message:t,context:a,source:r,ts:Date.now()}),tv.length>200&&tv.shift())}async function tx(e){try{if(!ty||tw)return;let{getDebugLogger:t}=await Promise.resolve().then(n.bind(n,9296)),a=await t({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(a&&(tw=a)&&0!==tv.length){for(let e of tv){let t={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":tw.error(e.message,t,e.source);break;case"warn":tw.warn(e.message,t,e.source);break;case"info":tw.info(e.message,t,e.source);break;case"debug":tw.debug(e.message,t,e.source)}}tv.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let tj={debug(e,t,a){tw?tw.debug(e,t,a):t_("debug",e,t,a)},error(e,t,a){tw?tw.error(e,t,a):t_("error",e,t,a)},info(e,t,a){tw?tw.info(e,t,a):t_("info",e,t,a)},warn(e,t,a){tw?tw.warn(e,t,a):t_("warn",e,t,a)}},tz={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,t)=>t<5,retryImmediately:!1,jitter:!0},tS=async e=>new Promise(t=>setTimeout(t,e)),tI=(e,t)=>t?e*(1+Math.random()):e,tA=async(e,t={})=>{var a;let r,n=0,{shouldRetry:i,initialDelay:s,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:u,onBeforeRetry:d}={...tz,...t},h=(a={initialDelay:s,maxDelayBetweenRetries:o,factor:l,jitter:u},r=0,async()=>{let e;await tS((e=tI(e=a.initialDelay*Math.pow(a.factor,r),a.jitter),Math.min(a.maxDelayBetweenRetries||e,e))),r++});for(;;)try{return await e()}catch(e){if(!i(e,++n))throw e;d&&await d(n),c&&1===n?await tS(tI(100,u)):await h()}},tC=async e=>tA(e,{initialDelay:100,shouldRetry:(e,t)=>t<=3,retryImmediately:!0,factor:2});class tE{#ea={"@zxcvbn-ts/core":()=>tC(()=>Promise.resolve().then(n.bind(n,3239))),"@zxcvbn-ts/language-common":()=>tC(()=>Promise.resolve().then(n.bind(n,9144))),"@base-org/account":()=>tC(()=>Promise.resolve().then(n.bind(n,1422))),"@coinbase/wallet-sdk":()=>tC(()=>Promise.resolve().then(n.bind(n,3197))),"@stripe/stripe-js":()=>tC(()=>Promise.resolve().then(n.bind(n,7544)))};import(e){return this.#ea[e]?this.#ea[e]():Promise.resolve(void 0)}}let tP=(e=!1)=>{let t,a;if(!e)return{track:async e=>{await e()},isUnloading:()=>!1};let r=(t=!1,a=()=>t=!0,{startListening:()=>{window.addEventListener("beforeunload",a),window.addEventListener(e8,a)},stopListening:()=>{window.removeEventListener("beforeunload",a),window.removeEventListener(e8,a)},isUnloading:()=>t});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}};function tq(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}let tO=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),tT=e=>({quantity:e.quantity,feePerBlock:tO(e.fee_per_block),total:tO(e.total)}),tU=e=>e.map(e=>({name:e.name,blockSize:e.block_size,tiers:e.tiers.map(tT)})),tM=e=>({name:e.name,blockSize:e.block_size,tiers:e.tiers.map(e=>({id:e.id,startsAtBlock:e.starts_at_block,endsAfterBlock:e.ends_after_block,feePerBlock:tO(e.fee_per_block)}))}),tR=e=>({proration:e.proration?{amount:tO(e.proration.amount),cycleDaysRemaining:e.proration.cycle_days_remaining,cycleDaysTotal:e.proration.cycle_days_total,cycleRemainingPercent:e.proration.cycle_remaining_percent}:null,payer:e.payer?{remainingBalance:tO(e.payer.remaining_balance),appliedAmount:tO(e.payer.applied_amount)}:null,total:tO(e.total)}),tN=e=>({proration:e.proration?{amount:tO(e.proration.amount),cycleDaysPassed:e.proration.cycle_days_passed,cycleDaysTotal:e.proration.cycle_days_total,cyclePassedPercent:e.proration.cycle_passed_percent}:null,total:tO(e.total)}),tB=e=>({subtotal:tO(e.subtotal),baseFee:tO(e.base_fee),taxTotal:tO(e.tax_total),grandTotal:tO(e.grand_total),perUnitTotals:e.per_unit_totals?tU(e.per_unit_totals):void 0}),tD=e=>({subtotal:tO(e.subtotal),baseFee:e.base_fee?tO(e.base_fee):null,taxTotal:tO(e.tax_total),grandTotal:tO(e.grand_total),totalDueAfterFreeTrial:e.total_due_after_free_trial?tO(e.total_due_after_free_trial):null,credit:e.credit?tO(e.credit):e.credit,credits:e.credits?tR(e.credits):null,discounts:e.discounts?tN(e.discounts):null,pastDue:e.past_due?tO(e.past_due):e.past_due,totalDueNow:e.total_due_now?tO(e.total_due_now):void 0,perUnitTotals:e.per_unit_totals?tU(e.per_unit_totals):void 0,totalsDuePerPeriod:e.totals_due_per_period?tB(e.totals_due_per_period):void 0,totalDuePerPeriod:e.total_due_per_period?tO(e.total_due_per_period):void 0}),tF=e=>({amount:tO(e.amount),date:tq(e.date),perUnitTotals:e.per_unit_totals?tU(e.per_unit_totals):void 0,totals:e.totals?tD(e.totals):void 0});function tL(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let tW=D({packageName:"@clerk/clerk-js"});function tK(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function tH(e){let t=(e||"").split("."),[a,r,n]=t;if(3!==t.length||!a||!r||!n)throw Error("JWT could not be decoded");let i=JSON.parse(tK(r)),s={__raw:e};return Object.keys(i).forEach(e=>{s[e]=i[e]}),{encoded:{header:a,payload:r,signature:n},header:JSON.parse(tK(a)),claims:s}}function tV(){if(!f())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function tG(){return void 0!==globalThis.document}function tJ(){if(!function(){if(!tG())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var tZ=class e{#er=[];#en={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #ei=null;constructor(){if("u"<typeof window)return;window.addEventListener("eip6963:announceProvider",this.#es),window.dispatchEvent(new Event("eip6963:requestProvider"))}static getInstance(){return e.#ei||(e.#ei=new e),e.#ei}get=e=>{let t=this.#er.find(t=>t.info.name===this.#en[e])?.provider;return void 0!==t?t:window.ethereum};#es=e=>{this.#er.some(t=>t.info.uuid===e.detail.info.uuid)||this.#er.push(e.detail)}},t$=class e{#eo=void 0;#el=!1;static #ei=null;async #ec(){if(this.#el)return;this.#el=!0;let e=await Promise.resolve().then(n.bind(n,1629)).then(e=>e.getWallets());this.#eo=e.get(),e.on("register",()=>{this.#eo=e.get()}),e.on("unregister",()=>{this.#eo=e.get()})}#eu(e){return e.chains?.some(e=>e.startsWith("solana:"))??!1}#ed(e){return"solana:signMessage"in e.features}static getInstance(){return e.#ei||(e.#ei=new e),e.#ei}get=async e=>{await this.#ec();let t=(this.#eo||[]).find(t=>t.name===e&&this.#eu(t)&&this.#ed(t));if(t&&this.#eu(t))return t;if("u"<typeof window)return;let a=window.solana;if(a&&"function"==typeof a.connect&&"function"==typeof a.signMessage)return a}};let tY=()=>(function(e){let t=D({packageName:"@clerk/shared"});async function a(e){let{provider:t,walletName:a}=e,r=await p(t,a);if(!r)return"";if("solana"===t){let e=await r.features["standard:connect"].connect();return e&&e.accounts[0].address||""}let n=await r.request({method:"eth_requestAccounts"});return n&&n[0]||""}let r=async e=>{let{identifier:t,nonce:a,provider:r,walletName:n=""}=e,i=await p(r,n);if(!i)return"";if("solana"===r)try{let e=i.accounts.find(e=>e.address===t);if(!e)return console.warn(`Wallet account with address ${t} not found`),"";let r=await i.features["solana:signMessage"]?.signMessage({account:e,message:new TextEncoder().encode(a)});return r?.[0]?.signature?btoa(String.fromCharCode(...r[0].signature)):""}catch(e){if(e instanceof Error&&e.message.includes("User rejected the request."))throw new q("Web3 signature request was rejected by the user.",{code:"web3_signature_request_rejected"});throw new q("An error occurred while generating the Solana signature.",{code:"web3_solana_signature_generation_failed",cause:e instanceof Error?e:void 0})}return await i.request({method:"personal_sign",params:[`0x${a.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,t]})};async function n(){return await a({provider:"metamask"})}async function i(){return await a({provider:"coinbase_wallet"})}async function s(){return await a({provider:"okx_wallet"})}async function o(){return await a({provider:"base"})}async function l(e){return await a({provider:"solana",walletName:e})}async function c(e){return await r({...e,provider:"metamask"})}async function u(e){return await r({...e,provider:"coinbase_wallet"})}async function d(e){return await r({...e,provider:"okx_wallet"})}async function h(e){return await r({...e,provider:"base"})}async function m(e){return await r({...e,provider:"solana"})}async function p(a,r){if("coinbase_wallet"===a){let t=await e.import("@coinbase/wallet-sdk");return t?t.createCoinbaseWalletSDK({appName:"u">typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"u">typeof document&&document.title||"Web3 Application",preference:{options:"all"}}).getProvider():null}if("base"===a)try{let t=await e.import("@base-org/account");if(!t)return null;return t.createBaseAccountSDK({appName:"u">typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"u">typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return"solana"===a?r&&0!==r.length?await t$.getInstance().get(r):void t.throw("Wallet name must be provided to get Solana wallet provider"):tZ.getInstance().get(a)}return{getWeb3Identifier:a,generateWeb3Signature:r,getMetamaskIdentifier:n,getCoinbaseWalletIdentifier:i,getOKXWalletIdentifier:s,getBaseIdentifier:o,getSolanaIdentifier:l,generateSignatureWithMetamask:c,generateSignatureWithCoinbaseWallet:u,generateSignatureWithOKXWallet:d,generateSignatureWithBase:h,generateSignatureWithSolana:m}})(new tE),tQ="environment",tX=JSON.stringify,t1=JSON.parse;class t0{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,t,a){try{let r={value:t,...a&&{exp:Date.now()+a}};window.localStorage.setItem(this._key(e),tX(r))}catch{}}static getItem(e,t){try{let a=window.localStorage.getItem(this._key(e));if(!a)return t;let r=t1(a);if(!r)return t;if(this.isExpired(r))return this.removeItem(e),t;return r?.value??t}catch{return t}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let t2="ClerkJS:";function t9(e=""){throw Error(`${t2} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function t3(e){throw Error(`${t2} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function t5(e){throw Error(`${t2} You need to start a ${e} flow by calling ${e}.create() first.`)}function t6(e,t){throw Error(`${t2} Strategy "${t}" is not a valid strategy for ${e}.`)}function t8(e){throw Error(`${t2} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function t4(e=""){throw Error(`${t2} Missing '${e}' option`)}function t7(e,t){throw Error(`${t2} Response: ${e||0} not supported yet.
61
- For more information contact us at ${t}`)}function ae(e){throw Error(`${t2} Calling ${e}.reload is not currently supported. Please contact support.`)}function at(e){throw Error(`${t2} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function aa(e="",t){let{async:a,defer:r,beforeLoad:n,crossOrigin:i,nonce:s}=t||{};return tA(()=>new Promise((t,o)=>{e||o(Error("loadScript cannot be called without a src")),document&&document.body||o(Error("loadScript cannot be called when document does not exist"));let l=document.createElement("script");i&&l.setAttribute("crossorigin",i),l.async=a||!1,l.defer=r||!1,l.addEventListener("load",()=>{l.remove(),t(l)}),l.addEventListener("error",t=>{l.remove(),o(t.error??Error(`failed to load script: ${e}`))}),l.src=e,s&&(l.nonce=s),n?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>t<=5})}async function ar(e){return window.turnstile||await an(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function an(e){try{return await aa("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 ai(e){try{let t=e.getAttribute("data-cl-theme")||void 0,a=e.getAttribute("data-cl-language")||void 0,r=e.getAttribute("data-cl-size")||void 0;return{theme:t,language:a,size:r}}catch{return{theme:void 0,language:void 0,size:void 0}}}let as=async e=>{let t,a,r,n,{siteKey:i,widgetType:s,invisibleSiteKey:o,nonce:l}=e,{modalContainerQuerySelector:c,modalWrapperQuerySelector:u,closeModal:d,openModal:h}=e,m=await ar(l),p=[],f="",g="",b=i,y=0,w=null,k="invisible";if(c&&u){w=s,n=c,k="modal";try{await h?.()}catch{throw{captchaError:"modal_component_not_ready"}}let e=await new Promise(e=>{if(document.querySelector(c))return e(document.querySelector(c));let t=new MutationObserver(()=>{document.querySelector(c)&&(t.disconnect(),e(document.querySelector(c)))});t.observe(document.body,{childList:!0,subtree:!0})});if(e){let{theme:n,language:i,size:s}=ai(e);t=n,r=i,a=s}}if(!n&&"smart"===s){let e=document.getElementById(eu);if(e){k="smart",w="smart",n=`#${eu}`,e.style.maxHeight="0";let{theme:i,language:s,size:o}=ai(e);t=i,r=s,a=o}else console.error("Cannot initialize Smart CAPTCHA widget because the `clerk-captcha` DOM element was not found; falling back to Invisible CAPTCHA widget. If you are using a custom flow, visit https://clerk.com/docs/guides/development/custom-flows/authentication/bot-sign-up-protection for instructions")}if(!n){k="invisible",b=o,w="invisible",n=`.${ed}`;let e=document.createElement("div");e.classList.add(ed),e.style.display="none",document.body.appendChild(e)}let v=async()=>new Promise((i,s)=>{try{let o=m.render(n,{sitekey:b,appearance:"interaction-only",theme:t||"auto",size:a||"normal",language:r||"auto",action:e.action,retry:"never","refresh-expired":"auto",callback:function(e){d?.(),i([e,o])},"before-interactive-callback":()=>{if(u){let e=document.querySelector(u);e?.style.setProperty("visibility","visible"),e?.style.setProperty("pointer-events","all")}else{let e=document.getElementById(eu);e&&(e.style.maxHeight="unset",e.style.minHeight="compact"===a?"140px":"68px",e.style.marginBottom="1.5rem",e.dataset.clInteractive="true")}},"error-callback":function(e){var t;(p.push(e),y<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))?setTimeout(()=>{n&&!document.querySelector(n)?s([p.join(","),o]):(m.reset(o),y++)},250):s([p.join(","),o])},"unsupported-callback":function(){return s(["This browser is not supported by the CAPTCHA.",o]),!0}})}catch(e){s([e,void 0])}});try{[f,g]=await v(),m.remove(g)}catch([e,t]){throw t&&m.remove(t),{captchaError:e}}finally{if("modal"===k&&d?.(),"invisible"===k){let e=document.querySelector(`.${ed}`);e&&document.body.removeChild(e)}if("smart"===k){let e=document.getElementById(eu);e&&(delete e.dataset.clInteractive,e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:f,captchaWidgetType:w}},ao=e=>{let t=e.__internal_environment,a=t?t.displayConfig.captchaProvider:"turnstile",r=e.__internal_getOption?.("nonce");return{captchaSiteKey:t?t.displayConfig.captchaPublicKey:null,captchaWidgetType:t?t.displayConfig.captchaWidgetType:null,captchaProvider:a,captchaPublicKeyInvisible:t?t.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:t?t.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:r||void 0}};class al{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:a,captchaPublicKeyInvisible:r,nonce:n}=ao(this.clerk);return a&&t&&r?{...await as({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:r,nonce:e?.nonce||n||void 0,siteKey:r,widgetType:"invisible"}).catch(e=>e.captchaError?{captchaError:e.captchaError}:{captchaError:e?.message||e||"unexpected_captcha_error"}),captchaAction:e?.action}:{captchaError:"captcha_unavailable",captchaAction:e?.action}}async managedOrInvisible(e){let{captchaSiteKey:t,canUseCaptcha:a,captchaWidgetType:r,captchaProvider:n,captchaPublicKeyInvisible:i,nonce:s}=ao(this.clerk);if(a&&t&&i){let a=await as({captchaProvider:n,invisibleSiteKey:i,nonce:s||void 0,siteKey:t,widgetType:r,...e}).catch(t=>t.captchaError?{captchaError:t.captchaError}:e?.action==="verify"?{captchaError:t?.message||t||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...a,captchaAction:"verify"}:a}return e?.action==="verify"?{captchaError:"captcha_unavailable",captchaAction:e?.action}:{}}async managedInModal(e){if("u"<typeof document)throw new q("Captcha is not supported in non-browser environments",{code:"captcha_unavailable"});return this.managedOrInvisible({modalWrapperQuerySelector:"#cl-modal-captcha-wrapper",modalContainerQuerySelector:"#cl-modal-captcha-container",openModal:()=>this.clerk.__internal_openBlankCaptchaModal(),closeModal:()=>this.clerk.__internal_closeBlankCaptchaModal(),action:e?.action})}}class ac{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return ac.instance||(ac.instance=new ac(rz,al)),ac.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new q("Security verification failed. Please try again by refreshing the page, clearing your browser cookies, or using a different web browser.",{code:"captcha_client_attempts_exceeded"});try{return this.inflightException&&await this.inflightException,await t()}catch(r){let a;if(!M(r)||O(r)&&"network_error"===r.code||r.errors[0]?.code!=="requires_captcha")throw r;if(this.inflightException)return await this.inflightException,await t();this.inflightException=new Promise(e=>a=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{a(),this.inflightException=null}return await t()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class au{static clerk;id;pathRoot="";static get fapiClient(){return au.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 ac.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let a;au.fapiClient||function(){throw Error(`${t2} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=t;try{a=await au.fapiClient.request(e,{fetchMaxTries:r})}catch(t){if(this.shouldRethrowOfflineNetworkErrors())throw new q(t?.message||t,{code:"network_error"});if(!v())return tj.warn("Network request failed while offline, returning null",{method:e.method,path:e.path},"baseResource"),null;throw t}let{payload:n,status:i,statusText:s,headers:o}=a;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||t.forceUpdateClient)&&!t.skipUpdateClient&&this._updateClient(n),i>=200&&i<=299)return n;if(i>=400){let e=n?.errors,t=e?.[0]?.long_message,a=e?.[0]?.code;401===i&&"dev_browser_unauthenticated"===a?await au.clerk.__internal_handleUnauthenticatedDevBrowser():401===i&&"requires_captcha"!==a&&await au.clerk.handleUnauthenticated(),function(e,t){var a;if(!t||!t[0])return;let r=t[0],n=r.long_message;if("origin_invalid"===r.code&&((a=au.clerk.publishableKey).startsWith("live_")||a.startsWith("pk_live_"))){let a=au.clerk.frontendApi.replace("clerk.","");throw new U(`Clerk: Production Keys are only allowed for domain "${a}".
62
- API Error: ${n}`,{data:t,status:e})}}(i,e);let r={data:e,status:i};if(429===i&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(r.retryAfter=t)}}throw new U(t||s,r)}return null}static _updateClient(e){let t=rj(e);t&&au.clerk&&au.clerk.updateClient(t)}path(e){let t=this.pathRoot;if(this.isNew())return t;let a=t.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?a.replace(/[^/]$/,"$&/")+encodeURIComponent(e):a}withDefault(e,t){return e??t}async _baseGet(e={}){let t=await au._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce,signal:e.abortSignal},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:a,method:r,path:n}=e,i=await au._fetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}async _baseMutateBypass(e){let{action:t,body:a,method:r,path:n}=e,i=await au._baseFetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}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=au.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}class ad extends au{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?tq(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tq(e.last_used_at):null,this.updatedAt=tq(e.updated_at),this.createdAt=tq(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 ah extends au{claimedAt=null;reverification=!1;singleSessionMode=!1;preferredChannels=null;sessionMinter=!1;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.claimedAt=this.withDefault(e.claimed_at?tq(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels),this.sessionMinter=this.withDefault(e.session_minter,this.sessionMinter)),this}__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,session_minter:this.sessionMinter}}}(A=E||(E={}))[A.None=0]="None",A[A.Mutable=1]="Mutable",A[A.Watching=2]="Watching",A[A.RecursedCheck=4]="RecursedCheck",A[A.Recursed=8]="Recursed",A[A.Dirty=16]="Dirty",A[A.Pending=32]="Pending";let am=[],{link:ap,unlink:af,propagate:ag,checkDirty:ab,endTracking:ay,startTracking:aw,shallowPropagate:ak}=function({update:e,notify:t,unwatched:a}){let r=0;return{link:function(e,t){let a,n=t.depsTail;if(void 0!==n&&n.dep===e)return;if(4&t.flags&&void 0!==(a=void 0!==n?n.nextDep:t.deps)&&a.dep===e){a.version=r,t.depsTail=a;return}let i=e.subsTail;if(void 0!==i&&i.version===r&&i.sub===t)return;let s=t.depsTail=e.subsTail={version:r,dep:e,sub:t,prevDep:n,nextDep:a,prevSub:i,nextSub:void 0};void 0!==a&&(a.prevDep=s),void 0!==n?n.nextDep=s:t.deps=s,void 0!==i?i.nextSub=s:e.subs=s},unlink:n,propagate:function(e){let a,r=e.nextSub;t:for(;;){let n=e.sub,i=n.flags;if(3&i&&(60&i?12&i?4&i?!(48&i)&&function(e,t){let a=t.depsTail;if(void 0!==a){let r=t.deps;do{if(r===e)return!0;if(r===a)break;r=r.nextDep}while(void 0!==r)}return!1}(e,n)?(n.flags=40|i,i&=1):i=0:n.flags=-9&i|32:i=0:n.flags=32|i,2&i&&t(n),1&i)){let t=n.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(a={value:r,prev:a},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==a;)if(e=a.value,a=a.prev,void 0!==e){r=e.nextSub;continue t}break}},checkDirty:function(t,a){let r,n=0;t:for(;;){let s=t.dep,o=s.flags,l=!1;if(16&a.flags)l=!0;else if((17&o)==17){if(e(s)){let e=s.subs;void 0!==e.nextSub&&i(e),l=!0}}else if((33&o)==33){(void 0!==t.nextSub||void 0!==t.prevSub)&&(r={value:t,prev:r}),t=s.deps,a=s,++n;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;n;){--n;let s=a.subs,o=void 0!==s.nextSub;if(o?(t=r.value,r=r.prev):t=s,l){if(e(a)){o&&i(s),a=t.sub;continue}}else a.flags&=-33;if(a=t.sub,void 0!==t.nextDep){t=t.nextDep;continue t}l=!1}return l}},endTracking:function(e){let t=e.depsTail,a=void 0!==t?t.nextDep:e.deps;for(;void 0!==a;)a=n(a,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:i};function n(e,t=e.sub){let r=e.dep,i=e.prevDep,s=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==s?s.prevDep=i:t.depsTail=i,void 0!==i?i.nextDep=s:t.deps=s,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&a(r),s}function i(e){do{let a=e.sub,r=e.nextSub,n=a.flags;(48&n)==32&&(a.flags=16|n,2&n&&t(a)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?aA(e):aC(e,e.value),notify:function e(t){let a=t.flags;if(!(64&a)){t.flags=64|a;let r=t.subs;void 0!==r?e(r.sub):am[ax++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=af(t,e);while(void 0!==t)}}else"previousValue"in e||aO.call(e)}}),av=0,a_=0,ax=0;function aj(t){let a=e;return e=t,a}function az(e){return aq.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function aS(e){return aP.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function aI(a){let r={fn:a,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?ap(r,e):void 0!==t&&ap(r,t);let n=aj(r);try{r.fn()}finally{aj(n)}return aO.bind(r)}function aA(e){let t=aj(e);aw(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{aj(t),ay(e)}}function aC(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function aE(){for(;a_<ax;){let e=am[a_];am[a_++]=void 0,function e(t,a){if(16&a||32&a&&ab(t.deps,t)){let e=aj(t);aw(t);try{t.fn()}finally{aj(e),ay(t)}return}32&a&&(t.flags=-33&a);let r=t.deps;for(;void 0!==r;){let t=r.dep,a=t.flags;64&a&&e(t,t.flags=-65&a),r=r.nextDep}}(e,e.flags&=-65)}a_=0,ax=0}function aP(){let a=this.flags;if(16&a||32&a&&ab(this.deps,this)){if(aA(this)){let e=this.subs;void 0!==e&&ak(e)}}else 32&a&&(this.flags=-33&a);return void 0!==e?ap(this,e):void 0!==t&&ap(this,t),this.value}function aq(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(ag(e),av||aE())}}else{let t=this.value;if(16&this.flags&&aC(this,t)){let e=this.subs;void 0!==e&&ak(e)}return void 0!==e&&ap(this,e),t}}function aO(){let e=this.deps;for(;void 0!==e;)e=af(e,this);let t=this.subs;void 0!==t&&af(t),this.flags=0}function aT(e){let{pageSize:t,initialPage:a,...r}=e||{},n=t??10;return new URLSearchParams({...Object.entries(r).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),limit:n+"",offset:((a??1)-1)*n+""})}class aU{static #eh="/billing";static path(e,t){let{orgId:a}=t||{},r=a?`/organizations/${a}`:"/me";return`${r}${aU.#eh}${e}`}getPlans=async e=>{let{for:t,orgId:a,minSeats:r,...n}=e||{},i={...n,payer_type:"organization"===t?"org":"user",org_id:a,min_seats:r};return await au._fetch({path:`${aU.#eh}/plans`,method:"GET",search:aT(i)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new a8(e))}})};getPlan=async e=>new a8(await au._fetch({path:`${aU.#eh}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await au._fetch({path:aU.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new re(e?.response));getStatements=async e=>{let{orgId:t,...a}=e;return await au._fetch({path:aU.path("/statements",{orgId:t}),method:"GET",search:aT(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new a4(e))}})};getStatement=async e=>new a4((await au._fetch({path:aU.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...a}=e;return await au._fetch({path:aU.path("/payment_attempts",{orgId:t}),method:"GET",search:aT(a)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new a1(e))}})};getPaymentAttempt=async e=>new a1(await au._fetch({path:aU.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...a}=e;return new a$((await au._fetch({path:aU.path("/checkouts",{orgId:t}),method:"POST",body:a}))?.response)};getCreditBalance=async e=>await au._fetch({path:aU.path("/credits",{orgId:e.orgId}),method:"GET"}).then(e=>new aQ(e?.response));getCreditHistory=async e=>await au._fetch({path:aU.path("/credits/history",{orgId:e.orgId}),method:"GET"}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new aX(e))}})}let aM=az({resource:null}),aR=az({error:null}),aN=az({status:"idle"}),aB=aS(()=>{let e=aM().resource,t=aR().error,a=aN().status;return{errors:aJ(t,{identifier:null,password:null,code:null}),fetchStatus:a,signIn:e?e.__internal_future:null}}),aD=az({resource:null}),aF=az({error:null}),aL=az({status:"idle"}),aW=aS(()=>{let e=aD().resource,t=aF().error,a=aL().status;return{errors:aJ(t,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:a,signUp:e?e.__internal_future:null}}),aK=az({resource:null}),aH=az({error:null}),aV=az({status:"idle"}),aG=aS(()=>{let e=aK().resource,t=aH().error,a=aV().status;return{errors:aJ(t,{emailAddress:null}),fetchStatus:a,waitlist:e}});function aJ(e,t){let a={fields:{...t},raw:null,global:null};if(!e)return a;if(!M(e))return a.raw=[e],a.global=[X(e)],a;function r(e){return"meta"in e&&e.meta&&"paramName"in e.meta&&void 0!==e.meta.paramName}return e.errors.some(r)?e.errors.forEach(e=>{if(a.raw?a.raw.push(e):a.raw=[e],r(e)){let t=eh(e.meta.paramName);t in a.fields&&(a.fields[t]=e)}}):(a.raw=[e],a.global=[X(e)]),a}class aZ extends au{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=tq(e.created_at)),e.updated_at&&(this.updatedAt=tq(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 a$ extends au{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 a5(e.payment_method):void 0,this.plan=new a8(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=tD(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tq(e.free_trial_ends_at)),this.payer=new aZ(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>tA(()=>this._basePatch({path:aU.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!M(e)||t>=4)return!1;let a=e?.status,r=409===a&&e.errors?.[0]?.code==="checkout_already_in_progress";return a>=500||r}})}class aY{resource=new a$(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 a$.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new a$(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 a$.clerk.setActive({session:a$.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,a){var r,n,i;return void 0===a$.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,n=this.signals,i=this.pendingOperations,async(e,t,a)=>{if(i.get(e))return i.get(e);let s=(async()=>{++av,n.errorSignal({error:null}),n.fetchSignal({status:"fetching"}),a?.(),--av||aE(),++av;try{return await t(),n.resourceSignal({resource:r}),{error:null}}catch(e){return n.errorSignal({error:e}),{error:e}}finally{i.delete(e),n.fetchSignal({status:"idle"}),--av||aE()}})();return i.set(e,s),s})(e,t,a)}}class aQ{balance;constructor(e){this.balance=e.balance?tO(e.balance):null}}class aX extends au{id;amount;sourceType;sourceId;createdAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=tO(e.amount),this.sourceType=e.source_type,this.sourceId=e.source_id,this.createdAt=tq(e.created_at)),this}}class a1 extends au{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;totals=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){let t;return e?(this.id=e.id,this.amount=tO(e.amount),this.paidAt=e.paid_at?tq(e.paid_at):null,this.failedAt=e.failed_at?tq(e.failed_at):null,this.updatedAt=tq(e.updated_at),this.paymentMethod=e.payment_method?new a5(e.payment_method):null,this.subscriptionItem=new rt(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status,this.totals=e.totals?{subtotal:tO((t=e.totals).subtotal),grandTotal:tO(t.grand_total),taxTotal:tO(t.tax_total),baseFee:t.base_fee?tO(t.base_fee):null,perUnitTotals:t.per_unit_totals?tU(t.per_unit_totals):void 0,discounts:t.discounts?tN(t.discounts):null}:null,this):this}}let a0="/payment_methods",a2=async e=>{let{orgId:t,...a}=e;return new a6((await au._fetch({path:aU.path(`${a0}/initialize`,{orgId:t}),method:"POST",body:a}))?.response)},a9=async e=>{let{orgId:t,...a}=e;return new a5((await au._fetch({path:aU.path(a0,{orgId:t}),method:"POST",body:a}))?.response)},a3=async e=>{let{orgId:t,...a}=e??{};return await au._fetch({path:aU.path(a0,{orgId:t}),method:"GET",search:aT(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new a5(e))}})};class a5 extends au{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:tq(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tq(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new rI((await au._fetch({path:aU.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await au._fetch({path:aU.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class a6 extends au{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 a8 extends au{id;name;fee=null;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;unitPrices;availablePrices;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=e.fee?tO(e.fee):null,this.annualFee=e.annual_fee?tO(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?tO(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 rX(e)),this.unitPrices=e.unit_prices?.map(tM),this.availablePrices=e.available_prices?.map(e=>({id:e.id,fee:e.fee?tO(e.fee):null,annualMonthlyFee:e.annual_monthly_fee?tO(e.annual_monthly_fee):null,isDefault:e.is_default,unitPrices:e.unit_prices?.map(tM)}))),this}}class a4 extends au{id;status;timestamp;totals;groups;constructor(e){super(),this.fromJSON(e)}fromJSON(e){var t;let a;return e?(this.id=e.id,this.status=e.status,this.timestamp=tq(e.timestamp),this.totals=(a={grandTotal:tO((t=e.totals).grand_total),subtotal:tO(t.subtotal),taxTotal:tO(t.tax_total)},"base_fee"in t&&t.base_fee&&(a.baseFee=tO(t.base_fee)),"past_due"in t&&(a.pastDue=t.past_due?tO(t.past_due):null),"credit"in t&&(a.credit=t.credit?tO(t.credit):null),"per_unit_totals"in t&&(a.perUnitTotals=t.per_unit_totals?tU(t.per_unit_totals):void 0),"credits"in t&&(a.credits=t.credits?tR(t.credits):null),"total_due_now"in t&&(a.totalDueNow=tO(t.total_due_now)),"total_due_after_free_trial"in t&&(a.totalDueAfterFreeTrial=t.total_due_after_free_trial?tO(t.total_due_after_free_trial):null),"discounts"in t&&(a.discounts=t.discounts?tN(t.discounts):null),"total_due_per_period"in t&&t.total_due_per_period&&(a.totalDuePerPeriod=tO(t.total_due_per_period)),"totals_due_per_period"in t&&t.totals_due_per_period&&(a.totalsDuePerPeriod=tB(t.totals_due_per_period)),a),this.groups=e.groups.map(e=>new a7(e)),this):this}}class a7{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tq(e.timestamp),this.items=e.items.map(e=>new a1(e))),this}}class re extends au{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=tq(e.created_at),this.updatedAt=e.updated_at?tq(e.updated_at):null,this.activeAt=tq(e.active_at),this.pastDueAt=e.past_due_at?tq(e.past_due_at):null,this.nextPayment=void 0===e.next_payment?void 0:null===e.next_payment?null:tF(e.next_payment),this.subscriptionItems=(e.subscription_items||[]).map(e=>new rt(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1),this):this}}class rt extends au{id;plan;planPeriod;priceId;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;seats;credits;nextPayment;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e?(this.id=e.id,this.plan=new a8(e.plan),this.planPeriod=e.plan_period,this.priceId=e.price_id,this.status=e.status,this.createdAt=tq(e.created_at),this.pastDueAt=e.past_due_at?tq(e.past_due_at):null,this.periodStart=tq(e.period_start),this.periodEnd=e.period_end?tq(e.period_end):null,this.canceledAt=e.canceled_at?tq(e.canceled_at):null,this.amount=e.amount?tO(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:tO(e.credit.amount)}:void 0,this.seats=e.seats?{quantity:e.seats.quantity,...e.seats.tiers?{tiers:e.seats.tiers.map(tT)}:{}}:void 0,this.credits=e.credits?tR(e.credits):void 0,this.nextPayment=void 0===e.next_payment?void 0:null===e.next_payment?null:tF(e.next_payment),this.isFreeTrial=this.withDefault(e.is_free_trial,!1),this):this}async cancel(e){let{orgId:t}=e;return new rI((await au._fetch({path:aU.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let ra="token:update",rr="user:signOut",rn="environment:update",ri="session:tokenResolved",rs=z(),ro={build:(e,t,a)=>[e,t,a].filter(Boolean).join("-"),parse:(e,t,a)=>{let r=ro.extractTemplate(e,t,a);return{organizationId:a,sessionId:t,template:r}},extractTemplate:(e,t,a)=>{if(e===t||a&&e===`${t}-${a}`)return;let r=e.slice(t.length+1);return a&&r.endsWith(`-${a}`)&&(r=r.slice(0,-(a.length+1))),r||void 0}};var rl=n(8591),rc='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 ru=(e,t={})=>{if("u"<typeof Worker)return null;try{let a=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(a);return new Worker(r,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},rd=()=>{let e=0,t=()=>e++,a=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{a.get(e.data.id)?.()},i=ru(rc,{name:"clerk-timers"});if(i?.addEventListener("message",n),!i)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:rl.t};let s=()=>{i||(i=ru(rc,{name:"clerk-timers"}),i?.addEventListener("message",n))};return{setTimeout:(e,n)=>{s();let o=t();return a.set(o,()=>{e(),a.delete(o)}),r(i,{type:"setTimeout",id:o,ms:n}),o},setInterval:(e,n)=>{s();let o=t();return a.set(o,e),r(i,{type:"setInterval",id:o,ms:n}),o},clearTimeout:e=>{s(),a.delete(e),r(i,{type:"clearTimeout",id:e})},clearInterval:e=>{s(),a.delete(e),r(i,{type:"clearInterval",id:e})},cleanup:()=>{i&&(i.terminate(),i=null,a.clear())}}};var rh=n(8388),rm=n.n(rh);class rp{lock=(function(e){let t=new(rm());return{acquireLockAndRun:async a=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,r=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(e,{signal:t.signal},async()=>(clearTimeout(r),await a())).catch(()=>!1)}if(await t.acquireLock(e,5e3))try{return await a()}finally{await t.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=rd();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}}let rf="clerk";function rg(e){return"getRawString"in e?e.jwt:e}function rb(e,t){if(null==e)return t;let a=rg(e)?.header?.oiat,r=rg(t)?.header?.oiat;return null==a&&null==r?t:null==r?e:null==a?t:a>r?e:a<r?t:(rg(e)?.claims?.iat??0)>(rg(t)?.claims?.iat??0)?e:t}function ry(e){return rg(e)?.header?.oiat}function rw(e){return rg(e)?.claims?.sid}function rk(e){let t=rg(e)?.claims;return t?.org_id||(t?.o?.id??"")}let rv={broadcast:!0},r_={broadcast:!1},rx=(s=new Map,o={get:e=>s.get(e),set:(e,t)=>{s.set(e,t)},delete:e=>{s.delete(e)},clear:()=>{s.clear()},forEach:e=>{s.forEach((t,a)=>e(t,a))},size:()=>s.size},l=((e=rf)=>({toKey:({tokenId:t,audience:a})=>[e,t,a||""].join("::")}))(C),c=Math.random().toString(36).slice(2),u=null,(d=()=>u||("u"<typeof BroadcastChannel?null:((u=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{m(e)}),u)))(),h=e=>{d();let t=l.toKey(e),a=o.get(t);if(!a)return;let r=Math.floor(Date.now()/1e3)-a.createdAt;if((a.expiresIn??1/0)-r<=5){void 0!==a.timeoutId&&clearTimeout(a.timeoutId),void 0!==a.refreshTimeoutId&&clearTimeout(a.refreshTimeoutId),o.delete(t);return}return{entry:a.entry}},m=async({data:e})=>{let t,a=ro.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==a)return void tj.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:a,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:c,template:e.template,traceId:e.traceId},"tokenCache");try{t=new nF({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){tj.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:c,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let r=t.jwt?.claims?.iat,n=t.jwt?.claims?.exp;if(!r||!n)return void tj.warn("Token missing iat/exp claim, skipping cache update",{tabId:c,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let a=h({tokenId:e.tokenId});if(a){let r=a.entry.resolvedToken??await a.entry.tokenResolver;if(rb(r,t)===r)return void tj.debug("Ignoring staler token broadcast",{tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){tj.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:c,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}tj.info("Updating token cache from broadcast",{iat:r,organizationId:e.organizationId,tabId:c,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),p({createdAt:r,tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},r_)},p=(e,t=rv)=>{let a=l.toKey({audience:e.audience,tokenId:e.tokenId}),r=o.get(a);clearTimeout(r?.timeoutId),clearTimeout(r?.refreshTimeoutId);let n=Math.floor(Date.now()/1e3),i={createdAt:e.createdAt??n,entry:e,expiresIn:void 0},s=r?.entry.resolvedToken;i.baseline=s?rb(r?.baseline,s):r?.baseline;let d=e=>{o.get(a)===e&&(clearTimeout(e.timeoutId),clearTimeout(e.refreshTimeoutId),o.delete(a))};o.set(a,i),e.tokenResolver.then(r=>{let n=o.get(a);if(!n)return;let s=r.jwt?.claims,l=!!s&&"number"==typeof s.exp&&"number"==typeof s.iat,h=n===i;if(h&&!l)return void d(n);if(!l)return;let m=rb(n.baseline,r);if(n.baseline=m,!h&&void 0===n.entry.resolvedToken)return;let p=rb(n.entry.resolvedToken,m);if(p===n.entry.resolvedToken)return;n.entry.resolvedToken=p;let f=p.jwt?.claims;if(!f||"number"!=typeof f.exp||"number"!=typeof f.iat)return void d(n);clearTimeout(n.timeoutId),clearTimeout(n.refreshTimeoutId);let g=f.exp,b=f.iat,y=g-b,w=g-Math.floor(Date.now()/1e3);if(n.createdAt=b,n.expiresIn=y,w<=0)return void d(n);let k=setTimeout(()=>d(n),1e3*w);n.timeoutId=k,"function"==typeof k.unref&&k.unref();let v=w-15-2;if(v>0&&n.entry.onRefresh){let e=setTimeout(()=>{n.entry.onRefresh?.()},1e3*v);n.refreshTimeoutId=e,"function"==typeof e.unref&&e.unref()}let _=u;if(_&&t.broadcast)try{let t=p.getRawString();if(t&&f.sid){let a=f.sid,r=f.org_id||f.o?.id,n=ro.extractTemplate(e.tokenId,a,r),i=ro.build(a,n,r);if(e.tokenId===i){let i=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;tj.info("Broadcasting token update to other tabs",{organizationId:r,sessionId:a,tabId:c,template:n,tokenId:e.tokenId,traceId:i},"tokenCache");let s={organizationId:r,sessionId:a,template:n,tokenId:e.tokenId,tokenRaw:t,traceId:i};_.postMessage(s)}}}catch(t){tj.warn("Failed to broadcast token update to other tabs",{error:t,tabId:c,tokenId:e.tokenId},"tokenCache")}}).catch(()=>{d(i)})},{clear:()=>{o.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId),void 0!==e.refreshTimeoutId&&clearTimeout(e.refreshTimeoutId)}),o.clear()},close:()=>{u&&(u.close(),u=null)},get:h,set:e=>{d(),p(e,rv)},size:()=>o.size()});function rj(e){if(!e)return;let t=e.client||e.meta?.client;return t?rz.getOrCreateInstance().fromJSON(t):void 0}class rz extends au{static instance;pathRoot="/client";sessions=[];signUp=new nU;signIn=new nq;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return rz.instance||(rz.instance=new rz(e)),rz.instance}static clearInstance(){rz.instance=null}static isClientResource(e){return!!e&&e instanceof rz}constructor(e=null){super(),this.fromJSON(e)}get signUpAttempt(){return this.signUp}get signInAttempt(){return this.signIn}get signedInSessions(){return this.sessions.filter(e=>"active"===e.status||"pending"===e.status)}create(){return this._basePut()}fetch({fetchMaxTries:e,abortSignal:t}={}){return this._baseGet({fetchMaxTries:e,abortSignal:t})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{rx.clear(),this.id="",this.sessions=[],this.signUp=new nU(null),this.signIn=new nq(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=>(rx.clear(),e))}resetSignIn(){this.signIn=new nq(null),rs.emit("resource:error",{resource:this.signIn,error:null})}resetSignUp(){this.signUp=new nU(null),rs.emit("resource:error",{resource:this.signUp,error:null})}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return au.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 ny(e)),e.sign_up&&this.signUp instanceof nU&&this.signUp.id===e.sign_up.id?this.signUp.__internal_updateFromJSON(e.sign_up):this.signUp=new nU(e.sign_up),e.sign_in&&this.signIn instanceof nq&&this.signIn.id===e.sign_in.id?this.signIn.__internal_updateFromJSON(e.sign_in):this.signIn=new nq(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tq(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tq(e.created_at||void 0),this.updatedAt=tq(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 rS extends au{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 rI{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 rA extends au{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}function rC({delayInMs:e}={delayInMs:1e3}){let t,a=rd(),r=!1,n=()=>{t&&(a.clearTimeout(t),a.cleanup()),r=!0},i=async s=>{r=!1,await s(n),r||(t=a.setTimeout(()=>{i(s)},e))};return{run:i,stop:n}}class rE extends au{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}=rC();return{startEmailLinkFlow:async({redirectUrl:a})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=rC();return{startEnterpriseSSOLinkFlow:async({redirectUrl:a})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:a})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEnterpriseSSOLinkFlow:t}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new rF(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new r1(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 rP=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,"/")),a=t.length,r=new Uint8Array(a);for(let e=0;e<a;e++)r[e]=t.charCodeAt(e);return r.buffer}};async function rq(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new K("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 K(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new K(t.message,{code:"passkey_registration_cancelled"}):rU(t),publicKeyCredential:null}}}let rO=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 rT({publicKeyOptions:e,conditionalUI:t}){try{let a=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:rO.createAbortSignal()});if(!a)return{error:new K("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:a,error:null}}catch(e){var a;return{error:"NotAllowedError"===(a=e).name?new K(a.message,{code:"passkey_retrieval_cancelled"}):rU(a),publicKeyCredential:null}}}function rU(e){return"AbortError"===e.name?new K(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new K(e.message,{code:"passkey_invalid_rpID_or_domain",docsUrl:"https://clerk.com/docs/deployments/overview#authentication-across-subdomains"}):e}function rM(e){let t=rD(e.challenge),a=(e.allowCredentials||[]).map(e=>({...e,id:rD(e.id)}));return{...e,allowCredentials:a,challenge:t}}function rR(e){return{type:e.type,id:e.id,rawId:rB(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function rN(e){let t=e.response;return{...rR(e),response:{clientDataJSON:rB(t.clientDataJSON),authenticatorData:rB(t.authenticatorData),signature:rB(t.signature),userHandle:t.userHandle?rB(t.userHandle):null}}}let rB=rP.encode.bind(rP),rD=rP.decode.bind(rP);class rF extends au{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===au.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=tq(e.expire_at||void 0),this.error=e.error?new T(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,seats_quantity_to_add:e?.meta?.seatsQuantityToAdd,seats_quantity:e?.meta?.seatsQuantity}}),verified_at_client:this.verifiedAtClient}}}class rL extends rF{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let a,r,n;return super.fromJSON(e),e?.nonce&&(this.publicKey=(a=rD((t=JSON.parse(e.nonce)).user.id),r=rD(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:rD(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:a}})),this}}class rW{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new rK(e.email_address),this.phoneNumber=new rK(e.phone_number),this.web3Wallet=new rK(e.web3_wallet),this.externalAccount=new rF(e.external_account)):(this.emailAddress=new rK(null),this.phoneNumber=new rK(null),this.web3Wallet=new rK(null),this.externalAccount=new rF(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 rK extends rF{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 rH extends au{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?tq(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new rF(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new rV(e.enterprise_connection))),this}destroy=()=>this._baseDelete();__internal_toSnapshot(){return{object:"enterprise_account",id:this.id,provider:this.provider,protocol:this.protocol,provider_user_id:this.providerUserId,active:this.active,email_address:this.emailAddress,first_name:this.firstName,last_name:this.lastName,public_metadata:this.publicMetadata,verification:this.verification?.__internal_toSnapshot()||null,enterprise_connection:this.enterpriseConnection?.__internal_toSnapshot()||null,last_authenticated_at:this.lastAuthenticatedAt?this.lastAuthenticatedAt.getTime():null,enterprise_connection_id:this.enterpriseConnectionId}}}class rV extends au{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;allowOrganizationAccountLinking;createdAt;updatedAt;enterpriseConnectionId="";constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.domain=e.domain,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url,this.syncUserAttributes=e.sync_user_attributes,this.allowSubdomains=e.allow_subdomains,this.allowIdpInitiated=e.allow_idp_initiated,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.allowOrganizationAccountLinking=e.allow_organization_account_linking,this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at),this.enterpriseConnectionId=e.enterprise_connection_id),this}__internal_toSnapshot(){return{object:"enterprise_account_connection",id:this.id,name:this.name,domain:this.domain,active:this.active,protocol:this.protocol,provider:this.provider,logo_public_url:this.logoPublicUrl,sync_user_attributes:this.syncUserAttributes,allow_subdomains:this.allowSubdomains,allow_idp_initiated:this.allowIdpInitiated,disable_additional_identifications:this.disableAdditionalIdentifications,allow_organization_account_linking:this.allowOrganizationAccountLinking,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class rG extends au{id;name;active;provider;logoPublicUrl=null;domains=[];organizationId=null;syncUserAttributes;disableAdditionalIdentifications;allowOrganizationAccountLinking;customAttributes=[];oauthConfig=null;samlConnection=null;createdAt=null;updatedAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){var t,a;return e?(this.id=e.id,this.name=e.name,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url??null,this.domains=e.domains??[],this.organizationId=e.organization_id??null,this.syncUserAttributes=e.sync_user_attributes,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.allowOrganizationAccountLinking=e.allow_organization_account_linking??!1,this.customAttributes=e.custom_attributes??[],this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at),this.samlConnection=e.saml_connection?{id:(t=e.saml_connection).id,name:t.name,active:t.active,idpEntityId:t.idp_entity_id,idpSsoUrl:t.idp_sso_url,idpCertificate:t.idp_certificate,idpCertificateIssuedAt:t.idp_certificate_issued_at,idpCertificateExpiresAt:t.idp_certificate_expires_at,idpMetadataUrl:t.idp_metadata_url,idpMetadata:t.idp_metadata,acsUrl:t.acs_url,spEntityId:t.sp_entity_id,spMetadataUrl:t.sp_metadata_url,allowSubdomains:t.allow_subdomains,allowIdpInitiated:t.allow_idp_initiated,forceAuthn:t.force_authn}:null,this.oauthConfig=e.oauth_config?{id:(a=e.oauth_config).id,name:a.name,clientId:a.client_id,providerKey:a.provider_key,discoveryUrl:a.discovery_url,logoPublicUrl:a.logo_public_url,requiresPkce:a.requires_pkce,createdAt:tq(a.created_at),updatedAt:tq(a.updated_at)}:null,this):this}__internal_toSnapshot(){var e,t;return{object:"enterprise_connection",id:this.id,name:this.name,active:this.active,provider:this.provider,logo_public_url:this.logoPublicUrl,domains:this.domains,organization_id:this.organizationId,sync_user_attributes:this.syncUserAttributes,disable_additional_identifications:this.disableAdditionalIdentifications,allow_organization_account_linking:this.allowOrganizationAccountLinking,custom_attributes:this.customAttributes,saml_connection:this.samlConnection?{id:(e=this.samlConnection).id,name:e.name,active:e.active,idp_entity_id:e.idpEntityId,idp_sso_url:e.idpSsoUrl,idp_certificate:e.idpCertificate,idp_certificate_issued_at:e.idpCertificateIssuedAt,idp_certificate_expires_at:e.idpCertificateExpiresAt,idp_metadata_url:e.idpMetadataUrl,idp_metadata:e.idpMetadata,acs_url:e.acsUrl,sp_entity_id:e.spEntityId,sp_metadata_url:e.spMetadataUrl,allow_subdomains:e.allowSubdomains,allow_idp_initiated:e.allowIdpInitiated,force_authn:e.forceAuthn}:void 0,oauth_config:this.oauthConfig?{id:(t=this.oauthConfig).id,name:t.name,client_id:t.clientId,provider_key:t.providerKey,discovery_url:t.discoveryUrl,logo_public_url:t.logoPublicUrl,requires_pkce:t.requiresPkce,created_at:t.createdAt?.getTime()??0,updated_at:t.updatedAt?.getTime()??0}:void 0,created_at:this.createdAt?.getTime()??0,updated_at:this.updatedAt?.getTime()??0}}}class rJ{pathRoot="/me";id;status;connectionType;parsedUserInfo=null;logs=[];saml=null;oauth=null;createdAt=null;constructor(e){this.fromJSON(e)}reload(e){ae("EnterpriseConnectionTestRun")}fromJSON(e){var t,a,r;return e&&(this.id=e.id,this.status=e.status,this.connectionType=e.connection_type,this.parsedUserInfo=(t=e.parsed_user_info??null)?{emailAddress:t.email_address,firstName:t.first_name,lastName:t.last_name,userId:t.user_id}:null,this.saml=(a=e.saml??null)?{samlRequest:a.saml_request,samlResponse:a.saml_response,relayState:a.relay_state}:null,this.oauth=(r=e.oauth??null)?{idToken:r.id_token,accessToken:r.access_token,userInfo:r.user_info}:null,this.createdAt=tq(e.created_at),this.logs=(e.logs??[]).map(e=>({level:e.level,code:e.code,shortMessage:e.short_message,message:e.message}))),this}__internal_toSnapshot(){var e,t,a;return{object:"enterprise_connection_test_run",id:this.id,status:this.status,connection_type:this.connectionType,parsed_user_info:(e=this.parsedUserInfo)?{email_address:e.emailAddress,first_name:e.firstName,last_name:e.lastName,user_id:e.userId}:null,saml:(t=this.saml)?{saml_request:t.samlRequest,saml_response:t.samlResponse,relay_state:t.relayState}:null,oauth:(a=this.oauth)?{id_token:a.idToken,access_token:a.accessToken,user_info:a.userInfo}:null,logs:this.logs.map(e=>({level:e.level,code:e.code,short_message:e.shortMessage,message:e.message})),created_at:this.createdAt?.getTime()??0}}}class rZ extends au{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 r$ extends au{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};organizationCreationDefaults={enabled:!1};enabled=!1;maxAllowedMemberships=1;forceOrganizationSelection;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.actions&&(this.actions.adminDelete=this.withDefault(e.actions.admin_delete,this.actions.adminDelete)),e.domains&&(this.domains.enabled=this.withDefault(e.domains.enabled,this.domains.enabled),this.domains.enrollmentModes=this.withDefault(e.domains.enrollment_modes,this.domains.enrollmentModes),this.domains.defaultRole=this.withDefault(e.domains.default_role,this.domains.defaultRole)),e.slug&&(this.slug.disabled=this.withDefault(e.slug.disabled,this.slug.disabled)),e.organization_creation_defaults&&(this.organizationCreationDefaults.enabled=this.withDefault(e.organization_creation_defaults.enabled,this.organizationCreationDefaults.enabled)),this.enabled=this.withDefault(e.enabled,this.enabled),this.maxAllowedMemberships=this.withDefault(e.max_allowed_memberships,this.maxAllowedMemberships),this.forceOrganizationSelection=this.withDefault(e.force_organization_selection,this.forceOrganizationSelection)),this}__internal_toSnapshot(){return{actions:{admin_delete:this.actions.adminDelete},domains:{enabled:this.domains.enabled,enrollment_modes:this.domains.enrollmentModes,default_role:this.domains.defaultRole},enabled:this.enabled,max_allowed_memberships:this.maxAllowedMemberships}}}class rY extends au{static instance;authConfig=new ah;displayConfig=new rA;maintenanceMode=!1;clientDebugMode=!1;partitionedCookies=!1;pathRoot="/environment";userSettings=new nX;organizationSettings=new r$;commerceSettings=new rS;apiKeysSettings=new rZ;protectConfig=new no;static getInstance(){return rY.instance||(rY.instance=new rY),rY.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new ah(e.auth_config),this.displayConfig=new rA(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.partitionedCookies=this.withDefault(e.partitioned_cookies,this.partitionedCookies),this.organizationSettings=new r$(e.organization_settings),this.userSettings=new nX(e.user_settings),this.commerceSettings=new rS(e.commerce_settings),this.apiKeysSettings=new rZ(e.api_keys_settings),this.protectConfig=new no(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(rs.emit(rn,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,partitioned_cookies:this.partitionedCookies,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class rQ extends au{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:a}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:a}})};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 rF(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 rX extends au{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 r1 extends au{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 r0 extends au{id;name=null;publicUrl=null;static async create(e,t={}){let a,r=t;return"string"==typeof t.file?(r=t.file,a=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(r=new FormData).append("file",t.file),new r0((await au._fetch({path:e,method:"POST",body:r,headers:a}))?.response)}static async delete(e){return new r0((await au._fetch({path:e,method:"DELETE"}))?.response)}constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.publicUrl=e.public_url),this}}function r2(e,t={}){let a={};r9(a,"provider",e.provider),r9(a,"name",e.name);let r=e.domains;return r&&r.length>0&&(a.domains=r),t.omitOrganizationId||r9(a,"organization_id",e.organizationId),r9(a,"active",e.active),r9(a,"sync_user_attributes",e.syncUserAttributes),r9(a,"disable_additional_identifications",e.disableAdditionalIdentifications),r9(a,"custom_attributes",e.customAttributes),e.saml&&(r9(a,"saml_idp_entity_id",e.saml.idpEntityId),r9(a,"saml_idp_sso_url",e.saml.idpSsoUrl),r9(a,"saml_idp_certificate",e.saml.idpCertificate),r9(a,"saml_idp_metadata_url",e.saml.idpMetadataUrl),r9(a,"saml_idp_metadata",e.saml.idpMetadata),r9(a,"saml_attribute_mapping",e.saml.attributeMapping),r9(a,"saml_allow_subdomains",e.saml.allowSubdomains),r9(a,"saml_allow_idp_initiated",e.saml.allowIdpInitiated),r9(a,"saml_force_authn",e.saml.forceAuthn)),e.oidc&&(r9(a,"oidc_client_id",e.oidc.clientId),r9(a,"oidc_client_secret",e.oidc.clientSecret),r9(a,"oidc_discovery_url",e.oidc.discoveryUrl),r9(a,"oidc_auth_url",e.oidc.authUrl),r9(a,"oidc_token_url",e.oidc.tokenUrl),r9(a,"oidc_user_info_url",e.oidc.userInfoUrl),r9(a,"oidc_requires_pkce",e.oidc.requiresPkce)),a}function r9(e,t,a){void 0!==a&&(e[t]=a)}class r3 extends au{id;name;organizationId;enrollmentMode;verification;affiliationVerification;ownershipVerification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t,enrollmentMode:a}){return new r3((await au._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t,enrollment_mode:a}}))?.response)}prepareAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/prepare_affiliation_verification`,method:"POST",body:e});attemptAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/attempt_affiliation_verification`,method:"POST",body:e});updateEnrollmentMode=e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/update_enrollment_mode`,body:e});delete=()=>this._baseDelete({path:`/organizations/${this.organizationId}/domains/${this.id}`});fromJSON(e){if(e){this.id=e.id,this.name=e.name,this.organizationId=e.organization_id,this.enrollmentMode=e.enrollment_mode,this.affiliationEmailAddress=e.affiliation_email_address,this.totalPendingSuggestions=e.total_pending_suggestions,this.totalPendingInvitations=e.total_pending_invitations;let t=e.affiliation_verification??e.verification;if(t){let e={status:t.status,strategy:t.strategy,attempts:t.attempts,expiresAt:tq(t.expires_at)};this.affiliationVerification=e,this.verification=e}else this.affiliationVerification=null,this.verification=null;e.ownership_verification?this.ownershipVerification={status:e.ownership_verification.status,strategy:e.ownership_verification.strategy,attempts:e.ownership_verification.attempts,expiresAt:e.ownership_verification.expire_at?tq(e.ownership_verification.expire_at):null,verifiedAt:e.ownership_verification.verified_at?tq(e.ownership_verification.verified_at):null,txtRecordName:e.ownership_verification.txt_record_name??null,txtRecordValue:e.ownership_verification.txt_record_value??null}:this.ownershipVerification=null}return this}}class r5 extends au{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=tq(e.created_at),this.updatedAt=tq(e.updated_at),e.public_user_data&&(this.publicUserData=new nl(e.public_user_data))),this}}class r6 extends au{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=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}}class r8 extends au{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 r6(e)),this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}}class r4 extends au{pathRoot="/organizations";id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;selfServeSSOEnabled=!1;exclusiveMembership=!1;constructor(e){super(),this.fromJSON(e)}static async create(e){return new r4((await au._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new r4((await au._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await au._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:aT(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a,has_role_set_migration:r}=e?.response;return{data:t.map(e=>new r8(e)),total_count:a,has_role_set_migration:r}});getDomains=async e=>{let{enrollmentMode:t,...a}=e||{},r=aT(a);return t&&r.set("enrollment_mode",t),await au._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:r},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new r3(e))}})};getDomain=async({domainId:e})=>new r3((await au._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getEnterpriseConnections=async e=>{let{withOrganizationAccountLinking:t}=e||{};return((await au._fetch({path:`/organizations/${this.id}/enterprise_connections`,method:"GET",...void 0!==t?{search:{with_organization_account_linking:String(t)}}:{}}))?.response||[]).map(e=>new rG(e))};createEnterpriseConnection=async e=>new rG((await au._fetch({path:`/organizations/${this.id}/enterprise_connections`,method:"POST",body:r2(e,{omitOrganizationId:!0})}))?.response);updateEnterpriseConnection=async(e,t)=>new rG((await au._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}`,method:"PATCH",body:r2(t,{omitOrganizationId:!0})}))?.response);deleteEnterpriseConnection=async e=>new rI((await au._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}`,method:"DELETE"}))?.response);createEnterpriseConnectionTestRun=async e=>({url:((await au._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/test_runs`,method:"POST"}))?.response).url});getEnterpriseConnectionTestRuns=async(e,t)=>{let{status:a,...r}=t||{},n=aT(r);if(a?.length)for(let e of a)n.append("status",e);let i=await au._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/test_runs`,method:"GET",search:n}),s=i?.response;return{total_count:s?.total_count??0,data:(s?.data??[]).map(e=>new rJ(e))}};getMembershipRequests=async e=>await au._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:aT(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new r5(e))}});createDomain=async(e,t)=>r3.create(this.id,{name:e,enrollmentMode:t?.enrollmentMode});prepareOwnershipVerification=async e=>this.bulkOwnershipVerification("prepare_ownership_verification",e);attemptOwnershipVerification=async e=>this.bulkOwnershipVerification("attempt_ownership_verification",e);bulkOwnershipVerification=async(e,t)=>{let{data:a,errors:r}=(await au._fetch({path:`/organizations/${this.id}/domains/${e}/bulk`,method:"POST",body:{organization_domain_ids:t}},{forceUpdateClient:!0}))?.response;return{data:(a??[]).map(e=>new r3(e)),errors:r??[]}};getMemberships=async e=>await au._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:aT({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new ne(e))}});getInvitations=async e=>await au._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:aT(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new r7(e))}});addMember=async({userId:e,role:t})=>await au._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new ne(e?.response));inviteMember=async e=>r7.create(this.id,e);inviteMembers=async e=>r7.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await au._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new ne(e?.response));removeMember=async e=>await au._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new ne(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,a;return null===e?await au._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new r4(e?.response)):("string"==typeof e?(t=e,a=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await au._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:a}).then(e=>new r4(e?.response)))};initializePaymentMethod=e=>a2({...e,orgId:this.id});addPaymentMethod=e=>a9({...e,orgId:this.id});getPaymentMethods=e=>a3({...e,orgId:this.id});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.slug=e.slug,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.publicMetadata=e.public_metadata||{},this.membersCount=e.members_count||0,this.pendingInvitationsCount=e.pending_invitations_count||0,this.maxAllowedMemberships=e.max_allowed_memberships||0,this.adminDeleteEnabled=e.admin_delete_enabled||!1,this.selfServeSSOEnabled=e.self_serve_sso_enabled||!1,this.exclusiveMembership=e.exclusive_membership||!1,this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization",id:this.id,name:this.name,slug:this.slug,image_url:this.imageUrl,has_image:this.hasImage,public_metadata:this.publicMetadata,members_count:this.membersCount,pending_invitations_count:this.pendingInvitationsCount,max_allowed_memberships:this.maxAllowedMemberships,admin_delete_enabled:this.adminDeleteEnabled,self_serve_sso_enabled:this.selfServeSSOEnabled,exclusive_membership:this.exclusiveMembership,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:t}=e||{},a=(await au._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(a)}}class r7 extends au{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:a}){return new r7((await au._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:a}}))?.response)}static async createBulk(e,t){let{emailAddresses:a,role:r}=t;return((await au._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:a,role:r}}))?.response).map(e=>new r7(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=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}}class ne extends au{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await au._fetch({path:"/me/organization_memberships",method:"GET",search:aT({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new ne(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 r4(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new nl(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tq(e.created_at),this.updatedAt=tq(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){ae("OrganizationMembership")}}class nt extends au{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await au._fetch({path:"/me/organization_suggestions",method:"GET",search:aT(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new nt(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=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}}function na(){return"u">typeof window&&w()&&"function"==typeof window.PublicKeyCredential}async function nr(){try{return na()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function nn(){try{return"u">typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class ni extends au{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return au._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new ni(e?.response))}static async attemptVerification(e,t){let a,r=(a=t.response,{...rR(t),response:{clientDataJSON:rB(a.clientDataJSON),attestationObject:rB(a.attestationObject),transports:a.getTransports()}});return au._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new ni(e?.response))}static async registerPasskey(){let e=ni.clerk.__internal_isWebAuthnSupported||na,t=ni.clerk.__internal_createPublicCredentials||rq,a=ni.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||nn;if(!e())throw new K("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:n}=r,i=n?.publicKey;if(i||at("create"),i.authenticatorSelection?.authenticatorAttachment==="platform"&&!await a())throw new K("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:s,error:o}=await t(i);if(!s)throw o;return this.attemptVerification(r.id,s)}update=e=>this._basePatch({body:e});delete=async()=>new rI((await au._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?tq(e.last_used_at):null,this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at),e.verification&&(this.verification=new rL(e.verification))),this}__internal_toSnapshot(){return{object:"passkey",id:this.id,name:this.name,verification:this.verification?.__internal_toSnapshot()||null,last_used_at:this.lastUsedAt?.getTime()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class ns extends au{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 rF(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new r1(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 no extends au{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 nl{firstName;lastName;imageUrl;hasImage;identifier;userId;username;banned;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name||null,this.lastName=e.last_name||null,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.identifier=e.identifier||"",this.userId=e.user_id,this.username=e.username,this.banned=e.banned??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,has_image:this.hasImage,identifier:this.identifier,user_id:this.userId,username:this.username,banned:this.banned}}}let nc={strict_mfa:{afterMinutes:10,level:"multi_factor"},strict:{afterMinutes:10,level:"second_factor"},moderate:{afterMinutes:60,level:"second_factor"},lax:{afterMinutes:1440,level:"second_factor"}},nu=new Set(["first_factor","second_factor","multi_factor"]),nd=new Set(["strict_mfa","strict","moderate","lax"]),nh=new Set(["o","org","organization"]),nm=new Set(["u","user"]),np=e=>"number"==typeof e&&Number.isFinite(e)&&(-1===e||e>=0),nf=(e,t)=>{let{org:a,user:r}=ng(e),[n,i]=t.split(":"),s=void 0!==i,o=i||n;if(s&&!nh.has(n)&&!nm.has(n))throw Error(`Invalid scope: ${n}`);if(s){if(nh.has(n))return a.includes(o);if(nm.has(n))return r.includes(o)}return[...a,...r].includes(o)},ng=e=>{let t=[],a=[];if(!e)return{org:t,user:a};let r=e.split(",");for(let e=0;e<r.length;e++){let n=r[e].trim(),i=n.indexOf(":");if(-1===i)throw Error(`Invalid claim element (missing colon): ${n}`);let s=n.slice(0,i),o=n.slice(i+1);"o"===s?t.push(o):"u"===s?a.push(o):("ou"===s||"uo"===s)&&(t.push(o),a.push(o))}return{org:t,user:a}};class nb extends au{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new rF(null);secondFactorVerification=new rF(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new ny(e.session),this.level=e.level,this.supportedFirstFactors=eg(e.supported_first_factors),this.supportedSecondFactors=eg(e.supported_second_factors),this.firstFactorVerification=new rF(e.first_factor_verification),this.secondFactorVerification=new rF(e.second_factor_verification)),this}}class ny extends au{pathRoot="/client/sessions";static #em=new Set;id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;agent;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof ny}constructor(e){super(),this.fromJSON(e),this.#ep(this.lastActiveToken)}end=()=>(rx.clear(),this._basePost({action:"end"}));remove=()=>(rx.clear(),this._basePost({action:"remove"}));_touchPost=async({intent:e,skipUpdateClient:t}={skipUpdateClient:!1})=>{let a=await au._fetch({method:"POST",path:this.path("touch"),body:{active_organization_id:this.lastActiveOrganizationId,intent:e}},{skipUpdateClient:t});return this.fromJSON(a?.response||a),a};touch=async({intent:e}={})=>(await this._touchPost({intent:e,skipUpdateClient:!1}),this.lastActiveToken&&rs.emit(ra,{token:this.lastActiveToken}),this);__internal_touch=async({intent:e}={})=>rj(await this._touchPost({intent:e,skipUpdateClient:!0}));clearCache=()=>rx.clear();getToken=async e=>{try{let t=await tA(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>(!V(e)||e?.status===429)&&(v()?t<=8:t<=3)});if(!t&&!v())throw new N("Network request failed while offline. The browser appears to be disconnected.");return t}catch(e){if(!v())throw new N("Network request failed while offline. The browser appears to be disconnected.");throw e}};checkAuthorization=e=>{let t,a=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(t={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:a?.organization?.id,orgRole:a?.role,orgPermissions:a?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{let a;return!!t.userId&&(a=[((e,t)=>{let{orgId:a,orgRole:r,orgPermissions:n}=t,i=void 0!==e.role,s=void 0!==e.permission;return i||s?i&&"string"!=typeof e.role||s&&"string"!=typeof e.permission||!a||i&&("string"!=typeof r||!r||r.replace(/^(org:)*/,"org:")!==e.role.replace(/^(org:)*/,"org:"))||s&&(!Array.isArray(n)||!n.includes(e.permission.replace(/^(org:)*/,"org:")))?"fail":"pass":"skip"})(e,t),((e,t)=>{let{features:a,plans:r}=t,n=void 0!==e.feature,i=void 0!==e.plan;if(!n&&!i)return"skip";if(n&&"string"!=typeof e.feature||i&&"string"!=typeof e.plan)return"fail";if(n){if("string"!=typeof a||!a)return"fail";try{if(!nf(a,e.feature))return"fail"}catch{return"fail"}}if(i){if("string"!=typeof r||!r)return"fail";try{if(!nf(r,e.plan))return"fail"}catch{return"fail"}}return"pass"})(e,t),((e,{factorVerificationAge:t})=>{if(void 0===e.reverification)return"skip";if(!t||!Array.isArray(t)||2!==t.length||!np(t[0])||!np(t[1]))return"fail";let a=(e=>{let t,a;if(!e)return!1;let r="string"==typeof e&&nd.has(e),n="object"==typeof e&&(t=e.level,nu.has(t))&&"number"==typeof(a=e.afterMinutes)&&a>0;return(!!r||!!n)&&(e=>"string"==typeof e?nc[e]:e).bind(null,e)})(e.reverification);if(!a)return"fail";let{level:r,afterMinutes:n}=a(),[i,s]=t;if(-1===i&&-1===s)return"fail";let o=-1!==i&&n>i,l=-1!==s&&n>s;switch(r){case"first_factor":return o?"pass":"fail";case"second_factor":if(-1===s)return o?"pass":"fail";return l?"pass":"fail";case"multi_factor":if(-1===s)return o?"pass":"fail";if(-1===i)return"fail";return o&&l?"pass":"fail"}})(e,t)]).some(e=>"pass"===e)&&a.every(e=>"pass"===e||"skip"===e)})(e)};#ep=e=>{if(e){let t=this.#ef();rx.set({tokenId:t,tokenResolver:Promise.resolve(e),onRefresh:()=>this.#eg(void 0,this.lastActiveOrganizationId,t,!0)})}};#ef(e,t){let a=void 0===t?this.lastActiveOrganizationId:t;return ro.build(this.id,e,a)}startVerification=async({level:e})=>new nb((await au._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:t6("Session.prepareFirstFactorVerification",e.strategy)}return new nb((await au._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(rN(e.publicKeyCredential))}:{...e},new nb((await au._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=ny.clerk.__internal_isWebAuthnSupported||na,a=ny.clerk.__internal_getPublicCredentials||rT;if(!t())throw new K("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?rM(JSON.parse(e)):null;r||at("get");let{publicKeyCredential:n,error:i}=await a({publicKeyOptions:r,conditionalUI:!1});if(!n)throw i;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:n})};prepareSecondFactorVerification=async e=>new nb((await au._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new nb((await au._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=tq(e.expire_at),this.abandonAt=tq(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tq(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.agent=e.actor?.type==="agent"?e.actor:null,this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at),this.user=new nZ(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new nl(e.public_user_data)),this.lastActiveToken=e.last_active_token?new nF(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){let t;if(!this.user)return null;let{skipCache:a=!1,template:r}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId,i=this.#ef(r,n),s=a?void 0:rx.get({tokenId:i}),o=!r&&n===this.lastActiveOrganizationId;if(s){let e=s.entry.resolvedToken??await s.entry.tokenResolver;o&&e.getRawString()&&rs.emit(ra,{token:e}),t=e.getRawString()||null}else if(k())t=await this.#eb(r,n,i,o,a);else throw new q("Browser is offline, skipping token fetch",{code:"network_error"});if(null===t&&!v())throw new q("Network request failed while offline",{code:"network_error"});return t}#ey(e,t,a){let r=e?`${this.path()}/tokens/${e}`:`${this.path()}/tokens`,n=ny.clerk?.__internal_environment?.authConfig?.sessionMinter,i=e?{}:{organizationId:t??null,...n&&this.lastActiveToken?{token:this.lastActiveToken.getRawString()}:{},...n&&a?{forceOrigin:"true"}:{}};if(n)return nF.create(r,i,a?{debug:"skip_cache"}:void 0);let s=this.lastActiveToken?.getRawString();return nF.create(r,i,a?{debug:"skip_cache"}:void 0).catch(e=>{if(R.is(e)&&s)return nF.create(r,{...i},{expired_token:s});throw e})}#ew(e,t){!t||e.getRawString()&&(rs.emit(ra,{token:e}),e.jwt&&!this.#ek(e)&&(this.lastActiveToken=e,rs.emit(ri,null)))}#ek(e){let t=this.lastActiveToken;return!!t?.jwt&&rw(t)===rw(e)&&(rk(t)||"")===(rk(e)||"")&&rb(t,e)!==e}#eb(e,t,a,r,n){tj.info("Fetching new token from API",{organizationId:t,template:e,tokenId:a},"session");let i=this.#ey(e,t,n);return rx.set({tokenId:a,tokenResolver:i,onRefresh:()=>this.#eg(e,t,a,r)}),i.then(e=>{let t=e.getRawString();if(!t)throw new q("Token fetch returned empty response",{code:"network_error"});return this.#ew(e,r),t})}#eg(e,t,a,r){if(ny.#em.has(a))return;ny.#em.add(a);let n=ny.clerk?.__internal_getOption?.("experimental"),i=n?.runtimeEnvironment==="headless",s=this.lastActiveToken?.jwt?.claims?.exp;i&&s&&Date.now()/1e3>s?ny.#em.delete(a):this.#ey(e,t,!1).then(n=>{n.getRawString()&&(rx.set({tokenId:a,tokenResolver:Promise.resolve(n),onRefresh:()=>this.#eg(e,t,a,r)}),this.#ew(n,r))}).catch(e=>{tj.warn("Background token refresh failed",{error:e,tokenId:a},"session")}).finally(()=>{ny.#em.delete(a)})}get currentTask(){let[e]=this.tasks??[];return e}}class nw extends au{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=au.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new nw(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=tq(e.expire_at),this.abandonAt=tq(e.abandon_at),this.lastActiveAt=tq(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 nk=(e,t,a)=>{let{onValidation:r=rl.t,onValidationComplexity:n=rl.t}=a||{},{show_zxcvbn:i,validatePassword:s}=t,o=e=>((e,t)=>{let{max_length:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o}=t,l=(e=>{let t;if(e.allowed_special_characters){let a=e.allowed_special_characters.replace("[","\\[");a=a.replace("]","\\]"),t=RegExp(`[${a}]`)}else t=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:a,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=a,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:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o},u=new Map;for(let e in c)c[e]&&!l[e]&&u.set(e,!0);return Object.freeze(Object.fromEntries(u))})(e,t),l=(({min_zxcvbn_strength:e,onResult:t})=>a=>r=>{let n=a(r);return(t?.(n),n.score>=e&&n.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:n}:n.score>=e?{state:"excellent",result:n}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...n.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:n}})(t),c={};return(t,a)=>{let{onValidation:u=r,onValidationComplexity:d=n}=a||{};if(!s)return;let h=o(t);d(0===Object.keys(h).length),c={...c,complexity:h},i&&e().then(e=>{let a=l(e)(t);u({...c={...c,strength:a},strength:a})}),c.complexity&&0===Object.keys(c.complexity).length&&i||u(c)}};function nv(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function n_(e,t,a,r,n){if(!e.client||!r.popup)return;let i=nv(e.frontendApi),{redirectUrl:s}=r,o=new URL(s);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",t);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${i}/popup-callback`),u=e.buildUrlWithAuth(`${i}/popup-callback?return_url=${encodeURIComponent(l)}`),d=async t=>{if(t.origin!==i)return;let a=!1;if(t.data.session){if(!e.client?.sessions.find(e=>e.id===t.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:t.data.session,redirectUrl:r.redirectUrlComplete}),a=!0}else t.data.return_url&&(e.navigate(t.data.return_url),a=!0);a&&window.removeEventListener("message",d)};window.addEventListener("message",d),await a({...r,redirectUrlComplete:c,redirectUrl:u},n)}function nx(e,{redirectCallbackUrl:t,redirectUrl:a}){let r=nv(e.frontendApi),n=new URL(t);n.searchParams.set("sign_in_force_redirect_url",a),n.searchParams.set("sign_up_force_redirect_url",a);let i=e.buildUrlWithAuth(n.toString()),s=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(i)}`),redirectUrl:s}}function nj(e,t){return new Promise((a,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===nv(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",n),a()):r())};window.addEventListener("message",n),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}let nz="oauth_callback_failed",nS=new Set(["external_account_not_found",ec]),nI={oauth_access_denied:"You did not grant access to your account."};async function nA(e){try{await e.create({})}catch{}}async function nC(e){let t,a=String(await e.transport.getRedirectUrl());if(await e.authenticateMethod({...e.params,redirectUrl:a},e=>{t=e}),!t)throw new q("OAuth transport did not receive a verification URL.",{code:"oauth_transport_missing_verification_url"});let{callbackUrl:r}=await e.transport.open(new URL(t.toString())),n=function(e){let t=new URL(e).searchParams;if("failed"!==t.get("__clerk_status"))return null;let a=t.get("__clerk_error_code")||nz;if(nS.has(a))return null;let r=nI[a]?a:nz;return{code:r,message:nI[r]||"OAuth callback failed."}}(r);if(n)throw await nA(e.resource),new q(n.message,{code:n.code});let i=new URL(r).searchParams.get("rotating_token_nonce");i?await e.resource.reload({rotatingTokenNonce:i}):await e.resource.reload(),await e.clerk.__internal_handleResourceCallback(e.resource,e.callbackParams)}async function nE(e,t){rs.emit("resource:error",{resource:e,error:null}),rs.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return rs.emit("resource:error",{resource:e,error:t}),{error:t}}finally{rs.emit("resource:fetch",{resource:e,status:"idle"})}}let nP=()=>{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:a,zxcvbn:r}=e,{dictionary:n,adjacencyGraphs:i}=t;return a.setOptions({dictionary:{...n},graphs:i}),r})}).loadZxcvbn};class nq extends au{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new rF(null);secondFactorVerification=new rF(null);identifier=null;createdSessionId=null;userData=new n$(null);clientTrustState;protectCheck=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tj.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new nO(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{tj.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t={...e},a=tV();if(a&&(t.locale=a),this.shouldRequireCaptcha(e)&&!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new al(nq.clerk),a=await e.managedOrInvisible({action:"signin"});if(!a)throw new q("",{code:"captcha_unavailable"});t={...t,...a}}return this._basePost({path:this.pathRoot,body:t})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(tj.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:t6("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor"})};submitProtectCheck=e=>(tj.debug("SignIn.submitProtectCheck",{id:this.id}),this._basePatch({action:"protect_check",body:{proof_token:e.proofToken}}));attemptFirstFactor=e=>{let t;return tj.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(rN(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=rC();return{startEmailLinkFlow:async({emailAddressId:a,redirectUrl:r})=>{this.id||t5("SignIn");let n={strategy:"email_link",emailAddressId:a,redirectUrl:r},i="needs_second_factor"===this.status||"needs_client_trust"===this.status,s=i?"secondFactorVerification":"firstFactorVerification";return i?await this.prepareSecondFactor(n):await this.prepareFirstFactor(n),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e[s].status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(tj.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(tj.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:a,redirectUrlComplete:r,identifier:n,oidcPrompt:i,continueSignIn:s,enterpriseConnectionId:o}=e||{},l=nq.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&s||await this.create({strategy:a,identifier:n,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===a&&await this.prepareFirstFactor({strategy:a,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:i,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:u}=this.firstFactorVerification;"unverified"===c&&u?t(u):t7(c,nq.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>{let t=nq.clerk.__internal_oauthTransport;return t?nC({clerk:nq.clerk,transport:t,resource:this,authenticateMethod:this.authenticateWithRedirectOrPopup,params:e,callbackParams:e.__internal_callbackParams??{}}):this.authenticateWithRedirectOrPopup(e,nq.clerk.__internal_windowNavigate)};authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||t4("popup"),n_(nq.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:a,generateSignature:r,strategy:n="web3_metamask_signature",walletName:i}=e||{},s=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&t4("generateSignature"),"solana"!==s||i||t4("walletName"),await this.create({identifier:a});let o=this.supportedFirstFactors?.find(e=>e.strategy===n);o||t8("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||t8("SignIn");try{t=await r({identifier:a,nonce:l,walletName:i,provider:s})}catch(e){if("coinbase_wallet"===s&&4001===e.code)t=await r({identifier:a,nonce:l,provider:s,walletName:i});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await tY().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await tY().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await tY().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await tY().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let t=await tY().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:t,generateSignature:t=>tY().generateSignatureWithSolana({...t,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},a=nq.clerk.__internal_isWebAuthnSupported||na,r=nq.clerk.__internal_getPublicCredentials||rT,n=nq.clerk.__internal_isWebAuthnAutofillSupported||nr;if(!a())throw new K("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(`${t2} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:i}=this.firstFactorVerification,s=i?rM(JSON.parse(i)):null;s||at("get");let o=!1;"autofill"===t&&(o=await n());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:s,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(nq.clerk.__internal_environment?.userSettings.passwordSettings)return nk(nP(),{...nq.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=eg(e.supported_first_factors),this.supportedSecondFactors=eg(e.supported_second_factors),this.firstFactorVerification=new rF(e.first_factor_verification),this.secondFactorVerification=new rF(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new n$(e.user_data),this.clientTrustState=e.client_trust_state??void 0,this.protectCheck=e.protect_check?{status:e.protect_check.status,token:e.protect_check.token,sdkUrl:e.protect_check.sdk_url,expiresAt:e.protect_check.expires_at,uiHints:e.protect_check.ui_hints}:null),rs.emit("resource:update",{resource:this}),this}clientBypass(){return nq.clerk.client?.captchaBypass}shouldRequireCaptcha(e){return"signUpIfMissing"in e&&!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=nq.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&nq.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=nq.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return"strategy"in e&&!!e.strategy&&t.some(t=>t===e.strategy)}__internal_updateFromJSON(e){return this.fromJSON(e)}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:ef(this.supportedFirstFactors),supported_second_factors:ef(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(),protect_check:this.protectCheck?{status:this.protectCheck.status,token:this.protectCheck.token,sdk_url:this.protectCheck.sdkUrl,...void 0!==this.protectCheck.expiresAt&&{expires_at:this.protectCheck.expiresAt},...void 0!==this.protectCheck.uiHints&&{ui_hints:this.protectCheck.uiHints}}:null}}}class nO{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(!f())return null;const e=eQ("__clerk_status"),t=eQ("__clerk_created_session");if(!e||!t)return null;const a="verified"===e&&void 0!==nq.clerk.client&&nq.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:a}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};resetPasswordPhoneCode={sendCode:this.sendResetPasswordPhoneCode.bind(this),verifyCode:this.verifyResetPasswordPhoneCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};phoneCode={sendCode:this.sendPhoneCode.bind(this),verifyCode:this.verifyPhoneCode.bind(this)};mfa={sendPhoneCode:this.sendMFAPhoneCode.bind(this),verifyPhoneCode:this.verifyMFAPhoneCode.bind(this),sendEmailCode:this.sendMFAEmailCode.bind(this),verifyEmailCode:this.verifyMFAEmailCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#ev=!1;#e_;constructor(e){this.#e_=e}get id(){return this.#e_.id}get identifier(){return this.#e_.identifier}get createdSessionId(){return this.#e_.createdSessionId}get userData(){return this.#e_.userData}get status(){return this.#e_.status||"needs_identifier"}get supportedFirstFactors(){return this.#e_.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#e_.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#e_.firstFactorVerification.status}get existingSession(){if("failed"===this.#e_.firstFactorVerification.status&&this.#e_.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#e_.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#e_.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#e_.firstFactorVerification}get secondFactorVerification(){return this.#e_.secondFactorVerification}get protectCheck(){return this.#e_.protectCheck}async submitProtectCheck(e){return nE(this.#e_,async()=>{await this.#e_.__internal_basePatch({action:"protect_check",body:{proof_token:e.proofToken}})})}get canBeDiscarded(){return this.#ev}async sendResetPasswordEmailCode(){if(!this.#e_.id)throw Error("Cannot reset password without a sign in.");return nE(this.#e_,async()=>{let e=this.#e_.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new q("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#e_.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async sendResetPasswordPhoneCode(e={}){let{phoneNumber:t}=e;if(!this.#e_.id&&!t)throw Error("signIn.resetPasswordPhoneCode.sendCode() cannot be called without a phoneNumber if an existing signIn does not exist.");return nE(this.#e_,async()=>{t&&await this._create({identifier:t});let e=this.#e_.supportedFirstFactors?.find(e=>"reset_password_phone_code"===e.strategy);if(!e)throw new q("Reset password phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:a}=e;await this.#e_.__internal_basePost({body:{phoneNumberId:a,strategy:"reset_password_phone_code"},action:"prepare_first_factor"})})}async verifyResetPasswordPhoneCode(e){let{code:t}=e;return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"reset_password_phone_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:a=!0}=e;return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{password:t,signOutOfOtherSessions:a},action:"reset_password"})})}shouldRequireCaptcha(e){return!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=nq.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&nq.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=nq.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return!!e.strategy&&t.some(t=>t===e.strategy)}async getCaptchaToken(e={}){if(!this.shouldRequireCaptcha(e)||nq.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new al(nq.clerk),a=await t.managedOrInvisible({action:"signin"});if(!a)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:i}=a;return{captchaToken:n,captchaWidgetType:i,captchaError:r}}async _create(e){let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(e),n={...e,captchaToken:t,captchaWidgetType:a,captchaError:r,locale:tV()||void 0};await this.#e_.__internal_basePost({path:this.#e_.pathRoot,body:n})}async create(e){return nE(this.#e_,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.#e_,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,a=this.#e_.identifier,r=tV();await this.#e_.__internal_basePost({path:this.#e_.pathRoot,body:{identifier:t||a,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:a}=e;if(!this.#e_.id&&a)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#e_.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return nE(this.#e_,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:a});if(!e)throw new q("Email code factor not found",{code:"factor_not_found"});await this.#e_.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:a,emailAddressId:r}=e;if(!this.#e_.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#e_.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return nE(this.#e_,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new q("Email link factor not found",{code:"factor_not_found"});let n=a;try{new URL(a)}catch{n=window.location.origin+a}await this.#e_.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return nE(this.#e_,async()=>{let{run:e,stop:t}=rC();await new Promise((a,r)=>{e(async()=>{try{let e=await this.#e_.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(t(),a(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:a,channel:r="sms"}=e;if(!this.#e_.id&&a)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#e_.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return nE(this.#e_,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:a});if(!e)throw new q("Phone code factor not found",{code:"factor_not_found"});await this.#e_.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,popup:n,oidcPrompt:i,enterpriseConnectionId:s,identifier:o}=e;return nE(this.#e_,async()=>{let e=a;try{new URL(a)}catch{e=window.location.origin+a}let l={redirectUrl:nq.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=nx(nq.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=t.redirectCallbackUrl,l.actionCompleteRedirectUrl=t.redirectUrl}let c=!!this.#e_.firstFactorVerification.externalVerificationRedirectURL,u="enterprise_sso"!==t&&c;(!this.#e_.id||u)&&await this._create({strategy:t,...l,identifier:o}),"enterprise_sso"===t&&await this.#e_.__internal_basePost({body:{...l,oidcPrompt:i,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:d,externalVerificationRedirectURL:h}=this.#e_.firstFactorVerification;"unverified"===d&&h&&(n?(await nj(nq.clerk,{popup:n,externalVerificationRedirectURL:h}),await this.#e_.reload()):nq.clerk.__internal_windowNavigate(h))})}async web3(e){let{strategy:t}=e,a=t.replace("web3_","").replace("_signature","");return nE(this.#e_,async()=>{let r,n,i;switch(a){case"metamask":r=await tY().getMetamaskIdentifier(),n=tY().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await tY().getCoinbaseWalletIdentifier(),n=tY().generateSignatureWithCoinbaseWallet;break;case"base":r=await tY().getBaseIdentifier(),n=tY().generateSignatureWithBase;break;case"okx_wallet":r=await tY().getOKXWalletIdentifier(),n=tY().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new q("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await tY().getSolanaIdentifier(e.walletName),n=t=>tY().generateSignatureWithSolana({...t,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${a}`)}await this._create({identifier:r});let s=this.#e_.supportedFirstFactors?.find(e=>e.strategy===t);if(!s)throw new q("Web3 first factor not found",{code:"factor_not_found"});await this.#e_.__internal_basePost({body:{web3WalletId:s.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new q("Web3 nonce not found",{code:"web3_nonce_not_found"});try{i=await n({identifier:r,nonce:o,walletName:e?.walletName,provider:a})}catch(e){if("coinbase_wallet"===a&&4001===e.code)i=await n({identifier:r,nonce:o,provider:a});else throw e}await this.#e_.__internal_basePost({body:{signature:i,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},a=nq.clerk.__internal_isWebAuthnSupported||na,r=nq.clerk.__internal_getPublicCredentials||rT,n=nq.clerk.__internal_isWebAuthnAutofillSupported||nr;if(!a())throw new K("Passkeys are not supported",{code:"passkey_not_supported"});return nE(this.#e_,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new q("Passkey factor not found",{code:"factor_not_found"});await this.#e_.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,a=e?rM(JSON.parse(e)):null;if(!a)throw new q("Missing public key options",{code:"missing_public_key_options"});let i=!1;"autofill"===t&&(i=await n());let{publicKeyCredential:s,error:o}=await r({publicKeyOptions:a,conditionalUI:i});if(!s)throw new K(o.message,{code:"passkey_retrieval_failed"});await this.#e_.__internal_basePost({body:{publicKeyCredential:JSON.stringify(rN(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return nE(this.#e_,async()=>{let e=this.#e_.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new q("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#e_.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async sendMFAEmailCode(){return nE(this.#e_,async()=>{let e=this.#e_.supportedSecondFactors?.find(e=>"email_code"===e.strategy);if(!e)throw new q("Email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#e_.__internal_basePost({body:{emailAddressId:t,strategy:"email_code"},action:"prepare_second_factor"})})}async verifyMFAEmailCode(e){let{code:t}=e;return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eQ("__clerk_ticket");return this.create({strategy:"ticket",ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.#e_.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return nE(this.#e_,async()=>{nq.clerk.client&&!nq.clerk.client.sessions.some(e=>e.id===this.#e_.createdSessionId)&&await nq.clerk.client.reload(),this.#ev=!0,await nq.clerk.setActive({session:this.#e_.createdSessionId,navigate:t})})}reset(){if(!nq.clerk.client)throw Error("Cannot reset sign-in without a client.");return this.#ev=!0,nq.clerk.client.resetSignIn(),Promise.resolve({error:null})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:a}){if(!this.#e_.supportedFirstFactors)return null;if(t){let a=this.#e_.supportedFirstFactors.find(a=>a.strategy===e&&a.emailAddressId===t);if(a)return a}if(a){let t=this.#e_.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===a);if(t)return t}let r=this.#e_.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#e_.identifier);if(r)return r;let n=this.#e_.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function nT(e){let{unsafeMetadata:t}={...e},a=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:a}:{}}}class nU extends au{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new rW(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};protectCheck=null;createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tj.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new nB(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{tj.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=tV();e&&(t.locale=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new al(nU.clerk),a=await e.managedOrInvisible({action:"signup"});if(!a)throw new q("",{code:"captcha_unavailable"});t={...t,...a}}return this._basePost({path:this.pathRoot,body:nT(t)})};prepareVerification=e=>(tj.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(tj.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));submitProtectCheck=e=>(tj.debug("SignUp.submitProtectCheck",{id:this.id}),this._basePatch({action:"protect_check",body:{proof_token:e.proofToken}}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:t}=rC();return{startEmailLinkFlow:async({redirectUrl:a})=>(this.id||t5("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};preparePhoneNumberVerification=e=>this.prepareVerification(e||{strategy:"phone_code"});attemptPhoneNumberVerification=e=>this.attemptVerification({...e,strategy:"phone_code"});prepareWeb3WalletVerification=e=>this.prepareVerification({strategy:"web3_metamask_signature",...e});attemptWeb3WalletVerification=async e=>{let{signature:t,strategy:a="web3_metamask_signature"}=e;return this.attemptVerification({signature:t,strategy:a})};authenticateWithWeb3=async e=>{let t,{generateSignature:a,identifier:r,unsafeMetadata:n,strategy:i="web3_metamask_signature",legalAccepted:s,walletName:o}=e||{},l=i.replace("web3_","").replace("_signature","");"function"!=typeof a&&t4("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:n,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:i});let{message:u}=this.verifications.web3Wallet;u||t8("SignUp");try{t=await a({identifier:r,nonce:u,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)t=await a({identifier:r,nonce:u,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:i})};authenticateWithMetamask=async e=>{let t=await tY().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await tY().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await tY().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await tY().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:t,legalAccepted:a})=>{let r=await tY().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:t=>tY().generateSignatureWithSolana({...t,walletName:e}),unsafeMetadata:t,strategy:"web3_solana_signature",legalAccepted:a,walletName:e})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:a,redirectUrlComplete:r,strategy:n,continueSignUp:i=!1,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u}=e,d=nU.clerk.buildUrlWithAuth(a),h=()=>{let e={strategy:n,redirectUrl:d,actionCompleteRedirectUrl:r,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u};return i&&this.id?this.update(e):this.create(e)},{verifications:m}=await h().catch(async e=>{if(M(e)&&H(e))return await nU.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:f,externalVerificationRedirectURL:g}=p;"unverified"===f&&g?t(g):t7(f,nU.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>{let t=nU.clerk.__internal_oauthTransport;return t?nC({clerk:nU.clerk,transport:t,resource:this,authenticateMethod:this.authenticateWithRedirectOrPopup,params:e,callbackParams:e.__internal_callbackParams??{}}):this.authenticateWithRedirectOrPopup(e,nU.clerk.__internal_windowNavigate)};authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||t4("popup"),n_(nU.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:nT(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(nU.clerk.__internal_environment?.userSettings.passwordSettings)return nk(nP(),{...nU.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 rW(e.verifications),this.protectCheck=e.protect_check?{status:e.protect_check.status,token:e.protect_check.token,sdkUrl:e.protect_check.sdk_url,expiresAt:e.protect_check.expires_at,uiHints:e.protect_check.ui_hints}:null,this.username=e.username,this.firstName=e.first_name,this.lastName=e.last_name,this.emailAddress=e.email_address,this.phoneNumber=e.phone_number,this.hasPassword=e.has_password,this.unsafeMetadata=e.unsafe_metadata,this.createdSessionId=e.created_session_id,this.createdUserId=e.created_user_id,this.abandonAt=e.abandon_at,this.web3wallet=e.web3_wallet,this.legalAcceptedAt=e.legal_accepted_at,this.locale=e.locale),rs.emit("resource:update",{resource:this}),this}__internal_updateFromJSON(e){return this.fromJSON(e)}__internal_toSnapshot(){return{object:"sign_up",id:this.id||"",status:this.status||null,required_fields:this.requiredFields,optional_fields:this.optionalFields,missing_fields:this.missingFields,unverified_fields:this.unverifiedFields,verifications:this.verifications.__internal_toSnapshot(),protect_check:this.protectCheck?{status:this.protectCheck.status,token:this.protectCheck.token,sdk_url:this.protectCheck.sdkUrl,...void 0!==this.protectCheck.expiresAt&&{expires_at:this.protectCheck.expiresAt},...void 0!==this.protectCheck.uiHints&&{ui_hints:this.protectCheck.uiHints}}:null,username:this.username,first_name:this.firstName,last_name:this.lastName,email_address:this.emailAddress,phone_number:this.phoneNumber,has_password:this.hasPassword,unsafe_metadata:this.unsafeMetadata,created_session_id:this.createdSessionId,created_user_id:this.createdUserId,abandon_at:this.abandonAt,web3_wallet:this.web3wallet,legal_accepted_at:this.legalAcceptedAt,locale:this.locale,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return nU.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){let t=nU.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=nU.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||nR(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}__experimental_getEnterpriseConnections=()=>au._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new nD(e)))}let nM=new Set(["email_link","email_code","phone_code"]);function nR(e){return!!e&&(nM.has(e)||e.startsWith("web3_"))}class nN{#e_;sendEmailCode;verifyEmailCode;sendEmailLink;waitForEmailLinkVerification;sendPhoneCode;verifyPhoneCode;constructor(e,t){this.#e_=e,this.sendEmailCode=t.sendEmailCode,this.verifyEmailCode=t.verifyEmailCode,this.sendEmailLink=t.sendEmailLink,this.waitForEmailLinkVerification=t.waitForEmailLinkVerification,this.sendPhoneCode=t.sendPhoneCode,this.verifyPhoneCode=t.verifyPhoneCode}get emailAddress(){return this.#e_.verifications.emailAddress}get phoneNumber(){return this.#e_.verifications.phoneNumber}get web3Wallet(){return this.#e_.verifications.web3Wallet}get externalAccount(){return this.#e_.verifications.externalAccount}get emailLinkVerification(){if(!f())return null;let e=eQ("__clerk_status"),t=eQ("__clerk_created_session");if(!e||!t)return null;let a="verified"===e&&void 0!==nU.clerk.client&&nU.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:a}}}class nB{verifications;#ev=!1;#e_;constructor(e){this.#e_=e,this.verifications=new nN(this.#e_,{sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendEmailLink:this.sendEmailLink.bind(this),waitForEmailLinkVerification:this.waitForEmailLinkVerification.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)})}get id(){return this.#e_.id}get requiredFields(){return this.#e_.requiredFields}get optionalFields(){return this.#e_.optionalFields}get missingFields(){return this.#e_.missingFields}get status(){return this.#e_.status||"missing_requirements"}get username(){return this.#e_.username}get firstName(){return this.#e_.firstName}get lastName(){return this.#e_.lastName}get emailAddress(){return this.#e_.emailAddress}get phoneNumber(){return this.#e_.phoneNumber}get web3Wallet(){return this.#e_.web3wallet}get hasPassword(){return this.#e_.hasPassword}get unsafeMetadata(){return this.#e_.unsafeMetadata}get createdSessionId(){return this.#e_.createdSessionId}get createdUserId(){return this.#e_.createdUserId}get abandonAt(){return this.#e_.abandonAt}get legalAcceptedAt(){return this.#e_.legalAcceptedAt}get locale(){return this.#e_.locale}get unverifiedFields(){return this.#e_.unverifiedFields}get protectCheck(){return this.#e_.protectCheck}get isTransferable(){return"transferable"===this.#e_.verifications.externalAccount.status&&this.#e_.verifications.externalAccount.error?.code===ec}get existingSession(){if(("failed"===this.#e_.verifications.externalAccount.status||"unverified"===this.#e_.verifications.externalAccount.status)&&this.#e_.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#e_.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#e_.verifications.externalAccount.error?.meta?.sessionId}}get canBeDiscarded(){return this.#ev}shouldBypassCaptchaForAttempt(e){let t=nU.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=nU.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||nR(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}async getCaptchaToken(e={}){if(nU.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new al(nU.clerk),a=await t.managedOrInvisible({action:"signup"});if(!a)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:i}=a;return{captchaToken:n,captchaWidgetType:i,captchaError:r}}async _create(e){let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(e),n={transfer:e.transfer,captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?nT(e.unsafeMetadata):void 0,locale:e.locale??tV()};await this.#e_.__internal_basePost({path:this.#e_.pathRoot,body:n})}async create(e){return nE(this.#e_,async()=>{await this._create(e)})}async update(e){return nE(this.#e_,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?nT(e.unsafeMetadata):void 0};await this.#e_.__internal_basePatch({body:t})})}async password(e){return nE(this.#e_,async()=>{let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?nT(e.unsafeMetadata):void 0};this.#e_.id?await this.#e_.__internal_basePatch({body:n}):(n.locale=e.locale??tV(),await this.#e_.__internal_basePost({path:this.#e_.pathRoot,body:n}))})}async sendEmailCode(){return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{channel:t="sms"}=e||{};return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return nE(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sendEmailLink(e){let{verificationUrl:t}=e;return nE(this.#e_,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}await this.#e_.__internal_basePost({body:{strategy:"email_link",redirectUrl:e},action:"prepare_verification"})})}async waitForEmailLinkVerification(){return nE(this.#e_,async()=>{let{run:e,stop:t}=rC();await new Promise((a,r)=>{e(()=>this.#e_.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,popup:c,locale:u}=e;return nE(this.#e_,async()=>{let{captchaToken:e,captchaWidgetType:d,captchaError:h}=await this.getCaptchaToken({strategy:t}),m=a;try{new URL(a)}catch{m=window.location.origin+a}let p={redirectUrl:nU.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:m};if(c){let e=nx(nU.clerk,{redirectCallbackUrl:p.redirectUrl,redirectUrl:m});p.redirectUrl=e.redirectCallbackUrl,p.actionCompleteRedirectUrl=e.redirectUrl}let f=()=>{let a={strategy:t,...p,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:h,locale:u};return this.#e_.id?this.#e_.__internal_basePatch({body:a}):(a.locale=u??tV(),this.#e_.__internal_basePost({path:this.#e_.pathRoot,body:a}))};await f().catch(async e=>{if(M(e)&&H(e))return await nU.clerk.__internal_environment.reload(),f();throw e});let{status:g,externalVerificationRedirectURL:b}=this.#e_.verifications.externalAccount;"unverified"===g&&b&&(c?(await nj(nU.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.#e_.reload()):nU.clerk.__internal_windowNavigate(b))})}async web3(e){let{strategy:t,unsafeMetadata:a,legalAccepted:r,firstName:n,lastName:i,locale:s}=e,o=t.replace("web3_","").replace("_signature","");return nE(this.#e_,async()=>{let e,l,c;switch(o){case"metamask":e=await tY().getMetamaskIdentifier(),l=tY().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tY().getCoinbaseWalletIdentifier(),l=tY().generateSignatureWithCoinbaseWallet;break;case"base":e=await tY().getBaseIdentifier(),l=tY().generateSignatureWithBase;break;case"okx_wallet":e=await tY().getOKXWalletIdentifier(),l=tY().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${o}`)}let u=e||this.#e_.web3wallet;await this._create({web3Wallet:u,unsafeMetadata:a,legalAccepted:r,firstName:n,lastName:i,locale:s}),await this.#e_.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:d}=this.#e_.verifications.web3Wallet;d||t8("SignUp");try{c=await l({identifier:e,nonce:d})}catch(t){if("coinbase_wallet"===o&&4001===t.code)c=await l({identifier:e,nonce:d});else throw t}await this.#e_.__internal_basePost({body:{signature:c,strategy:t},action:"attempt_verification"})})}async submitProtectCheck(e){return nE(this.#e_,async()=>{await this.#e_.__internal_basePatch({action:"protect_check",body:{proof_token:e.proofToken}})})}async ticket(e){let t=e?.ticket??eQ("__clerk_ticket");return this.create({...e,strategy:"ticket",ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return nE(this.#e_,async()=>{if(!this.#e_.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#ev=!0,await nU.clerk.setActive({session:this.#e_.createdSessionId,navigate:t})})}reset(){if(!nU.clerk.client)throw Error("Cannot reset sign-up without a client.");return this.#ev=!0,nU.clerk.client.resetSignUp(),Promise.resolve({error:null})}}class nD extends au{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class nF extends au{pathRoot="tokens";jwt;static async create(e,t={},a={}){return new nF(await au._fetch({method:"POST",path:e,body:t,search:a}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=tH(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=tH(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class nL extends au{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=tq(e.updated_at),this.createdAt=tq(e.created_at)),this}}var nW=Object.prototype.hasOwnProperty;function nK(e,t,a){for(a of e.keys())if(nH(a,t))return a}function nH(e,t){var a,r,n;if(e===t)return!0;if(e&&t&&(a=e.constructor)===t.constructor){if(a===Date)return e.getTime()===t.getTime();if(a===RegExp)return e.toString()===t.toString();if(a===Array){if((r=e.length)===t.length)for(;r--&&nH(e[r],t[r]););return -1===r}if(a===Set){if(e.size!==t.size)return!1;for(r of e)if((n=r)&&"object"==typeof n&&!(n=nK(t,n))||!t.has(n))return!1;return!0}if(a===Map){if(e.size!==t.size)return!1;for(r of e)if((n=r[0])&&"object"==typeof n&&!(n=nK(t,n))||!nH(r[1],t.get(n)))return!1;return!0}if(a===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(a===DataView){if((r=e.byteLength)===t.byteLength)for(;r--&&e.getInt8(r)===t.getInt8(r););return -1===r}if(ArrayBuffer.isView(e)){if((r=e.byteLength)===t.byteLength)for(;r--&&e[r]===t[r];);return -1===r}if(!a||"object"==typeof e){for(a in r=0,e)if(nW.call(e,a)&&++r&&!nW.call(t,a)||!(a in t)||!nH(e[a],t[a]))return!1;return Object.keys(t).length===r}}return e!=e&&t!=t}function nV(e){if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}class nG extends au{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=tq(e.updated_at),this.createdAt=tq(e.created_at)),this}}class nJ extends au{advisory=null;form={name:"",slug:"",logo:null,blurHash:null};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.advisory&&(this.advisory=this.withDefault(e.advisory,this.advisory??null)),e.form&&(this.form.name=this.withDefault(e.form.name,this.form.name),this.form.slug=this.withDefault(e.form.slug,this.form.slug),this.form.logo=this.withDefault(e.form.logo,this.form.logo),this.form.blurHash=this.withDefault(e.form.blur_hash,this.form.blurHash))),this}static async retrieve(){return await au._fetch({path:"/me/organization_creation_defaults",method:"GET"}).then(e=>new nJ(e?.response))}__internal_toSnapshot(){return{advisory:this.advisory?{code:this.advisory.code,meta:this.advisory.meta,severity:this.advisory.severity}:null,form:{name:this.form.name,slug:this.form.slug,logo:this.form.logo,blur_hash:this.form.blurHash}}}}class nZ extends au{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 nZ}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case rE:return this.primaryEmailAddressId===e.id;case ns:return this.primaryPhoneNumberId===e.id;case n1:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new rE({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>ni.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new ns({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new n1({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:a,additionalScopes:r,enterpriseConnectionId:n}=e||{};return new rQ((await au._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:a,additional_scope:r,enterprise_connection_id:n}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new nL((await au._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new nL((await au._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new rI((await au._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new nG((await au._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=async e=>{var t;let{unsafeMetadata:a,...r}=e,n=void 0!==a,i=Object.keys(r).length>0;if(!n)return this._basePatch({body:nT(e)});((t=au.clerk.publishableKey).startsWith("test_")||t.startsWith("pk_test_"))&&console.warn('Clerk - DEPRECATION WARNING: "user.update({ unsafeMetadata })" is deprecated and will be removed in the next major release.\nUse user.updateMetadata({ unsafeMetadata }) for partial updates (deep merge) instead.'),i?await this._basePatch({body:nT(r)}):await this.reload();let s=function e(t,a){if(null===a)return null;if(!nV(t)||!nV(a))return a;let r={};for(let n of Object.keys(a)){let i=t[n],s=a[n];if(!(n in t)){r[n]=s;continue}if(nV(i)&&nV(s)){let t=e(i,s);if(nV(t)&&0===Object.keys(t).length)continue;r[n]=t}else nH(i,s)||(r[n]=s)}for(let e of Object.keys(t))e in a||(r[e]=null);return r}(this.unsafeMetadata,a);return null!==s&&"object"==typeof s&&0===Object.keys(s).length?this:this.updateMetadata({unsafeMetadata:s})};updateMetadata=e=>this._basePatch({path:`${this.path()}/metadata`,body:nT(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=>(rs.emit(rr,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await nw.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?r0.delete(`${this.path()}/profile_image`):r0.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>nY.retrieve(e);getOrganizationSuggestions=e=>nt.retrieve(e);getOrganizationMemberships=e=>ne.retrieve(e);getOrganizationCreationDefaults=()=>nJ.retrieve();leaveOrganization=async e=>new rI((await au._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);getEnterpriseConnections=async e=>{let{withOrganizationAccountLinking:t}=e||{};return((await au._fetch({path:"/me/enterprise_connections",method:"GET",...void 0!==t?{search:{with_organization_account_linking:String(t)}}:{}}))?.response||[]).map(e=>new rG(e))};initializePaymentMethod=e=>a2(e);addPaymentMethod=e=>a9(e);getPaymentMethods=e=>a3(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:a})=>a||[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 rE(e,this.path()+"/email_addresses")),this.primaryEmailAddressId=e.primary_email_address_id||null,this.primaryEmailAddress=this.emailAddresses.find(({id:e})=>e===this.primaryEmailAddressId)||null,this.phoneNumbers=(e.phone_numbers||[]).map(e=>new ns(e,this.path()+"/phone_numbers")),this.primaryPhoneNumberId=e.primary_phone_number_id||null,this.primaryPhoneNumber=this.phoneNumbers.find(({id:e})=>e===this.primaryPhoneNumberId)||null,this.web3Wallets=(e.web3_wallets||[]).map(e=>new n1(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 rQ(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new ni(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new ne(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new rH(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=tq(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tq(e.legal_accepted_at)),this.updatedAt=tq(e.updated_at||void 0),this.createdAt=tq(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 n${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 nY extends au{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await au._fetch({path:"/me/organization_invitations",method:"GET",search:aT(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new nY(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=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}}let nQ={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 nX extends au{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:{...nQ,name:"phone_number"},username:{...nQ,name:"username"},web3_wallet:{...nQ,name:"web3_wallet"},first_name:{...nQ,name:"first_name"},last_name:{...nQ,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:{...nQ,name:"authenticator_app"},backup_code:{...nQ,name:"backup_code"},passkey:{...nQ,name:"passkey"}};enterpriseSSO={enabled:!1,self_serve_sso:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0,mfa:{required:!1}};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!this.attributes?.password?.enabled}get hasValidAuthFactor(){return!!(this.attributes?.email_address?.enabled||this.attributes?.phone_number?.enabled||this.attributes.password?.required&&this.attributes.username?.required)}fromJSON(e){return e&&(this.attributes=this.withDefault(e.attributes?Object.fromEntries(Object.entries(e.attributes).map(e=>[e[0],{...e[1],name:e[0]}])):null,this.attributes),this.actions=this.withDefault(e.actions,this.actions),this.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 n1 extends au{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 rF(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class n0 extends au{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tq(e.updated_at),this.createdAt=tq(e.created_at),rs.emit("resource:update",{resource:this})),this}async join(e){return nE(this,async()=>{await n0.join(e)})}static async join(e){return new n0(await au._fetch({path:"/waitlist",method:"POST",body:e}))}}function n2(e,t){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(a=t,r=e,a.organizationMemberships.length!==r.organizationMemberships.length||a.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function n9(e,t){return!function(e,t){if(!e&&t||e&&!t)return!0;if(!e&&e===t)return!1;if(!e||!t)return!0;try{if(rz.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(ny.isSessionResource(e)){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==t.lastActiveToken?.jwt?.claims?.__raw||function(e,t){if(e.lastActiveOrganizationId!==t.lastActiveOrganizationId)return!0;let a=e.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId),r=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return a?.permissions?.length!==r?.permissions?.length}(e,t)||(a=e,r=t,!!a.user!=!!r.user||!!a.user&&!!r.user&&n2(a.user,r.user))}if(nZ.isUserResource(e))return n2(e,t)}catch{}return!0}(e,t)?e:t}let n3="__clerk_db_jwt";function n5(e,t){let a=new URL(e),r=a.searchParams.get(n3);a.searchParams.delete(n3);let n=r||t;return n&&a.searchParams.set(n3,n),a}let n6=e=>{let t=new URL(e);return t.searchParams.delete(n3),t},n8=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 n4(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)"__proto__"!==r&&(e[r]=a[r])}return e}var n7=function e(t,a){function r(e,r,n){if("u">typeof document){"number"==typeof(n=n4({},a,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var s in n)n[s]&&(i+="; "+s,!0!==n[s]&&(i+="="+n[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var a=document.cookie?document.cookie.split("; "):[],r={},n=0;n<a.length;n++){var i=a[n].split("="),s=i.slice(1).join("=");try{var o=decodeURIComponent(i[0]);if(o in r||(r[o]=t.read(s,o)),e===o)break}catch{}}return e?r[e]:r}},remove:function(e,t){r(e,"",n4({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,n4({},this.attributes,t))},withConverter:function(t){return e(n4({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(a)},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 ie(e){return{get:()=>n7.get(e),set(t,a={}){n7.set(e,t,a)},remove(t){n7.remove(e,t)}}}let it=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function ia(e,t){let a=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return a.setFullYear(a.getFullYear()+t),a}let ir=ie("__clerk_test_etld"),ii=[".lovable.app",".lovableproject.com",".webcontainer-api.io",".vusercontent.net",".v0.dev",".v0.app",".lp.dev",".replit.dev"];function is(){try{return ii.some(e=>window.location.hostname.endsWith(e))}catch{return!1}}let io="__client_uat",il="__session",ic=e=>{let t=e.usePartitionedCookies(),a=t||tJ()||is()?"None":"Lax",r=it(a);return{sameSite:a,secure:r,partitioned:t&&r}};async function iu(e){let t;try{t=await eA(e)}catch(o){var a;a=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,eO.has(a)||(console.log(a),eO.add(a));let{default:r}=await Promise.resolve().then(n.t.bind(n,3515,23)),{default:i}=await Promise.resolve().then(n.t.bind(n,5662,23)),s=r(e);t=i.stringify(s).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let id=e=>{let t=e.usePartitionedCookies(),a=t||tJ()||is()?"None":"Lax",r=it(a);return{sameSite:a,secure:r,partitioned:t&&r}},ih={sameSite:"None",secure:!0,partitioned:!0};class im{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,a,r){let n=await iu(e.publishableKey),i=new im(e,t,n,a,r);return await i.setup(),i}constructor(e,t,r,n,i){this.clerk=e,this.instanceType=n,this.clerkEventBus=i,rs.on(ra,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),rs.on(rr,()=>this.handleSignOut()),rs.on(rn,()=>{this.devBrowser.refreshCookies()}),this.refreshTokenOnFocus(),this.startPollingForToken();const s={usePartitionedCookies:()=>rY.getInstance().partitionedCookies};this.clientUat=((e,t)=>{let r=ie(io),n=ie(eC(io,e));return{set:e=>{let i=ia(Date.now(),1),s=t.usePartitionedCookies(),o=s||tJ()||is()?"None":"Strict",l=it(o),c=s&&l,u=function(e=window.location.hostname,t=ir,r){if(a)return a;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 i=n.slice(e).join(".");if(t.set("1",{...r,domain:i}),"1"===t.get())return t.remove({...r,domain:i}),a=i,i;t.remove({...r,domain:i})}return a=e,e}(void 0,void 0,{sameSite:o,secure:l}),d="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(d=Math.floor(e.updatedAt.getTime()/1e3).toString()),n.remove(),r.remove(),n.set(d,{domain:u,expires:i,partitioned:c,sameSite:o,secure:l}),r.set(d,{domain:u,expires:i,partitioned:c,sameSite:o,secure:l})},get:()=>parseInt(n.get()||r.get()||"0",10)}})(r,s),this.sessionCookie=((e,t)=>{let a=ie(il),r=ie(eC(il,e));return{set:e=>{let n=ia(Date.now(),1),{sameSite:i,secure:s,partitioned:o}=ic(t);o&&(a.remove(),r.remove()),a.set(e,{expires:n,sameSite:i,secure:s,partitioned:o}),r.set(e,{expires:n,sameSite:i,secure:s,partitioned:o})},remove:()=>{let e=ic(t);a.remove(e),r.remove(e),e.partitioned&&(a.remove(),r.remove())},get:()=>r.get()||a.get()}})(r,s),this.activeCookie=(()=>{let e=ie("clerk_active_context"),t={secure:it("None")};return{set:a=>{e.set(a,t)},get:()=>e.get(),remove:()=>e.remove(t)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:a,cookieOptions:r}){let n,i,s,o,l=(i=ie(n3),s=ie(eC(n3,e)),o=()=>{let e=id(r);for(let t of[s,i])t.remove(e),t.remove(),t.remove(ih)},{get:()=>s.get()||i.get(),set:e=>{let t=ia(Date.now(),1),{sameSite:a,secure:n,partitioned:l}=id(r);o(),s.set(e,{expires:t,sameSite:a,secure:n,partitioned:l}),i.set(e,{expires:t,sameSite:a,secure:n,partitioned:l})},remove:()=>o()});function c(){return n||l.get()}function u(e){n=e,l.set(e)}function d(){n=void 0,l.remove()}return{clear:function(){d()},setup:async function e(){var e;let r,i;if(!eB(t))return;a.onBeforeRequest(e=>{let t=c();t&&e?.url&&(e.url=n5(e.url,t))}),a.onAfterResponse((e,t)=>{let a=t?.headers?.get("Clerk-Db-Jwt");a&&u(a)});let s=(r=(e=new URL(window.location.href)).searchParams.get("__clerk_db_jwt")||"",(i=n6(n8(e))).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",i),r);if(s)return void u(s);let o=l.get();if(o){n=o;return}let d=a.buildUrl({path:"/dev_browser"}),h=await fetch(d.toString(),{method:"POST"});if(!h.ok){let e=function(e=[]){return e.length>0?e.map(e=>new T(e)):[]}((await h.json()).errors);e[0]?t9(e[0].longMessage):t9()}let m=await h.json();u(m?.id)},getDevBrowser:c,setDevBrowser:u,removeDevBrowser:d,refreshCookies:function(){let e=c();e&&u(e)}}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:r,cookieOptions:s})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let t=this.devBrowser.getDevBrowser();if(!t)throw Error(`${t2} Missing dev browser. Please contact support.`);return n5(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new rp,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){let e=()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})};window.addEventListener("focus",e),"u">typeof document&&document.addEventListener("visibilitychange",e)}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if((document.hasFocus()||this.inVisibleCrossOriginIframe()||this.isCurrentContextActive())&&!(e&&this.#ex(e)))return e||v()||tj.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}#ex(e){let t=this.#ej(e);if(!t||null==ry(t))return!1;let a=this.#ej(this.sessionCookie.get());if(!a||null==ry(a))return!1;let r=a.jwt?.claims?.exp;return!("number"!=typeof r||r<=Math.floor(Date.now()/1e3))&&rw(a)===rw(t)&&(rk(a)||"")===(rk(t)||"")&&rb(a,t)===a}#ej(e){if(!e)return null;try{let t=new nF({id:"__session",jwt:e,object:"token"});return t.jwt?t:null}catch{return null}}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(M(e)||O(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(J(e))return void this.clerk.handleUnauthenticated().catch(tb.lQ);this.clerkEventBus.emit(S,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",t=this.clerk.organization?.id||"",a=`${e}:${t}`;":"!==a?this.activeCookie.set(a):this.activeCookie.remove()}inVisibleCrossOriginIframe(){return tJ()&&"visible"===document.visibilityState}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[t,a]=e.split(":"),r=this.clerk.session?.id||"",n=this.clerk.organization?.id||"";return t===r&&a===n}getSessionCookie(){return this.sessionCookie.get()}}class ip{clerk;captchaChallenge;timers;constructor(e,t=new al(e),a=rd()){this.clerk=e,this.captchaChallenge=t,this.timers=a}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 ig=["/client","/waitlist"];function ib(e){let t;try{t=new nF({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(rz.clearInstance(),!t?.jwt)return rz.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:a,userId:r,orgId:n,orgRole:i,orgPermissions:s,orgSlug:o,factorVerificationAge:l}=(e=>{let t,a,r,n,i=e.fva??null,s=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,r=e.o?.slg,e.o?.rol&&(a=`org:${e.o?.rol}`);let{org:i}=ng(e.fea),{permissions:s,featurePermissionMap:o}=(({per:e,fpm:t})=>{if(!e||!t)return{permissions:[],featurePermissionMap:[]};let a=e.split(",").map(e=>e.trim());return{permissions:a,featurePermissionMap:t.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(a.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});n=function({features:e,permissions:t,featurePermissionMap:a}){if(!e||!t||!a)return[];let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(n>=a.length)continue;let s=a[n];if(s)for(let e=0;e<s.length;e++)1===s[e]&&r.push(`org:${i}:${t[e]}`)}return r}({features:i,featurePermissionMap:o,permissions:s})}}else t=e.org_id,a=e.org_role,r=e.org_slug,n=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:s,actor:e.act,userId:e.sub,orgId:t,orgRole:a,orgSlug:r,orgPermissions:n,factorVerificationAge:i}})(t.jwt.claims),c={object:"client",last_active_session_id:a,id:"client_init",sessions:[{object:"session",id:a,status:"active",last_active_organization_id:n||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:r},user:{object:"user",id:r,updated_at:1,organization_memberships:n&&o&&i?[{object:"organization_membership",id:n,role:i,permissions:s||[],organization:{object:"organization",id:n,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return rz.getOrCreateInstance(c)}class iy{static #eh="/api_keys";async #ez(){let e=await au.clerk.session?.getToken();if(!e)throw new q("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 au._fetch({...await this.#ez(),method:"GET",path:iy.#eh,search:aT({...e,subject:e?.subject??au.clerk.organization?.id??au.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new ad(e))}})}async create(e){return new ad(await au._fetch({...await this.#ez(),path:iy.#eh,method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??au.clerk.organization?.id??au.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new ad(await au._fetch({...await this.#ez(),method:"POST",path:`${iy.#eh}/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let iw=new Map;class ik{async getConsentInfo(e){let{oauthClientId:t,scope:a,redirectUri:r}=e,n={...void 0!==a&&{scope:a},...void 0!==r&&{redirect_uri:r}},i=await au._fetch({method:"GET",path:`/me/oauth/consent/${encodeURIComponent(t)}`,search:Object.keys(n).length>0?n:void 0},{skipUpdateClient:!0});if(!i)throw new q("Network request failed while offline",{code:"network_error"});let s=i.response??i;return{oauthApplicationName:s.oauth_application_name,oauthApplicationLogoUrl:s.oauth_application_logo_url,oauthApplicationUrl:s.oauth_application_url,clientId:s.client_id,state:s.state,redirectDomain:s.redirect_domain,scopes:s.scopes?.map(e=>({scope:e.scope,description:e.description,requiresConsent:e.requires_consent}))??[]}}buildConsentActionUrl({clientId:e}){let t=au.fapiClient.buildUrl({path:`/me/oauth/consent/${encodeURIComponent(e)}`,sessionId:au.clerk.session?.id});return au.clerk.buildUrlWithAuth(t.toString())}}class iv{#el=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#el){if(f())for(let e of(this.#el=!0,t.loaders))try{this.applyLoader(e)}catch(e){eT(`[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 eT(`[protect] loader rollout value is invalid: ${t}`);if(0===t||Math.random()>t)return}let t=e.type||"script",a=e.target||"body",r=document.createElement(t);if(e.attributes)for(let[t,a]of Object.entries(e.attributes))switch(typeof a){case"string":case"number":case"boolean":r.setAttribute(t,String(a));break;default:eT(`[protect] loader attribute is invalid type: ${t}=${a}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),a){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(a?.startsWith("#")){let e=document.getElementById(a.substring(1));if(!e)return void eT(`[protect] loader target element not found: ${a}`);e.appendChild(r);return}eT(`[protect] loader target is invalid: ${a}`)}}}class i_{signInResourceSignal=aM;signInErrorSignal=aR;signInFetchSignal=aN;signInSignal=aB;signUpResourceSignal=aD;signUpErrorSignal=aF;signUpFetchSignal=aL;signUpSignal=aW;waitlistResourceSignal=aK;waitlistErrorSignal=aH;waitlistFetchSignal=aV;waitlistSignal=aG;_waitlistInstance;__internal_effect=aI;__internal_computed=aS;constructor(){rs.on("resource:update",this.onResourceUpdated),rs.on("resource:error",this.onResourceError),rs.on("resource:fetch",this.onResourceFetch),this._waitlistInstance=new n0(null),this.waitlistResourceSignal({resource:this._waitlistInstance})}get __internal_waitlist(){return this._waitlistInstance}onResourceError=e=>{e.resource instanceof nq&&this.signInErrorSignal({error:e.error}),e.resource instanceof nU&&this.signUpErrorSignal({error:e.error}),e.resource instanceof n0&&this.waitlistErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof nq){if(ix(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof nU){if(ix(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}e.resource instanceof n0&&(this._waitlistInstance=e.resource,this.waitlistResourceSignal({resource:e.resource}))};onResourceFetch=e=>{e.resource instanceof nq&&this.signInFetchSignal({status:e.status}),e.resource instanceof nU&&this.signUpFetchSignal({status:e.status}),e.resource instanceof n0&&this.waitlistFetchSignal({status:e.status})}}function ix(e,t){return!t?.id&&e&&e.__internal_future?.canBeDiscarded===!1}let ij="cannot_render_billing_disabled",iz="cannot_render_user_missing",iS="cannot_render_organizations_disabled",iI="cannot_render_organization_missing",iA="cannot_render_single_session_enabled",iC={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 iE{static version="6.25.9-canary.v20260724235708";static sdkMetadata={name:"@clerk/clerk-js",version:"6.25.9-canary.v20260724235708"};static _billing;static _apiKeys;static _oauthApplication;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new i_;internal_last_error=null;environment;#eS;#eI="";#eA;#eC;#eE;#eP;#eq;#eO=null;#eT;#eU;#eM;#eR="loading";#eN=[];#eB=[];#eD={};#eF=null;#eL=null;#eW=0;#eK=z();#eH=new tE;get __internal_moduleManager(){return this.#eH}get __internal_queryClient(){return this.#eS||Promise.resolve().then(n.bind(n,6125)).then(e=>e.QueryClient).then(e=>{this.#eS||(this.#eS=new e,this.#eK.emit("queryClientStatus","ready"))}),this.#eS?{__tag:"clerk-rq-client",client:this.#eS}:void 0}get __internal_hasOAuthTransport(){return null!==this.#eF}get __internal_oauthTransport(){return this.#eF}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eI}get version(){return iE.version}get uiVersion(){let e="u">typeof window?window.__internal_ClerkUICtor:void 0,t=this.#eD.ui?.ClerkUI;return e?.version??(t instanceof Promise?void 0:t?.version)}set sdkMetadata(e){iE.sdkMetadata=e}get sdkMetadata(){return iE.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eR}get isSatellite(){return!!tG()&&(0,tb.VK)(this.#eD.isSatellite,new URL(window.location.href),!1)}get domain(){if(tG()){let e=eP((0,tb.VK)(this.#eA,new URL(window.location.href)));if("production"===this.#eM){let t;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))t=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;t=/^(clerk\.)*/gi}return`clerk.${e.replace(t,"")}`}return e}return"function"==typeof this.#eA?(eT(e6.domainAsFunctionNotSupported),""):eP(this.#eA||"")}get proxyUrl(){if(tG()){var e;let t=(0,tb.VK)(this.#eC,new URL(window.location.href));!t||te(t)||tt(t)||tW.throwInvalidProxyUrl({url:t});let a=t?!tt(t)||"u"<typeof window||!window.location?.origin?t:new URL(t,window.location.origin).toString():"";if(a)return a;if(!this.#eA&&"production"===this.#eM&&(e=window.location.hostname,ta.some(t=>e?.endsWith(t))))return`${window.location.origin}/__clerk`}return"function"==typeof this.#eC?(eT(e6.proxyUrlAsFunctionNotSupported),""):this.#eC||""}get frontendApi(){let e=eS(this.publishableKey);return e?e.frontendApi:tW.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#eM}get isStandardBrowser(){return this.#eD.standardBrowser||!1}get billing(){return iE._billing||(iE._billing=new aU),iE._billing}get apiKeys(){return iE._apiKeys||(iE._apiKeys=new iy),iE._apiKeys}get oauthApplication(){return iE._oauthApplication||(iE._oauthApplication=new ik),iE._oauthApplication}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let a,r,n,i,{for:s,planId:o,planPeriod:l,seatsQuantity:c,priceId:u}=t;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===s&&null===e.organization)throw Error("Clerk: The current session does not have an active organization. Use `setActive` to set the organization");let d=function(e){let{userId:t,orgId:a,planId:r,planPeriod:n,seatsQuantity:i,priceId:s}=e;return`${t}-${a||"user"}-${r}-${n}-${i}-${s}`}({userId:e.user?.id||"",orgId:"organization"===s?e.organization?.id:void 0,planId:o,planPeriod:l,seatsQuantity:c,priceId:u}),h=iw.get(d);if(h)return h.signals.computedSignal();let m=(a=az({resource:null}),r=az({error:null}),n=az({status:"idle"}),i=aS(()=>{let e=a().resource,t=r().error,i=n().status;return{errors:aJ(t,{}),fetchStatus:i,checkout:e}}),{resourceSignal:a,errorSignal:r,fetchSignal:n,computedSignal:i}),p=new aY(m,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l,seatsQuantity:c,priceId:u});return iw.set(d,{resource:p,signals:m}),m.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eD[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return tW.throwMissingPublishableKeyError();const a=eS(e);if(!a)return tW.throwInvalidPublishableKeyError({key:e});this.#eA=t?.domain,this.#eC=t?.proxyUrl,this.environment=rY.getInstance(),this.#eM=a.instanceType,this.#eI=e,this.#eU=function(e){let t=[],a=[];async function r(e){for await(let a of["u">typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await a(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["u">typeof window&&window.__internal_onAfterResponse,...a].filter(e=>e))if(await r(e,t)===!1)return!1;return!0}function i({method:t,path:a,sessionId:r,search:n,rotatingTokenNonce:s}){let o=new URLSearchParams(n);return o.append("__clerk_api_version","2026-05-12"),o.append("_clerk_js_version","6.25.9-canary.v20260724235708"),s&&o.append("rotating_token_nonce",s),e.domain&&"development"===e.instanceType&&e.isSatellite&&o.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&o.append("_method",t),a&&!ig.some(e=>a.startsWith(e))&&r&&o.append("_clerk_session_id",r),eM([...o.entries()].reduce((e,[t,a])=>(e[t]=a.includes(",")?a.split(","):a,e),{}))}function s(t){let{path:a,pathPrefix:r="v1"}=t;if(e.proxyUrl){let n=new URL(e.proxyUrl),s=n.pathname.slice(1);return s.endsWith("/")&&(s=s.slice(0,-1)),eL({base:n.origin,pathname:`${s}/${r}${a}`,search:i(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return eL({base:`https://${n||e.frontendApi}`,pathname:`${r}${a}`,search:i(t)},{stringify:!1})}async function o(t,a){let i,o={...t},{method:l="GET",body:c}=o;!c||"object"!=typeof c||c instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let t={};for(let[a,r]of Object.entries(e))void 0!==r&&(t[a]=r);return t}(c)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||c instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=c?eM(c,{keyEncoder:em}):c);let u=await r(o),d="GET"===l?"GET":"POST",h=o.url,m={...o,method:d,credentials:o.credentials||"include"};try{if(u){let e=a?.fetchMaxTries??(k()?4:11);i=await tA(()=>fetch(h,m),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,a)=>"GET"===d&&a<e&&!m.signal?.aborted,onBeforeRetry:e=>{h.searchParams.set("_clerk_retry_attempt",e.toString())}})}else i=new Response("{}",o)}catch(t){let e=h.toString();tj.error("network error",{error:t,url:e,method:l},"fapiClient");throw Error(`${t2} Network error at "${e}" - ${t}. Please try again.`)}let p=204!==i.status?await i.json():null,f=Object.assign(i,{payload:p});return i.ok||tj.error("request failed",{method:l,path:o.path,status:i.status},"fapiClient"),await n(o,f),f}return{buildEmailAddress:function(t){return function({localPart:e,frontendApi:t}){return`${e}@${t?t.replace("clerk.",""):"clerk.com"}`}({localPart:t,frontendApi:e.frontendApi})},buildUrl:s,onAfterResponse:function(e){a.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.#eK.emit(S,"loading"),this.#eK.prioritizedOn(S,e=>this.#eR=e),this.#eK.on(S,e=>{tG()&&("ready"===e||"degraded"===e?window.__clerk_internal_ready?.__resolve&&this.#eV()&&window.__clerk_internal_ready.__resolve(this):"error"===e&&window.__clerk_internal_ready?.__reject&&window.__clerk_internal_ready.__reject(new q("Clerk failed to initialize.",{code:"clerk_init_failed"})))}),tG()&&("ready"===this.#eR||"degraded"===this.#eR)&&this.#eV()&&window.__clerk_internal_ready?.__resolve&&window.__clerk_internal_ready.__resolve(this),au.clerk=this,this.#eP=new iv}getFapiClient=()=>this.#eU;load=async e=>{if(tj.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#eM||e?.unsafe_disableDevelopmentModeConsoleWarning||eT("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.#eD=this.#eG(e),this.#eF=this.#eD.__internal_oauthTransport??null,this.#eD.ui?.ClerkUI&&(this.#eT=Promise.resolve(this.#eD.ui.ClerkUI).then(e=>new e(()=>this,()=>this.environment,this.#eD,this.#eH))),"development"===this.#eM&&(this.#eD.routerPush||this.#eD.routerReplace)&&(!this.#eD.routerPush||!this.#eD.routerReplace)){let e=this.#eD.routerPush?"routerReplace":"routerPush";eT(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}rs.on(ri,()=>{this.#eJ(this.session)}),this.#eD.sdkMetadata&&(iE.sdkMetadata=this.#eD.sdkMetadata),!1!==this.#eD.telemetry&&(this.telemetry=new tu({clerkVersion:iE.version,samplingRate:1,perEventSampling:!this.#eD.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eD.telemetry}),this.#eD.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let a=e.theme;if(!a)return{};if(Array.isArray(a))for(let e of a){let a=tg(e);if(a){t=a;break}}else t=tg(a);return{themeName:t}}(this.#eD.appearance)}));try{this.#eD.standardBrowser?await this.#eZ():await this.#e$();let e=this.#eD.telemetry,t=!1!==e&&!e?.disabled,a=!!this.#eD.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,n=this.environment?.isProduction?.()??!1,i=r||a&&!n,s=a&&!r?"error":void 0;i&&function(e={}){if(tk)return;let{enabled:t=!1,...a}=e;t&&(ty=!0,tk=!0,tx(a))}({enabled:!0,...s?{logLevel:s}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#eP?.load(this.environment),tj.info("load() complete",{},"clerk")}catch(e){throw this.#eK.emit(S,"error"),tj.error("load() failed",{error:e},"clerk"),e}}};#eY(){let e;return!!(!this.#eD.signUpUrl&&this.#eD.signInUrl&&(e=this.#eD.signInUrl,!eq.test(e)))}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let a="u">typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:tb.lQ,r="u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tb.lQ,n=e&&"object"==typeof e?e:t||{},i=n?.redirectUrl||this.buildAfterSignOutUrl();tj.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:i,sessionTarget:n?.sessionId??null},"clerk");let s="function"==typeof e?e:void 0,o=async()=>{let e=tP(this.#eD.standardBrowser);rs.emit(rr,null),await e.track(async()=>{s?await s():await this.navigate(i)}),e.isUnloading()||(this.#eJ(),await r())};if(await a(),!n.sessionId||1===this.client.signedInSessions.length){this.#eQ(),this.#eD.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),tj.info("signOut() complete",{redirectUrl:eW(i)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId);l?.id&&this.session?.id===l.id?(this.#eQ(),await l?.remove(),await o(),tj.info("signOut() complete",{redirectUrl:eW(i)},"clerk")):await l?.remove()};openGoogleOneTap=e=>{this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(tf("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(ee(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotOpenSignInOrSignUp,{code:iA});return}this.assertComponentsReady(this.#eT);let t="SignIn";this.#eT.then(e=>e.ensureMounted({preloadHint:t})).then(t=>t.openModal("signIn",e||{}));let a={withSignUp:e?.withSignUp??this.#eY()};this.telemetry?.record(tf(t,e,a))};closeSignIn=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(et(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotRenderAnyBillingComponent("Checkout"),{code:ij});return}if(!this.user){if("development"===this.#eM)throw new q(e6.cannotOpenCheckout,{code:iz});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(et(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotRenderAnyBillingComponent("PlanDetails"),{code:ij});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(tf("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#eM)throw new q(e6.cannotOpenUserProfile,{code:iz});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(tf("UserVerification",e))};__internal_closeReverification=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:a}=e;if(this.user||"development"!==this.#eM||eT(`Clerk: "${a}" requires an active user session. Ensure a user is signed in before executing ${a}.`),"organizations"===t){let t;return(t=this.environment,t?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#eM&&this.__internal_openEnableOrganizationsPrompt({caller:a,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.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(tp("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#eT),this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await Promise.resolve().then(n.bind(n,7544));return e};openSignUp=e=>{if(ee(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotOpenSignInOrSignUp,{code:iA});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"SignUp"})).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(tf("SignUp",e))};closeSignUp=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#eM)throw new q(e6.cannotOpenUserProfile,{code:iz});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"UserProfile"})).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(tf("UserProfile",e,t))};closeUserProfile=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:iS})}});if(t){if(!this.organization){if("development"===this.#eM)throw new q(e6.createCannotRenderComponentWhenOrgDoesNotExist("OrganizationProfile"),{code:iI});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"OrganizationProfile"})).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(tf("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:iS})}});t&&(this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"CreateOrganization"})).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(tf("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"Waitlist"})).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(tf("Waitlist",e))};closeWaitlist=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#eT);let a="SignIn";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#eY()};this.telemetry?.record(tp(a,t,r))};unmountSignIn=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#eT);let a="UserAvatar";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(tp(a,t))};unmountUserAvatar=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#eT);let a="SignUp";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(tp(a,t))};unmountSignUp=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#eM)throw new q(e6.cannotRenderComponentWhenUserDoesNotExist,{code:iz});return}this.assertComponentsReady(this.#eT);let a="UserProfile";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"userProfile",node:e,props:t}));let r=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(tp(a,t,r))};unmountUserProfile=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationProfile=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:iS})}});if(!a)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#eM)throw new q(e6.createCannotRenderComponentWhenOrgDoesNotExist("OrganizationProfile"),{code:iI});return}this.assertComponentsReady(this.#eT);let n="OrganizationProfile";this.#eT.then(e=>e.ensureMounted({preloadHint:n})).then(a=>a.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(tp(n,t))};unmountOrganizationProfile=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountCreateOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:iS})}});if(!a)return;this.assertComponentsReady(this.#eT);let r="CreateOrganization";this.#eT.then(e=>e.ensureMounted({preloadHint:r})).then(a=>a.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountCreateOrganization=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:iS})}});if(!a)return;this.assertComponentsReady(this.#eT);let r="OrganizationSwitcher";this.#eT.then(e=>e.ensureMounted({preloadHint:r})).then(a=>a.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(tp(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:iS})}});if(!a)return;this.assertComponentsReady(this.#eT);let r="OrganizationList";this.#eT.then(e=>e.ensureMounted({preloadHint:r})).then(a=>a.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(tp(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#eT);let a="UserButton";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"userButton",node:e,props:t}));let r={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(tp(a,t,r))};unmountUserButton=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#eT);let a="Waitlist";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(tp(a,t))};unmountWaitlist=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(et(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotRenderAnyBillingComponent("PricingTable"),{code:ij});return}this.assertComponentsReady(this.#eT);let a="PricingTable";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(tp(a,t))};unmountPricingTable=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOAuthConsent=(e,t)=>{if(!this.user){if("development"===this.#eM)throw new q(e6.cannotRenderOAuthConsentComponentWhenUserDoesNotExist,{code:iz});return}this.assertComponentsReady(this.#eT);let a="OAuthConsent";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"__internal_oauthConsent",node:e,props:t}))};unmountOAuthConsent=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>this.mountOAuthConsent(e,t);__internal_unmountOAuthConsent=e=>this.unmountOAuthConsent(e);mountAPIKeys=(e,t)=>{let a;if(ea(this,a=this.environment)&&er(this,a)){if("development"===this.#eM)throw new q(e6.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&er(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(!this.organization&&ea(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#eT);let r="APIKeys";this.#eT.then(e=>e.ensureMounted({preloadHint:r})).then(a=>a.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountAPIKeys=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountConfigureSSO=(e,t)=>{let a,r,{isEnabled:n}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"ConfigureSSO",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("ConfigureSSO"),{code:iS})}});if(!n)return;let i=!!this.user;if(!this.organization&&i){if("development"===this.#eM)throw new q(e6.createCannotRenderComponentWhenOrgDoesNotExist("ConfigureSSO"),{code:iI});return}if(a=this.environment,!a?.userSettings.enterpriseSSO.self_serve_sso||!this.organization?.selfServeSSOEnabled){if("development"===this.#eM)throw new q(e6.cannotRenderConfigureSSOComponentWhenDisabled,{code:"cannot_render_self_serve_sso_disabled"});return}if(r=this.environment,!r?.userSettings.attributes.email_address?.enabled){if("development"===this.#eM)throw new q(e6.cannotRenderConfigureSSOComponentWhenEmailAddressDisabled,{code:"cannot_render_configure_sso_email_address_disabled"});return}this.assertComponentsReady(this.#eT);let s="ConfigureSSO";this.#eT.then(e=>e.ensureMounted({preloadHint:s})).then(a=>a.mountComponent({name:s,appearanceKey:"configureSSO",node:e,props:t})),this.telemetry?.record(tp(s,t))};__internal_unmountConfigureSSO=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:iS})}});if(!a)return;this.assertComponentsReady(this.#eT);let r="TaskChooseOrganization";this.#eT.then(e=>e.ensureMounted({preloadHint:r})).then(a=>a.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountTaskChooseOrganization=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#eT);let a="TaskResetPassword";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(tp("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskSetupMFA=(e,t)=>{this.assertComponentsReady(this.#eT);let a="TaskSetupMFA";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"taskSetupMfa",node:e,props:t})),this.telemetry?.record(tp("TaskSetupMFA",t))};unmountTaskSetupMFA=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:a,navigate:r}=e,{session:n}=e;this.__internal_setActiveInProgress=!0,tj.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof n?n:n?.id??n??null,organizationTarget:"string"==typeof t?t:t?.id??t??null,redirectUrl:a??null},"clerk");try{var i;let s;if(!this.client)throw tj.warn("Clerk setActive called before client is loaded",{},"clerk"),Error("setActive is being called before the client is loaded. Wait for init.");if(void 0===n&&!this.session)throw tj.warn("Clerk setActive precondition not met: no target session and no active session",{},"clerk"),Error("setActive should either be called with a session param or there should be already an active session.");"string"==typeof n&&(n=this.client.sessions.find(e=>e.id===n)||null);let o="u">typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:tb.lQ,l="u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tb.lQ,c=void 0===n?this.session:n;c?.status==="pending"&&(i={...this.#eD,...e},s=["taskUrls","navigate"],Object.keys(i).some(e=>s.includes(e))||eT('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let u=void 0!==t;if(c&&u){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let t=c.user.organizationMemberships.find(t=>t.organization.slug===e),a=t?.organization.id||null,r=null===a;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=a}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0);let d=c?.status==="pending"&&c?.currentTask&&this.#eD.taskUrls?.[c?.currentTask.key],h=!!(a||d||r),m=u?"select_org":"select_session";if(tG()&&globalThis.document.hasFocus()||!this.#eD.standardBrowser){let e;if(h&&c)try{(e=await c.__internal_touch({intent:m}))&&this.updateClient(e,{__internal_dangerouslySkipEmit:!0})}catch(e){if(J(e))this.handleUnauthenticated();else throw e}else await this.#eX(c,m);c=this.#e1(c?.id,e)}try{await c?.getToken()||rs.emit(ra,{token:null})}catch(e){if(N.is(e))tj.warn("Token fetch failed when setting active session (offline). Preserving existing auth state.",{sessionId:c?.id},"clerk");else throw e}let p=tP(this.#eD.standardBrowser);if(h&&await p.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eQ(),d){let e=a?eL({base:d,hashSearchParams:{redirectUrl:a}},{stringify:!0}):d;await this.navigate(e)}else if(r&&c){let e=!1,t=t=>{if(e=!0,!this.client?.isEligibleForTouch())return t;let a=new URL(t,window.location.href),r=this.client.buildTouchUrl({redirectUrl:a});return this.buildUrlWithAuth(r)};await r({session:c,decorateUrl:t}),"development"===this.#eM&&!e&&this.client.isEligibleForTouch()&&eT("Clerk: The navigate callback in setActive() did not call decorateUrl(). In Safari, sessions may be limited to 7 days due to Intelligent Tracking Prevention (ITP). Use decorateUrl() to wrap your destination URL to enable the ITP workaround. Learn more: https://clerk.com/docs/troubleshooting/safari-itp")}else if(a){if(this.client.isEligibleForTouch()){let e=new URL(a,window.location.href),t=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(t)}await this.navigate(a)}}}),p.isUnloading())return;this.#eJ(c),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=(e,t)=>{var a;let r;return a=e,e=e=>{var t;r||={...e},a(r={...{client:n9((t=r).client,e.client),session:n9(t.session,e.session),user:n9(t.user,e.user),organization:n9(t.organization,e.organization)}})},this.#eN.push(e),this.client&&!t?.skipInitialEmit&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#eN=this.#eN.filter(t=>t!==e)}};on=(...e)=>{this.#eK.on(...e)};off=(...e)=>{this.#eK.off(...e)};__internal_addNavigationListener=e=>(this.#eB.push(e),()=>{this.#eB=this.#eB.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tG())return;if(void 0===window.location){let a=t?.replace&&this.#eD.routerReplace?this.#eD.routerReplace:this.#eD.routerPush;return a?(tj.info(`Clerk is navigating to: ${e}`),await a(e,{windowNavigate:this.__internal_windowNavigate})):void 0}setTimeout(()=>{this.#e0()},0);let a=new URL(e,window.location.href);this.#e2.includes(a.protocol)||(console.warn(`Clerk: "${a.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),a=new URL("/",window.location.href));let r=t?.replace&&this.#eD.routerReplace?this.#eD.routerReplace:this.#eD.routerPush;if(tj.info(`Clerk is navigating to: ${a}`),this.#eD.routerDebug&&console.log(`Clerk is navigating to: ${a}`),"null"!==a.origin&&a.origin!==window.location.origin||!r)return void this.__internal_windowNavigate(a);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:this.__internal_windowNavigate};return await r(eW(a),n)};buildUrlWithAuth(e){if("production"===this.#eM)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#eE?this.#eE.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#e9(t));let a=this.isSatellite?this.#e3(e):e;return this.#e5("signInUrl",{...a,redirectUrl:t},e?.initialValues)}buildSignUpUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#e9(t));let a=this.isSatellite?this.#e3(e):e;return this.#e5("signUpUrl",{...a,redirectUrl:t},e?.initialValues)}#e9=e=>{try{let t=new URL(e,window.location.origin);return t.searchParams.set(en,ei),t.toString()}catch{return e}};#e3=e=>{if(!e)return e;let t={...e};return t.signInForceRedirectUrl&&(t.signInForceRedirectUrl=this.#e9(t.signInForceRedirectUrl)),t.signInFallbackRedirectUrl&&(t.signInFallbackRedirectUrl=this.#e9(t.signInFallbackRedirectUrl)),t.signUpForceRedirectUrl&&(t.signUpForceRedirectUrl=this.#e9(t.signUpForceRedirectUrl)),t.signUpFallbackRedirectUrl&&(t.signUpFallbackRedirectUrl=this.#e9(t.signUpFallbackRedirectUrl)),t};buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eZ(this.#eD,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eZ(this.#eD,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eD.afterSignOutUrl?this.buildUrlWithAuth(this.#eD.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eD.newSubscriptionRedirectUrl?this.#eD.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?eL({base:this.#eD.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eD.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eD.afterMultiSessionSingleSignOutUrl):this.#eD.signInUrl?this.buildUrlWithAuth(eL({base:this.#eD.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 a=this.#eD.taskUrls?.[t.key];return a||eL({base:this.buildSignInUrl(e),hashPath:e2(t)},{stringify:!0})}#e6=async()=>{if(!tG())return;let e=new URLSearchParams({[en]:es}),t=eQ(el);t&&te(t)||function(){throw Error(`${t2} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let a=eL({base:eQ(el),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(a))};redirectWithAuth=async e=>{if(tG())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tG())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tG())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tG())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tG())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tG())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tG())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tG())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tG())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tG())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tG())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let a=eQ("__clerk_status");if("expired"===a)throw new F(W.Expired);if("client_mismatch"===a)throw new F(W.ClientMismatch);if("verified"!==a)throw new F(W.Failed);let r=eQ("__clerk_created_session"),{signIn:n,signUp:i,sessions:s}=this.client,o=s.some(e=>e.id===r),l="needs_second_factor"===n.status||"missing_requirements"===i.status,c=e=>t&&"function"==typeof t?t(e):this.navigate(e),u=e.redirectUrl?()=>c(e.redirectUrl):tb.lQ;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?u():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};__internal_handleResourceCallback=async(e,t,a)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:n}=this.client,i="identifier"in(e||{})?e:r,s="missingFields"in(e||{})?e:n,o=e=>a&&"function"==typeof a?a(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:s,signIn:i,navigate:o})};handleGoogleOneTapCallback=async(e,t,a)=>this.__internal_handleResourceCallback(e,t,a);_handleRedirectCallback=async(e,{signIn:t,signUp:a,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await t.reload():"signUp"===e.reloadResource&&await a.reload()}catch{}let{displayConfig:n}=this.environment,{firstFactorVerification:i}=t,{externalAccount:s}=a.verifications,o={status:a.status,missingFields:a.missingFields,externalAccountStatus:s.status,externalAccountErrorCode:s.error?.code,externalAccountSessionId:s.error?.meta?.sessionId,sessionId:a.createdSessionId,protectCheck:a.protectCheck},l={status:t.status,firstFactorVerificationStatus:i.status,firstFactorVerificationErrorCode:i.error?.code,firstFactorVerificationSessionId:i.error?.meta?.sessionId,sessionId:t.createdSessionId,protectCheck:t.protectCheck},c=e=>()=>r(e),u=c(e.signInUrl||n.signInUrl),d=c(e.signUpUrl||n.signUpUrl),h=c(e.firstFactorUrl||eL({base:n.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||eL({base:n.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||eL({base:n.signInUrl,hashPath:"/reset-password"},{stringify:!0})),f=c(e.signInProtectCheckUrl||eL({base:n.signInUrl,hashPath:"/protect-check"},{stringify:!0})),g=new eZ(this.#eD,e),b=c(e.continueSignUpUrl||eL({base:n.signUpUrl,hashPath:"/continue"},{stringify:!0})),y=c(e.signUpProtectCheckUrl||eL({base:n.signUpUrl,hashPath:"/protect-check"},{stringify:!0})),w=({missingFields:t})=>a.protectCheck||t.includes("protect_check")?y():t.length?b():(({signUp:e,verifyEmailPath:t,verifyPhonePath:a,protectCheckPath:r,continuePath:n,navigate:i,handleComplete:s,redirectUrl:o="",redirectUrlComplete:l="",oidcPrompt:c})=>{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:o,redirectUrlComplete:l,continueSignUp:!0,oidcPrompt:c});let s=e1();if((e.protectCheck||e.missingFields.some(e=>"protect_check"===e))&&r)return i(r,{searchParams:s});if(e.unverifiedFields?.includes("email_address")&&t)return i(t,{searchParams:s});if(e.unverifiedFields?.includes("phone_number")&&a)return i(a,{searchParams:s});if(n)return i(n,{searchParams:s})}})({signUp:a,verifyEmailPath:e.verifyEmailAddressUrl||eL({base:n.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||eL({base:n.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),protectCheckPath:e.signUpProtectCheckUrl||eL({base:n.signUpUrl,hashPath:"/protect-check"},{stringify:!0}),navigate:r}),k=e.signInUrl||n.signInUrl,v=e.signUpUrl||n.signUpUrl,_=e.__internal_navigateOnSetActive,x=async({session:e,baseUrl:t,redirectUrl:a})=>{_?await _({session:e,redirectUrl:a,decorateUrl:e=>this.buildUrlWithAuth(e)}):e.currentTask?await e9(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(a)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await x({session:e,baseUrl:k,redirectUrl:g.getAfterSignInUrl()})}});if("signUp"!==e.reloadResource&&(l.protectCheck||"needs_protect_check"===l.status))return f();if("signIn"!==e.reloadResource&&o.protectCheck)return y();if("transferable"===o.externalAccountStatus&&o.externalAccountErrorCode===ec){let e=await t.create({transfer:!0});if(e.protectCheck||"needs_protect_check"===e.status)return f();switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await x({session:e,baseUrl:v,redirectUrl:g.getAfterSignInUrl()})}});case"needs_first_factor":return h();case"needs_second_factor":return m();case"needs_new_password":return p();default:t3("sign in")}}let j="user_locked"===o.externalAccountErrorCode,z="user_locked"===l.firstFactorVerificationErrorCode;if(j)return d();if(z)return u();if("needs_first_factor"===l.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return h();if("needs_new_password"===l.status)return p();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return u();let t=await a.create({transfer:!0,unsafeMetadata:e.unsafeMetadata});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await x({session:e,baseUrl:v,redirectUrl:g.getAfterSignUpUrl()})}});case"missing_requirements":return w({missingFields:t.missingFields});default:t3("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await x({session:e,baseUrl:v,redirectUrl:g.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return m();let S=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,I="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(S||I){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await x({session:e,baseUrl:S?v:k,redirectUrl:g.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(a)?d():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?w({missingFields:a.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):u()};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:a,signUp:r}=this.client,n=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:a,navigate:n})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await rz.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&rs.emit(rr,null),this.setActive({session:null})}catch(e){if(M(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};__internal_handleUnauthenticatedDevBrowser=async()=>{this.#eE&&await this.#eE.handleUnauthenticatedDevBrowser()};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if(M(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:a,unsafeMetadata:r,strategy:n,legalAccepted:i,secondFactorUrl:s,protectCheckUrl:o,signUpProtectCheckUrl:l,walletName:c})=>{let u,d;if(!this.client||!this.environment)return;let{displayConfig:h}=this.environment,m=n.replace("web3_","").replace("_signature",""),p=await tY().getWeb3Identifier({provider:m,walletName:c});switch(m){case"metamask":u=tY().generateSignatureWithMetamask;break;case"base":u=tY().generateSignatureWithBase;break;case"coinbase_wallet":u=tY().generateSignatureWithCoinbaseWallet;break;case"solana":if(!c)throw new q("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});u=e=>tY().generateSignatureWithSolana({...e,walletName:c});break;default:u=tY().generateSignatureWithOKXWallet}let f=e=>()=>a&&"function"==typeof a?a(e):this.navigate(e),g=f(s||eL({base:h.signInUrl,hashPath:"/factor-two"},{stringify:!0})),b=f(o||eL({base:h.signInUrl,hashPath:"/protect-check"},{stringify:!0})),y=f(l||eL({base:h.signUpUrl,hashPath:"/protect-check"},{stringify:!0})),w=f(t||eL({base:h.signUpUrl,hashPath:"/continue"},{stringify:!0})),k=!1;try{d=await this.client.signIn.authenticateWithWeb3({identifier:p,generateSignature:u,strategy:n,walletName:c})}catch(e){if(tL(e,"form_identifier_not_found"))k=!0,d=await this.client.signUp.authenticateWithWeb3({identifier:p,generateSignature:u,unsafeMetadata:r,strategy:n,legalAccepted:i,walletName:c}),t&&"missing_requirements"===d.status&&"verified"===d.verifications.web3Wallet.status&&!d.protectCheck&&await w();else throw e}let v=async({session:e,redirectUrl:t})=>{e.currentTask?await e9(e,{baseUrl:h.signInUrl,navigate:this.navigate}):await this.navigate(t)};if(d.protectCheck||"needs_protect_check"===d.status)return void await (k?y:b)();switch(d.status){case"needs_second_factor":await g();break;case"complete":d.createdSessionId&&await this.setActive({session:d.createdSessionId,navigate:async({session:t})=>{await v({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>r4.create({name:e,slug:t});getOrganization=async e=>r4.get(e);joinWaitlist=async({emailAddress:e})=>n0.join({emailAddress:e});updateEnvironment(e){this.environment=e}__internal_setCountry=e=>{this.__internal_country||(this.__internal_country=e)};get __internal_last_error(){let e=this.internal_last_error;return this.internal_last_error=null,e}set __internal_last_error(e){this.internal_last_error=e}updateClient=(e,t)=>{if(!this.client){let t=this.#eD.selectInitialSession?this.#eD.selectInitialSession(e):this.#e8(e);this.#eJ(t,{dangerouslySkipEmit:!0})}if(this.client=e,this.session){let t=this.#e1(this.session.id,e);"active"===this.session.status&&t?.status==="pending"&&("u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tb.lQ)(),this.#eJ(t,{dangerouslySkipEmit:!0}),this.session?.lastActiveToken||v()||tj.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),rs.emit(ra,{token:this.session?.lastActiveToken})}t?.__internal_dangerouslySkipEmit||this.#e4()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new rY(e)};__internal_onBeforeRequest=e=>{this.#eU.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#eU.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#eG({...this.#eD,...e.options})};return this.#eT?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#e7=()=>{let e=new URLSearchParams({[el]:window.location.href});return eL({base:this.#eD.signInUrl,searchParams:e},{stringify:!0})};#te=()=>{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()||""};#tt=()=>{let e=eQ(en);return e!==es&&!!this.isSatellite&&(e===ei||!0===this.#eD.satelliteAutoSync&&!!this.#eE?.isSignedOut())};#ta=()=>"production"!==this.#eM&&!this.isSatellite&&!!eQ(el);#tr=async()=>{"development"===this.instanceType?await this.navigate(this.#e7()):"production"===this.instanceType&&await this.navigate(this.#te())};#tn=(e,t)=>{let a;try{a=new URL(e)}catch{throw Error(`${t2} The signInUrl needs to have a absolute url format.`)}a.origin===t&&function(){throw Error(`${t2} The signInUrl needs to be on a different origin than your satellite application.`)}()};#ti=()=>{this.isSatellite&&("development"!==this.#eM||this.#eD.signInUrl||function(){throw Error(`${t2} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${t2} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#eD.signInUrl&&this.#tn(this.#eD.signInUrl,window.location.origin))};#eZ=async()=>{if(this.#eE=await im.create(this,this.#eU,this.#eM,this.#eK),this.#ti(),this.#tt())return void await this.#tr();if(this.#ta())return void await this.#e6();this.#eL=(()=>{if(!f())return{onPageFocus:tb.lQ};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"u">typeof BroadcastChannel&&(this.#eO=new BroadcastChannel("clerk")),this.#ts();let e=function(e=window.location.hostname){if(!e)return!1;let t=eD.get(e);void 0===t&&(t=ek.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||ev.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),eD.set(e,t));return t}(window?.location.hostname),t="development"===this.#eM&&!e,a=0,r=0;for(;r<2;){r++;try{let e=rY.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++a;let e=t0.getItem(tQ,null);e&&this.updateEnvironment(new rY(e))}),r=async()=>{let e=new AbortController;return(0,tb.zc)(rz.getOrCreateInstance().fetch({abortSignal:e.signal}),7e3,e).then(e=>this.updateClient(e)).catch(async e=>{if(V(e))throw e;++a,this.#eE?.stopPollingForToken();try{let e=this.#e8(ib(this.#eE?.getSessionCookie()));e?.clearCache();let t=e?await (0,tb.zc)(e.getToken(),7e3).catch(()=>(e.clearCache(),this.#eE?.getSessionCookie())):this.#eE?.getSessionCookie();this.updateClient(ib(t))}finally{this.#eE?.startPollingForToken()}return rz.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(tb.lQ),null})},[,n]=await (0,tb.vd)([e,r()]);if("rejected"===n.status){let e=n.reason;if(tL(e,"requires_captcha"))await r();else throw e}if(this.#eE?.setClientUatCookieForDevelopmentInstances(),await this.#to())return;break}catch(e){if(tL(e,"dev_browser_unauthenticated"))await this.#eE.handleUnauthenticatedDevBrowser();else if(!v())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${t2} Something went wrong initializing Clerk.`)}()}this.#eq=new ip(this),this.#eq.start(),this.#tl(),this.#tc(),this.#tu(),this.#eK.emit(S,a>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#e$=async()=>{let e,t,a=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([rY.getInstance().fetch({touch:!1,fetchMaxTries:a}),rz.getOrCreateInstance().fetch({fetchMaxTries:a})])}catch(a){if(O(a)&&"network_error"===a.code&&this.shouldFallbackToCachedResources()){let a=await this.__internal_getCachedResources?.();e=new rY(a?.environment),rz.clearInstance(),t=rz.getOrCreateInstance(a?.client),++r}else throw a}this.updateClient(t),this.updateEnvironment(e),this.#eK.emit(S,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([rY.getInstance().fetch({touch:!1,fetchMaxTries:1}),rz.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#e4()};#e8=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#ts=()=>{f()&&(this.#eL?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eW>Date.now())&&(this.#eW=Date.now()+5e3,this.#eD.touchSession&&this.#eX(this.session,"focus"))}),this.#eO?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),rs.on(rr,()=>{this.#eO?.postMessage({type:"signout"})}),rs.on(rn,()=>{t0.setItem(tQ,this.environment?.__internal_toSnapshot(),864e5)}))};#eX=async(e,t="focus")=>{if(!e)return Promise.resolve();await e.touch({intent:t}).catch(e=>{if(J(e))this.handleUnauthenticated();else throw e})};__internal_lastEmittedResources;#e4=()=>{if(this.client){let e={client:this.client,session:this.session,user:this.user,organization:this.organization};for(let t of(this.__internal_lastEmittedResources=e,this.#eN))t(e)}};#e0=()=>{for(let e of this.#eB)e()};#eQ=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#e4()};#td=(e=this.session)=>(e?.user.organizationMemberships||[]).map(e=>e.organization).find(t=>t.id===e?.lastActiveOrganizationId)||null;#th=(e=this.session)=>({session:e||null,organization:this.#td(e),user:e?e.user:null});#eJ=(e,t)=>{let{session:a,organization:r,user:n}=this.#th(e);this.session=a,this.organization=r,this.user=n,t?.dangerouslySkipEmit||this.#e4()};#e1=(e,t=this.client)=>t?.signedInSessions.find(t=>t.id===e)||null;#tc=()=>{this.addListener(({session:e})=>{e?.actor&&this.#eT?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#tu=()=>{this.#eD.__internal_keyless_claimKeylessApplicationUrl&&this.#eT?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eD.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eD.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eD.__internal_keyless_dismissPrompt}})})};#e5=(e,t,a)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eD[e]||this.environment.displayConfig[e];this.#eY()&&(r=this.#eD.signInUrl);let n=new eZ(this.#eD,t).toSearchParams(),i=new URLSearchParams(a||{}),s=eL({base:r,hashPath:this.#eY()&&"signUpUrl"===e?"/create":"",hashSearchParams:[i,n]},{stringify:!0});return this.buildUrlWithAuth(s)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#to=async()=>{var e;let t,a,r,n,i=new URLSearchParams(window.location.search).get("redirect_url"),s="production"===this.instanceType,o=null!==i&&(e=this.frontendApi,a=(t=new URL(i,eR)).pathname,r=eG.includes(a)||eJ.includes(a),e===t.host&&r);if(s||!o)return!1;let l=this.session,c=this.#eD.signInUrl||this.environment?.displayConfig.signInUrl,u=c&&window.location.href.startsWith(c),d=this.#eD.signUpUrl||this.environment?.displayConfig.signUpUrl,h=d&&window.location.href.startsWith(d);return n=new URL(i,eR),(!eG.includes(n.pathname)||!!l||!u&&!h)&&(await this.navigate(this.buildUrlWithAuth(i)),!0)};#eG=e=>{let t=e?.clerkUICtor??e?.clerkUiCtor,a=t?{...e?.ui,ClerkUI:t}:e?.ui;return{...iC,...e,ui:a,allowedRedirectOrigins:function(e,t,a){if(Array.isArray(e)&&e.length)return e;let r=[];return"u">typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${eF(t)}`),r.push(`https://*.${eF(t)}`),"development"===a&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)}};#tl=()=>{try{eX(en),eX(e$),eX(eo),eX("__clerk_handshake"),eX("__clerk_handshake_nonce"),eX("__clerk_help")}catch{}};get #e2(){let e=e4;return this.#eD.allowedRedirectProtocols&&(e=e.concat(this.#eD.allowedRedirectProtocols)),e}__internal_windowNavigate=(e,t)=>{!function(e,t){if("string"==typeof e&&e7.test(function(e){let t=0;for(;t<e.length&&32>=e.charCodeAt(t);)t++;let a="";for(let r=t;r<e.length;r++){let t=e.charCodeAt(r);9!==t&&10!==t&&13!==t&&(a+=e[r])}return a}(e)))return console.warn(`Clerk: scheme-relative navigation to "${e}" is not allowed. Provide a same-origin path or an absolute URL.`);let a=new URL(e,window.location.href);(t?.allowedProtocols??e4).includes(a.protocol)?(window.dispatchEvent(new CustomEvent(e8)),window.location.href=a.href):console.warn(`Clerk: "${a.protocol}" is not a valid navigation protocol. Aborting navigation. If you think this is a mistake, please open an issue.`)}(e,{allowedProtocols:t?.useStaticAllowlistOnly?e4:this.#e2})};#eV(){return void 0!==this.client}}})();var s=exports;for(var o in i)s[o]=i[o];i.__esModule&&Object.defineProperty(s,"__esModule",{value:!0})})();
61
+ For more information contact us at ${t}`)}function ae(e){throw Error(`${t2} Calling ${e}.reload is not currently supported. Please contact support.`)}function at(e){throw Error(`${t2} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function aa(e="",t){let{async:a,defer:r,beforeLoad:n,crossOrigin:i,nonce:s}=t||{};return tA(()=>new Promise((t,o)=>{e||o(Error("loadScript cannot be called without a src")),document&&document.body||o(Error("loadScript cannot be called when document does not exist"));let l=document.createElement("script");i&&l.setAttribute("crossorigin",i),l.async=a||!1,l.defer=r||!1,l.addEventListener("load",()=>{l.remove(),t(l)}),l.addEventListener("error",t=>{l.remove(),o(t.error??Error(`failed to load script: ${e}`))}),l.src=e,s&&(l.nonce=s),n?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>t<=5})}async function ar(e){return window.turnstile||await an(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function an(e){try{return await aa("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 ai(e){try{let t=e.getAttribute("data-cl-theme")||void 0,a=e.getAttribute("data-cl-language")||void 0,r=e.getAttribute("data-cl-size")||void 0;return{theme:t,language:a,size:r}}catch{return{theme:void 0,language:void 0,size:void 0}}}let as=async e=>{let t,a,r,n,{siteKey:i,widgetType:s,invisibleSiteKey:o,nonce:l}=e,{modalContainerQuerySelector:c,modalWrapperQuerySelector:u,closeModal:d,openModal:h}=e,m=await ar(l),p=[],f="",g="",b=i,y=0,w=null,k="invisible";if(c&&u){w=s,n=c,k="modal";try{await h?.()}catch{throw{captchaError:"modal_component_not_ready"}}let e=await new Promise(e=>{if(document.querySelector(c))return e(document.querySelector(c));let t=new MutationObserver(()=>{document.querySelector(c)&&(t.disconnect(),e(document.querySelector(c)))});t.observe(document.body,{childList:!0,subtree:!0})});if(e){let{theme:n,language:i,size:s}=ai(e);t=n,r=i,a=s}}if(!n&&"smart"===s){let e=document.getElementById(eu);if(e){k="smart",w="smart",n=`#${eu}`,e.style.maxHeight="0";let{theme:i,language:s,size:o}=ai(e);t=i,r=s,a=o}else console.error("Cannot initialize Smart CAPTCHA widget because the `clerk-captcha` DOM element was not found; falling back to Invisible CAPTCHA widget. If you are using a custom flow, visit https://clerk.com/docs/guides/development/custom-flows/authentication/bot-sign-up-protection for instructions")}if(!n){k="invisible",b=o,w="invisible",n=`.${ed}`;let e=document.createElement("div");e.classList.add(ed),e.style.display="none",document.body.appendChild(e)}let v=async()=>new Promise((i,s)=>{try{let o=m.render(n,{sitekey:b,appearance:"interaction-only",theme:t||"auto",size:a||"normal",language:r||"auto",action:e.action,retry:"never","refresh-expired":"auto",callback:function(e){d?.(),i([e,o])},"before-interactive-callback":()=>{if(u){let e=document.querySelector(u);e?.style.setProperty("visibility","visible"),e?.style.setProperty("pointer-events","all")}else{let e=document.getElementById(eu);e&&(e.style.maxHeight="unset",e.style.minHeight="compact"===a?"140px":"68px",e.style.marginBottom="1.5rem",e.dataset.clInteractive="true")}},"error-callback":function(e){var t;(p.push(e),y<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))?setTimeout(()=>{n&&!document.querySelector(n)?s([p.join(","),o]):(m.reset(o),y++)},250):s([p.join(","),o])},"unsupported-callback":function(){return s(["This browser is not supported by the CAPTCHA.",o]),!0}})}catch(e){s([e,void 0])}});try{[f,g]=await v(),m.remove(g)}catch([e,t]){throw t&&m.remove(t),{captchaError:e}}finally{if("modal"===k&&d?.(),"invisible"===k){let e=document.querySelector(`.${ed}`);e&&document.body.removeChild(e)}if("smart"===k){let e=document.getElementById(eu);e&&(delete e.dataset.clInteractive,e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:f,captchaWidgetType:w}},ao=e=>{let t=e.__internal_environment,a=t?t.displayConfig.captchaProvider:"turnstile",r=e.__internal_getOption?.("nonce");return{captchaSiteKey:t?t.displayConfig.captchaPublicKey:null,captchaWidgetType:t?t.displayConfig.captchaWidgetType:null,captchaProvider:a,captchaPublicKeyInvisible:t?t.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:t?t.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:r||void 0}};class al{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:a,captchaPublicKeyInvisible:r,nonce:n}=ao(this.clerk);return a&&t&&r?{...await as({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:r,nonce:e?.nonce||n||void 0,siteKey:r,widgetType:"invisible"}).catch(e=>e.captchaError?{captchaError:e.captchaError}:{captchaError:e?.message||e||"unexpected_captcha_error"}),captchaAction:e?.action}:{captchaError:"captcha_unavailable",captchaAction:e?.action}}async managedOrInvisible(e){let{captchaSiteKey:t,canUseCaptcha:a,captchaWidgetType:r,captchaProvider:n,captchaPublicKeyInvisible:i,nonce:s}=ao(this.clerk);if(a&&t&&i){let a=await as({captchaProvider:n,invisibleSiteKey:i,nonce:s||void 0,siteKey:t,widgetType:r,...e}).catch(t=>t.captchaError?{captchaError:t.captchaError}:e?.action==="verify"?{captchaError:t?.message||t||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...a,captchaAction:"verify"}:a}return e?.action==="verify"?{captchaError:"captcha_unavailable",captchaAction:e?.action}:{}}async managedInModal(e){if("u"<typeof document)throw new q("Captcha is not supported in non-browser environments",{code:"captcha_unavailable"});return this.managedOrInvisible({modalWrapperQuerySelector:"#cl-modal-captcha-wrapper",modalContainerQuerySelector:"#cl-modal-captcha-container",openModal:()=>this.clerk.__internal_openBlankCaptchaModal(),closeModal:()=>this.clerk.__internal_closeBlankCaptchaModal(),action:e?.action})}}class ac{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return ac.instance||(ac.instance=new ac(rS,al)),ac.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new q("Security verification failed. Please try again by refreshing the page, clearing your browser cookies, or using a different web browser.",{code:"captcha_client_attempts_exceeded"});try{return this.inflightException&&await this.inflightException,await t()}catch(r){let a;if(!M(r)||O(r)&&"network_error"===r.code||r.errors[0]?.code!=="requires_captcha")throw r;if(this.inflightException)return await this.inflightException,await t();this.inflightException=new Promise(e=>a=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{a(),this.inflightException=null}return await t()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class au{static clerk;id;pathRoot="";static get fapiClient(){return au.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 ac.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let a;au.fapiClient||function(){throw Error(`${t2} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=t;try{a=await au.fapiClient.request(e,{fetchMaxTries:r})}catch(t){if(this.shouldRethrowOfflineNetworkErrors())throw new q(t?.message||t,{code:"network_error"});if(!v())return tj.warn("Network request failed while offline, returning null",{method:e.method,path:e.path},"baseResource"),null;throw t}let{payload:n,status:i,statusText:s,headers:o}=a;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||t.forceUpdateClient)&&!t.skipUpdateClient&&this._updateClient(n),i>=200&&i<=299)return n;if(i>=400){let e=n?.errors,t=e?.[0]?.long_message,a=e?.[0]?.code;401===i&&"dev_browser_unauthenticated"===a?await au.clerk.__internal_handleUnauthenticatedDevBrowser():401===i&&"requires_captcha"!==a&&await au.clerk.handleUnauthenticated(),function(e,t){var a;if(!t||!t[0])return;let r=t[0],n=r.long_message;if("origin_invalid"===r.code&&((a=au.clerk.publishableKey).startsWith("live_")||a.startsWith("pk_live_"))){let a=au.clerk.frontendApi.replace("clerk.","");throw new U(`Clerk: Production Keys are only allowed for domain "${a}".
62
+ API Error: ${n}`,{data:t,status:e})}}(i,e);let r={data:e,status:i};if(429===i&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(r.retryAfter=t)}}throw new U(t||s,r)}return null}static _updateClient(e){let t=rz(e);t&&au.clerk&&au.clerk.updateClient(t)}path(e){let t=this.pathRoot;if(this.isNew())return t;let a=t.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?a.replace(/[^/]$/,"$&/")+encodeURIComponent(e):a}withDefault(e,t){return e??t}async _baseGet(e={}){let t=await au._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce,signal:e.abortSignal},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:a,method:r,path:n}=e,i=await au._fetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}async _baseMutateBypass(e){let{action:t,body:a,method:r,path:n}=e,i=await au._baseFetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}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=au.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}class ad extends au{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?tq(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tq(e.last_used_at):null,this.updatedAt=tq(e.updated_at),this.createdAt=tq(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 ah extends au{claimedAt=null;reverification=!1;singleSessionMode=!1;preferredChannels=null;sessionMinter=!1;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.claimedAt=this.withDefault(e.claimed_at?tq(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels),this.sessionMinter=this.withDefault(e.session_minter,this.sessionMinter)),this}__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,session_minter:this.sessionMinter}}}(A=E||(E={}))[A.None=0]="None",A[A.Mutable=1]="Mutable",A[A.Watching=2]="Watching",A[A.RecursedCheck=4]="RecursedCheck",A[A.Recursed=8]="Recursed",A[A.Dirty=16]="Dirty",A[A.Pending=32]="Pending";let am=[],{link:ap,unlink:af,propagate:ag,checkDirty:ab,endTracking:ay,startTracking:aw,shallowPropagate:ak}=function({update:e,notify:t,unwatched:a}){let r=0;return{link:function(e,t){let a,n=t.depsTail;if(void 0!==n&&n.dep===e)return;if(4&t.flags&&void 0!==(a=void 0!==n?n.nextDep:t.deps)&&a.dep===e){a.version=r,t.depsTail=a;return}let i=e.subsTail;if(void 0!==i&&i.version===r&&i.sub===t)return;let s=t.depsTail=e.subsTail={version:r,dep:e,sub:t,prevDep:n,nextDep:a,prevSub:i,nextSub:void 0};void 0!==a&&(a.prevDep=s),void 0!==n?n.nextDep=s:t.deps=s,void 0!==i?i.nextSub=s:e.subs=s},unlink:n,propagate:function(e){let a,r=e.nextSub;t:for(;;){let n=e.sub,i=n.flags;if(3&i&&(60&i?12&i?4&i?!(48&i)&&function(e,t){let a=t.depsTail;if(void 0!==a){let r=t.deps;do{if(r===e)return!0;if(r===a)break;r=r.nextDep}while(void 0!==r)}return!1}(e,n)?(n.flags=40|i,i&=1):i=0:n.flags=-9&i|32:i=0:n.flags=32|i,2&i&&t(n),1&i)){let t=n.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(a={value:r,prev:a},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==a;)if(e=a.value,a=a.prev,void 0!==e){r=e.nextSub;continue t}break}},checkDirty:function(t,a){let r,n=0;t:for(;;){let s=t.dep,o=s.flags,l=!1;if(16&a.flags)l=!0;else if((17&o)==17){if(e(s)){let e=s.subs;void 0!==e.nextSub&&i(e),l=!0}}else if((33&o)==33){(void 0!==t.nextSub||void 0!==t.prevSub)&&(r={value:t,prev:r}),t=s.deps,a=s,++n;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;n;){--n;let s=a.subs,o=void 0!==s.nextSub;if(o?(t=r.value,r=r.prev):t=s,l){if(e(a)){o&&i(s),a=t.sub;continue}}else a.flags&=-33;if(a=t.sub,void 0!==t.nextDep){t=t.nextDep;continue t}l=!1}return l}},endTracking:function(e){let t=e.depsTail,a=void 0!==t?t.nextDep:e.deps;for(;void 0!==a;)a=n(a,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:i};function n(e,t=e.sub){let r=e.dep,i=e.prevDep,s=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==s?s.prevDep=i:t.depsTail=i,void 0!==i?i.nextDep=s:t.deps=s,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&a(r),s}function i(e){do{let a=e.sub,r=e.nextSub,n=a.flags;(48&n)==32&&(a.flags=16|n,2&n&&t(a)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?aA(e):aC(e,e.value),notify:function e(t){let a=t.flags;if(!(64&a)){t.flags=64|a;let r=t.subs;void 0!==r?e(r.sub):am[ax++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=af(t,e);while(void 0!==t)}}else"previousValue"in e||aO.call(e)}}),av=0,a_=0,ax=0;function aj(t){let a=e;return e=t,a}function az(e){return aq.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function aS(e){return aP.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function aI(a){let r={fn:a,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?ap(r,e):void 0!==t&&ap(r,t);let n=aj(r);try{r.fn()}finally{aj(n)}return aO.bind(r)}function aA(e){let t=aj(e);aw(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{aj(t),ay(e)}}function aC(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function aE(){for(;a_<ax;){let e=am[a_];am[a_++]=void 0,function e(t,a){if(16&a||32&a&&ab(t.deps,t)){let e=aj(t);aw(t);try{t.fn()}finally{aj(e),ay(t)}return}32&a&&(t.flags=-33&a);let r=t.deps;for(;void 0!==r;){let t=r.dep,a=t.flags;64&a&&e(t,t.flags=-65&a),r=r.nextDep}}(e,e.flags&=-65)}a_=0,ax=0}function aP(){let a=this.flags;if(16&a||32&a&&ab(this.deps,this)){if(aA(this)){let e=this.subs;void 0!==e&&ak(e)}}else 32&a&&(this.flags=-33&a);return void 0!==e?ap(this,e):void 0!==t&&ap(this,t),this.value}function aq(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(ag(e),av||aE())}}else{let t=this.value;if(16&this.flags&&aC(this,t)){let e=this.subs;void 0!==e&&ak(e)}return void 0!==e&&ap(this,e),t}}function aO(){let e=this.deps;for(;void 0!==e;)e=af(e,this);let t=this.subs;void 0!==t&&af(t),this.flags=0}function aT(e){let{pageSize:t,initialPage:a,...r}=e||{},n=t??10;return new URLSearchParams({...Object.entries(r).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),limit:n+"",offset:((a??1)-1)*n+""})}class aU{static #eh="/billing";static path(e,t){let{orgId:a}=t||{},r=a?`/organizations/${a}`:"/me";return`${r}${aU.#eh}${e}`}getPlans=async e=>{let{for:t,orgId:a,minSeats:r,...n}=e||{},i={...n,payer_type:"organization"===t?"org":"user",org_id:a,min_seats:r};return await au._fetch({path:`${aU.#eh}/plans`,method:"GET",search:aT(i)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new a8(e))}})};getPlan=async e=>new a8(await au._fetch({path:`${aU.#eh}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await au._fetch({path:aU.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new re(e?.response));getStatements=async e=>{let{orgId:t,...a}=e;return await au._fetch({path:aU.path("/statements",{orgId:t}),method:"GET",search:aT(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new a4(e))}})};getStatement=async e=>new a4((await au._fetch({path:aU.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...a}=e;return await au._fetch({path:aU.path("/payment_attempts",{orgId:t}),method:"GET",search:aT(a)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new a1(e))}})};getPaymentAttempt=async e=>new a1(await au._fetch({path:aU.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...a}=e;return new a$((await au._fetch({path:aU.path("/checkouts",{orgId:t}),method:"POST",body:a}))?.response)};getCreditBalance=async e=>await au._fetch({path:aU.path("/credits",{orgId:e.orgId}),method:"GET"}).then(e=>new aQ(e?.response));getCreditHistory=async e=>await au._fetch({path:aU.path("/credits/history",{orgId:e.orgId}),method:"GET"}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new aX(e))}})}let aM=az({resource:null}),aR=az({error:null}),aN=az({status:"idle"}),aB=aS(()=>{let e=aM().resource,t=aR().error,a=aN().status;return{errors:aJ(t,{identifier:null,password:null,code:null}),fetchStatus:a,signIn:e?e.__internal_future:null}}),aD=az({resource:null}),aF=az({error:null}),aL=az({status:"idle"}),aW=aS(()=>{let e=aD().resource,t=aF().error,a=aL().status;return{errors:aJ(t,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:a,signUp:e?e.__internal_future:null}}),aK=az({resource:null}),aH=az({error:null}),aV=az({status:"idle"}),aG=aS(()=>{let e=aK().resource,t=aH().error,a=aV().status;return{errors:aJ(t,{emailAddress:null}),fetchStatus:a,waitlist:e}});function aJ(e,t){let a={fields:{...t},raw:null,global:null};if(!e)return a;if(!M(e))return a.raw=[e],a.global=[X(e)],a;function r(e){return"meta"in e&&e.meta&&"paramName"in e.meta&&void 0!==e.meta.paramName}return e.errors.some(r)?e.errors.forEach(e=>{if(a.raw?a.raw.push(e):a.raw=[e],r(e)){let t=eh(e.meta.paramName);t in a.fields&&(a.fields[t]=e)}}):(a.raw=[e],a.global=[X(e)]),a}class aZ extends au{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=tq(e.created_at)),e.updated_at&&(this.updatedAt=tq(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 a$ extends au{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 a5(e.payment_method):void 0,this.plan=new a8(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=tD(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tq(e.free_trial_ends_at)),this.payer=new aZ(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>tA(()=>this._basePatch({path:aU.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!M(e)||t>=4)return!1;let a=e?.status,r=409===a&&e.errors?.[0]?.code==="checkout_already_in_progress";return a>=500||r}})}class aY{resource=new a$(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 a$.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new a$(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 a$.clerk.setActive({session:a$.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,a){var r,n,i;return void 0===a$.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,n=this.signals,i=this.pendingOperations,async(e,t,a)=>{if(i.get(e))return i.get(e);let s=(async()=>{++av,n.errorSignal({error:null}),n.fetchSignal({status:"fetching"}),a?.(),--av||aE(),++av;try{return await t(),n.resourceSignal({resource:r}),{error:null}}catch(e){return n.errorSignal({error:e}),{error:e}}finally{i.delete(e),n.fetchSignal({status:"idle"}),--av||aE()}})();return i.set(e,s),s})(e,t,a)}}class aQ{balance;constructor(e){this.balance=e.balance?tO(e.balance):null}}class aX extends au{id;amount;sourceType;sourceId;createdAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=tO(e.amount),this.sourceType=e.source_type,this.sourceId=e.source_id,this.createdAt=tq(e.created_at)),this}}class a1 extends au{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;totals=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){let t;return e?(this.id=e.id,this.amount=tO(e.amount),this.paidAt=e.paid_at?tq(e.paid_at):null,this.failedAt=e.failed_at?tq(e.failed_at):null,this.updatedAt=tq(e.updated_at),this.paymentMethod=e.payment_method?new a5(e.payment_method):null,this.subscriptionItem=new rt(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status,this.totals=e.totals?{subtotal:tO((t=e.totals).subtotal),grandTotal:tO(t.grand_total),taxTotal:tO(t.tax_total),baseFee:t.base_fee?tO(t.base_fee):null,perUnitTotals:t.per_unit_totals?tU(t.per_unit_totals):void 0,discounts:t.discounts?tN(t.discounts):null}:null,this):this}}let a0="/payment_methods",a2=async e=>{let{orgId:t,...a}=e;return new a6((await au._fetch({path:aU.path(`${a0}/initialize`,{orgId:t}),method:"POST",body:a}))?.response)},a9=async e=>{let{orgId:t,...a}=e;return new a5((await au._fetch({path:aU.path(a0,{orgId:t}),method:"POST",body:a}))?.response)},a3=async e=>{let{orgId:t,...a}=e??{};return await au._fetch({path:aU.path(a0,{orgId:t}),method:"GET",search:aT(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new a5(e))}})};class a5 extends au{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:tq(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tq(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new rA((await au._fetch({path:aU.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await au._fetch({path:aU.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class a6 extends au{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 a8 extends au{id;name;fee=null;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;unitPrices;availablePrices;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=e.fee?tO(e.fee):null,this.annualFee=e.annual_fee?tO(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?tO(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 r1(e)),this.unitPrices=e.unit_prices?.map(tM),this.availablePrices=e.available_prices?.map(e=>({id:e.id,fee:e.fee?tO(e.fee):null,annualMonthlyFee:e.annual_monthly_fee?tO(e.annual_monthly_fee):null,isDefault:e.is_default,unitPrices:e.unit_prices?.map(tM)}))),this}}class a4 extends au{id;status;timestamp;totals;groups;constructor(e){super(),this.fromJSON(e)}fromJSON(e){var t;let a;return e?(this.id=e.id,this.status=e.status,this.timestamp=tq(e.timestamp),this.totals=(a={grandTotal:tO((t=e.totals).grand_total),subtotal:tO(t.subtotal),taxTotal:tO(t.tax_total)},"base_fee"in t&&t.base_fee&&(a.baseFee=tO(t.base_fee)),"past_due"in t&&(a.pastDue=t.past_due?tO(t.past_due):null),"credit"in t&&(a.credit=t.credit?tO(t.credit):null),"per_unit_totals"in t&&(a.perUnitTotals=t.per_unit_totals?tU(t.per_unit_totals):void 0),"credits"in t&&(a.credits=t.credits?tR(t.credits):null),"total_due_now"in t&&(a.totalDueNow=tO(t.total_due_now)),"total_due_after_free_trial"in t&&(a.totalDueAfterFreeTrial=t.total_due_after_free_trial?tO(t.total_due_after_free_trial):null),"discounts"in t&&(a.discounts=t.discounts?tN(t.discounts):null),"total_due_per_period"in t&&t.total_due_per_period&&(a.totalDuePerPeriod=tO(t.total_due_per_period)),"totals_due_per_period"in t&&t.totals_due_per_period&&(a.totalsDuePerPeriod=tB(t.totals_due_per_period)),a),this.groups=e.groups.map(e=>new a7(e)),this):this}}class a7{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tq(e.timestamp),this.items=e.items.map(e=>new a1(e))),this}}class re extends au{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=tq(e.created_at),this.updatedAt=e.updated_at?tq(e.updated_at):null,this.activeAt=tq(e.active_at),this.pastDueAt=e.past_due_at?tq(e.past_due_at):null,this.nextPayment=void 0===e.next_payment?void 0:null===e.next_payment?null:tF(e.next_payment),this.subscriptionItems=(e.subscription_items||[]).map(e=>new rt(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1),this):this}}class rt extends au{id;plan;planPeriod;priceId;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;seats;credits;nextPayment;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e?(this.id=e.id,this.plan=new a8(e.plan),this.planPeriod=e.plan_period,this.priceId=e.price_id,this.status=e.status,this.createdAt=tq(e.created_at),this.pastDueAt=e.past_due_at?tq(e.past_due_at):null,this.periodStart=tq(e.period_start),this.periodEnd=e.period_end?tq(e.period_end):null,this.canceledAt=e.canceled_at?tq(e.canceled_at):null,this.amount=e.amount?tO(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:tO(e.credit.amount)}:void 0,this.seats=e.seats?{quantity:e.seats.quantity,...e.seats.tiers?{tiers:e.seats.tiers.map(tT)}:{}}:void 0,this.credits=e.credits?tR(e.credits):void 0,this.nextPayment=void 0===e.next_payment?void 0:null===e.next_payment?null:tF(e.next_payment),this.isFreeTrial=this.withDefault(e.is_free_trial,!1),this):this}async cancel(e){let{orgId:t}=e;return new rA((await au._fetch({path:aU.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let ra="token:update",rr="user:signOut",rn="environment:update",ri="session:tokenResolved",rs=z(),ro={build:(e,t,a)=>[e,t,a].filter(Boolean).join("-"),parse:(e,t,a)=>{let r=ro.extractTemplate(e,t,a);return{organizationId:a,sessionId:t,template:r}},extractTemplate:(e,t,a)=>{if(e===t||a&&e===`${t}-${a}`)return;let r=e.slice(t.length+1);return a&&r.endsWith(`-${a}`)&&(r=r.slice(0,-(a.length+1))),r||void 0}};var rl=n(8591),rc='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 ru=(e,t={})=>{if("u"<typeof Worker)return null;try{let a=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(a);return new Worker(r,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},rd=()=>{let e=0,t=()=>e++,a=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{a.get(e.data.id)?.()},i=ru(rc,{name:"clerk-timers"});if(i?.addEventListener("message",n),!i)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:rl.t};let s=()=>{i||(i=ru(rc,{name:"clerk-timers"}),i?.addEventListener("message",n))};return{setTimeout:(e,n)=>{s();let o=t();return a.set(o,()=>{e(),a.delete(o)}),r(i,{type:"setTimeout",id:o,ms:n}),o},setInterval:(e,n)=>{s();let o=t();return a.set(o,e),r(i,{type:"setInterval",id:o,ms:n}),o},clearTimeout:e=>{s(),a.delete(e),r(i,{type:"clearTimeout",id:e})},clearInterval:e=>{s(),a.delete(e),r(i,{type:"clearInterval",id:e})},cleanup:()=>{i&&(i.terminate(),i=null,a.clear())}}};function rh(){if("u">typeof document)try{if("function"!=typeof document.hasFocus)return;return document.hasFocus()}catch{return}}var rm=n(8388),rp=n.n(rm);class rf{lock=(function(e){let t=new(rp());return{acquireLockAndRun:async a=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,r=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(e,{signal:t.signal},async()=>(clearTimeout(r),await a())).catch(()=>!1)}if(await t.acquireLock(e,5e3))try{return await a()}finally{await t.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=rd();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let t=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e);let a=!0===rh()?1500:5e3;this.timerId=this.workerTimers.setTimeout(t,a)};t()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}let rg="clerk";function rb(e){return"getRawString"in e?e.jwt:e}function ry(e,t){if(null==e)return t;let a=rb(e)?.header?.oiat,r=rb(t)?.header?.oiat;return null==a&&null==r?t:null==r?e:null==a?t:a>r?e:a<r?t:(rb(e)?.claims?.iat??0)>(rb(t)?.claims?.iat??0)?e:t}function rw(e){return rb(e)?.header?.oiat}function rk(e){return rb(e)?.claims?.sid}function rv(e){let t=rb(e)?.claims;return t?.org_id||(t?.o?.id??"")}let r_={broadcast:!0},rx={broadcast:!1},rj=(s=new Map,o={get:e=>s.get(e),set:(e,t)=>{s.set(e,t)},delete:e=>{s.delete(e)},clear:()=>{s.clear()},forEach:e=>{s.forEach((t,a)=>e(t,a))},size:()=>s.size},l=((e=rg)=>({toKey:({tokenId:t,audience:a})=>[e,t,a||""].join("::")}))(C),c=Math.random().toString(36).slice(2),u=null,(d=()=>u||("u"<typeof BroadcastChannel?null:((u=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{m(e)}),u)))(),h=e=>{d();let t=l.toKey(e),a=o.get(t);if(!a)return;let r=Math.floor(Date.now()/1e3)-a.createdAt;if((a.expiresIn??1/0)-r<=5){void 0!==a.timeoutId&&clearTimeout(a.timeoutId),void 0!==a.refreshTimeoutId&&clearTimeout(a.refreshTimeoutId),o.delete(t);return}return{entry:a.entry}},m=async({data:e})=>{let t,a=ro.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==a)return void tj.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:a,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:c,template:e.template,traceId:e.traceId},"tokenCache");try{t=new nW({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){tj.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:c,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let r=t.jwt?.claims?.iat,n=t.jwt?.claims?.exp;if(!r||!n)return void tj.warn("Token missing iat/exp claim, skipping cache update",{tabId:c,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let a=h({tokenId:e.tokenId});if(a){let r=a.entry.resolvedToken??await a.entry.tokenResolver;if(ry(r,t)===r)return void tj.debug("Ignoring staler token broadcast",{tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){tj.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:c,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}tj.info("Updating token cache from broadcast",{iat:r,organizationId:e.organizationId,tabId:c,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),p({createdAt:r,tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},rx)},p=(e,t=r_)=>{let a=l.toKey({audience:e.audience,tokenId:e.tokenId}),r=o.get(a);clearTimeout(r?.timeoutId),clearTimeout(r?.refreshTimeoutId);let n=Math.floor(Date.now()/1e3),i={createdAt:e.createdAt??n,entry:e,expiresIn:void 0},s=r?.entry.resolvedToken;i.baseline=s?ry(r?.baseline,s):r?.baseline;let d=e=>{o.get(a)===e&&(clearTimeout(e.timeoutId),clearTimeout(e.refreshTimeoutId),o.delete(a))};o.set(a,i),e.tokenResolver.then(r=>{let n=o.get(a);if(!n)return;let s=r.jwt?.claims,l=!!s&&"number"==typeof s.exp&&"number"==typeof s.iat,h=n===i;if(h&&!l)return void d(n);if(!l)return;let m=ry(n.baseline,r);if(n.baseline=m,!h&&void 0===n.entry.resolvedToken)return;let p=ry(n.entry.resolvedToken,m);if(p===n.entry.resolvedToken)return;n.entry.resolvedToken=p;let f=p.jwt?.claims;if(!f||"number"!=typeof f.exp||"number"!=typeof f.iat)return void d(n);clearTimeout(n.timeoutId),clearTimeout(n.refreshTimeoutId);let g=f.exp,b=f.iat,y=g-b,w=g-Math.floor(Date.now()/1e3);if(n.createdAt=b,n.expiresIn=y,w<=0)return void d(n);let k=setTimeout(()=>d(n),1e3*w);n.timeoutId=k,"function"==typeof k.unref&&k.unref();let v=w-15-2;if(v>0&&n.entry.onRefresh){let e=setTimeout(()=>{n.entry.onRefresh?.()},1e3*v);n.refreshTimeoutId=e,"function"==typeof e.unref&&e.unref()}let _=u;if(_&&t.broadcast)try{let t=p.getRawString();if(t&&f.sid){let a=f.sid,r=f.org_id||f.o?.id,n=ro.extractTemplate(e.tokenId,a,r),i=ro.build(a,n,r);if(e.tokenId===i){let i=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;tj.info("Broadcasting token update to other tabs",{organizationId:r,sessionId:a,tabId:c,template:n,tokenId:e.tokenId,traceId:i},"tokenCache");let s={organizationId:r,sessionId:a,template:n,tokenId:e.tokenId,tokenRaw:t,traceId:i};_.postMessage(s)}}}catch(t){tj.warn("Failed to broadcast token update to other tabs",{error:t,tabId:c,tokenId:e.tokenId},"tokenCache")}}).catch(()=>{d(i)})},{clear:()=>{o.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId),void 0!==e.refreshTimeoutId&&clearTimeout(e.refreshTimeoutId)}),o.clear()},close:()=>{u&&(u.close(),u=null)},get:h,set:e=>{d(),p(e,r_)},size:()=>o.size()});function rz(e){if(!e)return;let t=e.client||e.meta?.client;return t?rS.getOrCreateInstance().fromJSON(t):void 0}class rS extends au{static instance;pathRoot="/client";sessions=[];signUp=new nR;signIn=new nT;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return rS.instance||(rS.instance=new rS(e)),rS.instance}static clearInstance(){rS.instance=null}static isClientResource(e){return!!e&&e instanceof rS}constructor(e=null){super(),this.fromJSON(e)}get signUpAttempt(){return this.signUp}get signInAttempt(){return this.signIn}get signedInSessions(){return this.sessions.filter(e=>"active"===e.status||"pending"===e.status)}create(){return this._basePut()}fetch({fetchMaxTries:e,abortSignal:t}={}){return this._baseGet({fetchMaxTries:e,abortSignal:t})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{rj.clear(),this.id="",this.sessions=[],this.signUp=new nR(null),this.signIn=new nT(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=>(rj.clear(),e))}resetSignIn(){this.signIn=new nT(null),rs.emit("resource:error",{resource:this.signIn,error:null})}resetSignUp(){this.signUp=new nR(null),rs.emit("resource:error",{resource:this.signUp,error:null})}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return au.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 nk(e)),e.sign_up&&this.signUp instanceof nR&&this.signUp.id===e.sign_up.id?this.signUp.__internal_updateFromJSON(e.sign_up):this.signUp=new nR(e.sign_up),e.sign_in&&this.signIn instanceof nT&&this.signIn.id===e.sign_in.id?this.signIn.__internal_updateFromJSON(e.sign_in):this.signIn=new nT(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tq(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tq(e.created_at||void 0),this.updatedAt=tq(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 rI extends au{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 rA{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 rC extends au{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}function rE({delayInMs:e}={delayInMs:1e3}){let t,a=rd(),r=!1,n=()=>{t&&(a.clearTimeout(t),a.cleanup()),r=!0},i=async s=>{r=!1,await s(n),r||(t=a.setTimeout(()=>{i(s)},e))};return{run:i,stop:n}}class rP extends au{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}=rE();return{startEmailLinkFlow:async({redirectUrl:a})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=rE();return{startEnterpriseSSOLinkFlow:async({redirectUrl:a})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:a})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEnterpriseSSOLinkFlow:t}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new rL(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new r0(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 rq=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,"/")),a=t.length,r=new Uint8Array(a);for(let e=0;e<a;e++)r[e]=t.charCodeAt(e);return r.buffer}};async function rO(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new K("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 K(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new K(t.message,{code:"passkey_registration_cancelled"}):rM(t),publicKeyCredential:null}}}let rT=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 rU({publicKeyOptions:e,conditionalUI:t}){try{let a=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:rT.createAbortSignal()});if(!a)return{error:new K("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:a,error:null}}catch(e){var a;return{error:"NotAllowedError"===(a=e).name?new K(a.message,{code:"passkey_retrieval_cancelled"}):rM(a),publicKeyCredential:null}}}function rM(e){return"AbortError"===e.name?new K(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new K(e.message,{code:"passkey_invalid_rpID_or_domain",docsUrl:"https://clerk.com/docs/deployments/overview#authentication-across-subdomains"}):e}function rR(e){let t=rF(e.challenge),a=(e.allowCredentials||[]).map(e=>({...e,id:rF(e.id)}));return{...e,allowCredentials:a,challenge:t}}function rN(e){return{type:e.type,id:e.id,rawId:rD(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function rB(e){let t=e.response;return{...rN(e),response:{clientDataJSON:rD(t.clientDataJSON),authenticatorData:rD(t.authenticatorData),signature:rD(t.signature),userHandle:t.userHandle?rD(t.userHandle):null}}}let rD=rq.encode.bind(rq),rF=rq.decode.bind(rq);class rL extends au{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===au.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=tq(e.expire_at||void 0),this.error=e.error?new T(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,seats_quantity_to_add:e?.meta?.seatsQuantityToAdd,seats_quantity:e?.meta?.seatsQuantity}}),verified_at_client:this.verifiedAtClient}}}class rW extends rL{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let a,r,n;return super.fromJSON(e),e?.nonce&&(this.publicKey=(a=rF((t=JSON.parse(e.nonce)).user.id),r=rF(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:rF(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:a}})),this}}class rK{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new rH(e.email_address),this.phoneNumber=new rH(e.phone_number),this.web3Wallet=new rH(e.web3_wallet),this.externalAccount=new rL(e.external_account)):(this.emailAddress=new rH(null),this.phoneNumber=new rH(null),this.web3Wallet=new rH(null),this.externalAccount=new rL(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 rH extends rL{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 rV extends au{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?tq(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new rL(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new rG(e.enterprise_connection))),this}destroy=()=>this._baseDelete();__internal_toSnapshot(){return{object:"enterprise_account",id:this.id,provider:this.provider,protocol:this.protocol,provider_user_id:this.providerUserId,active:this.active,email_address:this.emailAddress,first_name:this.firstName,last_name:this.lastName,public_metadata:this.publicMetadata,verification:this.verification?.__internal_toSnapshot()||null,enterprise_connection:this.enterpriseConnection?.__internal_toSnapshot()||null,last_authenticated_at:this.lastAuthenticatedAt?this.lastAuthenticatedAt.getTime():null,enterprise_connection_id:this.enterpriseConnectionId}}}class rG extends au{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;allowOrganizationAccountLinking;createdAt;updatedAt;enterpriseConnectionId="";constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.domain=e.domain,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url,this.syncUserAttributes=e.sync_user_attributes,this.allowSubdomains=e.allow_subdomains,this.allowIdpInitiated=e.allow_idp_initiated,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.allowOrganizationAccountLinking=e.allow_organization_account_linking,this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at),this.enterpriseConnectionId=e.enterprise_connection_id),this}__internal_toSnapshot(){return{object:"enterprise_account_connection",id:this.id,name:this.name,domain:this.domain,active:this.active,protocol:this.protocol,provider:this.provider,logo_public_url:this.logoPublicUrl,sync_user_attributes:this.syncUserAttributes,allow_subdomains:this.allowSubdomains,allow_idp_initiated:this.allowIdpInitiated,disable_additional_identifications:this.disableAdditionalIdentifications,allow_organization_account_linking:this.allowOrganizationAccountLinking,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class rJ extends au{id;name;active;provider;logoPublicUrl=null;domains=[];organizationId=null;syncUserAttributes;disableAdditionalIdentifications;allowOrganizationAccountLinking;customAttributes=[];oauthConfig=null;samlConnection=null;createdAt=null;updatedAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){var t,a;return e?(this.id=e.id,this.name=e.name,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url??null,this.domains=e.domains??[],this.organizationId=e.organization_id??null,this.syncUserAttributes=e.sync_user_attributes,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.allowOrganizationAccountLinking=e.allow_organization_account_linking??!1,this.customAttributes=e.custom_attributes??[],this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at),this.samlConnection=e.saml_connection?{id:(t=e.saml_connection).id,name:t.name,active:t.active,idpEntityId:t.idp_entity_id,idpSsoUrl:t.idp_sso_url,idpCertificate:t.idp_certificate,idpCertificateIssuedAt:t.idp_certificate_issued_at,idpCertificateExpiresAt:t.idp_certificate_expires_at,idpMetadataUrl:t.idp_metadata_url,idpMetadata:t.idp_metadata,acsUrl:t.acs_url,spEntityId:t.sp_entity_id,spMetadataUrl:t.sp_metadata_url,allowSubdomains:t.allow_subdomains,allowIdpInitiated:t.allow_idp_initiated,forceAuthn:t.force_authn}:null,this.oauthConfig=e.oauth_config?{id:(a=e.oauth_config).id,name:a.name,clientId:a.client_id,providerKey:a.provider_key,discoveryUrl:a.discovery_url,logoPublicUrl:a.logo_public_url,requiresPkce:a.requires_pkce,createdAt:tq(a.created_at),updatedAt:tq(a.updated_at)}:null,this):this}__internal_toSnapshot(){var e,t;return{object:"enterprise_connection",id:this.id,name:this.name,active:this.active,provider:this.provider,logo_public_url:this.logoPublicUrl,domains:this.domains,organization_id:this.organizationId,sync_user_attributes:this.syncUserAttributes,disable_additional_identifications:this.disableAdditionalIdentifications,allow_organization_account_linking:this.allowOrganizationAccountLinking,custom_attributes:this.customAttributes,saml_connection:this.samlConnection?{id:(e=this.samlConnection).id,name:e.name,active:e.active,idp_entity_id:e.idpEntityId,idp_sso_url:e.idpSsoUrl,idp_certificate:e.idpCertificate,idp_certificate_issued_at:e.idpCertificateIssuedAt,idp_certificate_expires_at:e.idpCertificateExpiresAt,idp_metadata_url:e.idpMetadataUrl,idp_metadata:e.idpMetadata,acs_url:e.acsUrl,sp_entity_id:e.spEntityId,sp_metadata_url:e.spMetadataUrl,allow_subdomains:e.allowSubdomains,allow_idp_initiated:e.allowIdpInitiated,force_authn:e.forceAuthn}:void 0,oauth_config:this.oauthConfig?{id:(t=this.oauthConfig).id,name:t.name,client_id:t.clientId,provider_key:t.providerKey,discovery_url:t.discoveryUrl,logo_public_url:t.logoPublicUrl,requires_pkce:t.requiresPkce,created_at:t.createdAt?.getTime()??0,updated_at:t.updatedAt?.getTime()??0}:void 0,created_at:this.createdAt?.getTime()??0,updated_at:this.updatedAt?.getTime()??0}}}class rZ{pathRoot="/me";id;status;connectionType;parsedUserInfo=null;logs=[];saml=null;oauth=null;createdAt=null;constructor(e){this.fromJSON(e)}reload(e){ae("EnterpriseConnectionTestRun")}fromJSON(e){var t,a,r;return e&&(this.id=e.id,this.status=e.status,this.connectionType=e.connection_type,this.parsedUserInfo=(t=e.parsed_user_info??null)?{emailAddress:t.email_address,firstName:t.first_name,lastName:t.last_name,userId:t.user_id}:null,this.saml=(a=e.saml??null)?{samlRequest:a.saml_request,samlResponse:a.saml_response,relayState:a.relay_state}:null,this.oauth=(r=e.oauth??null)?{idToken:r.id_token,accessToken:r.access_token,userInfo:r.user_info}:null,this.createdAt=tq(e.created_at),this.logs=(e.logs??[]).map(e=>({level:e.level,code:e.code,shortMessage:e.short_message,message:e.message}))),this}__internal_toSnapshot(){var e,t,a;return{object:"enterprise_connection_test_run",id:this.id,status:this.status,connection_type:this.connectionType,parsed_user_info:(e=this.parsedUserInfo)?{email_address:e.emailAddress,first_name:e.firstName,last_name:e.lastName,user_id:e.userId}:null,saml:(t=this.saml)?{saml_request:t.samlRequest,saml_response:t.samlResponse,relay_state:t.relayState}:null,oauth:(a=this.oauth)?{id_token:a.idToken,access_token:a.accessToken,user_info:a.userInfo}:null,logs:this.logs.map(e=>({level:e.level,code:e.code,short_message:e.shortMessage,message:e.message})),created_at:this.createdAt?.getTime()??0}}}class r$ extends au{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 rY extends au{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};organizationCreationDefaults={enabled:!1};enabled=!1;maxAllowedMemberships=1;forceOrganizationSelection;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.actions&&(this.actions.adminDelete=this.withDefault(e.actions.admin_delete,this.actions.adminDelete)),e.domains&&(this.domains.enabled=this.withDefault(e.domains.enabled,this.domains.enabled),this.domains.enrollmentModes=this.withDefault(e.domains.enrollment_modes,this.domains.enrollmentModes),this.domains.defaultRole=this.withDefault(e.domains.default_role,this.domains.defaultRole)),e.slug&&(this.slug.disabled=this.withDefault(e.slug.disabled,this.slug.disabled)),e.organization_creation_defaults&&(this.organizationCreationDefaults.enabled=this.withDefault(e.organization_creation_defaults.enabled,this.organizationCreationDefaults.enabled)),this.enabled=this.withDefault(e.enabled,this.enabled),this.maxAllowedMemberships=this.withDefault(e.max_allowed_memberships,this.maxAllowedMemberships),this.forceOrganizationSelection=this.withDefault(e.force_organization_selection,this.forceOrganizationSelection)),this}__internal_toSnapshot(){return{actions:{admin_delete:this.actions.adminDelete},domains:{enabled:this.domains.enabled,enrollment_modes:this.domains.enrollmentModes,default_role:this.domains.defaultRole},enabled:this.enabled,max_allowed_memberships:this.maxAllowedMemberships}}}class rQ extends au{static instance;authConfig=new ah;displayConfig=new rC;maintenanceMode=!1;clientDebugMode=!1;partitionedCookies=!1;pathRoot="/environment";userSettings=new n0;organizationSettings=new rY;commerceSettings=new rI;apiKeysSettings=new r$;protectConfig=new nl;static getInstance(){return rQ.instance||(rQ.instance=new rQ),rQ.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new ah(e.auth_config),this.displayConfig=new rC(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.partitionedCookies=this.withDefault(e.partitioned_cookies,this.partitionedCookies),this.organizationSettings=new rY(e.organization_settings),this.userSettings=new n0(e.user_settings),this.commerceSettings=new rI(e.commerce_settings),this.apiKeysSettings=new r$(e.api_keys_settings),this.protectConfig=new nl(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(rs.emit(rn,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,partitioned_cookies:this.partitionedCookies,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class rX extends au{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:a}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:a}})};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 rL(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 r1 extends au{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 r0 extends au{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 r2 extends au{id;name=null;publicUrl=null;static async create(e,t={}){let a,r=t;return"string"==typeof t.file?(r=t.file,a=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(r=new FormData).append("file",t.file),new r2((await au._fetch({path:e,method:"POST",body:r,headers:a}))?.response)}static async delete(e){return new r2((await au._fetch({path:e,method:"DELETE"}))?.response)}constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.publicUrl=e.public_url),this}}function r9(e,t={}){let a={};r3(a,"provider",e.provider),r3(a,"name",e.name);let r=e.domains;return r&&r.length>0&&(a.domains=r),t.omitOrganizationId||r3(a,"organization_id",e.organizationId),r3(a,"active",e.active),r3(a,"sync_user_attributes",e.syncUserAttributes),r3(a,"disable_additional_identifications",e.disableAdditionalIdentifications),r3(a,"custom_attributes",e.customAttributes),e.saml&&(r3(a,"saml_idp_entity_id",e.saml.idpEntityId),r3(a,"saml_idp_sso_url",e.saml.idpSsoUrl),r3(a,"saml_idp_certificate",e.saml.idpCertificate),r3(a,"saml_idp_metadata_url",e.saml.idpMetadataUrl),r3(a,"saml_idp_metadata",e.saml.idpMetadata),r3(a,"saml_attribute_mapping",e.saml.attributeMapping),r3(a,"saml_allow_subdomains",e.saml.allowSubdomains),r3(a,"saml_allow_idp_initiated",e.saml.allowIdpInitiated),r3(a,"saml_force_authn",e.saml.forceAuthn)),e.oidc&&(r3(a,"oidc_client_id",e.oidc.clientId),r3(a,"oidc_client_secret",e.oidc.clientSecret),r3(a,"oidc_discovery_url",e.oidc.discoveryUrl),r3(a,"oidc_auth_url",e.oidc.authUrl),r3(a,"oidc_token_url",e.oidc.tokenUrl),r3(a,"oidc_user_info_url",e.oidc.userInfoUrl),r3(a,"oidc_requires_pkce",e.oidc.requiresPkce)),a}function r3(e,t,a){void 0!==a&&(e[t]=a)}class r5 extends au{id;name;organizationId;enrollmentMode;verification;affiliationVerification;ownershipVerification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t,enrollmentMode:a}){return new r5((await au._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t,enrollment_mode:a}}))?.response)}prepareAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/prepare_affiliation_verification`,method:"POST",body:e});attemptAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/attempt_affiliation_verification`,method:"POST",body:e});updateEnrollmentMode=e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/update_enrollment_mode`,body:e});delete=()=>this._baseDelete({path:`/organizations/${this.organizationId}/domains/${this.id}`});fromJSON(e){if(e){this.id=e.id,this.name=e.name,this.organizationId=e.organization_id,this.enrollmentMode=e.enrollment_mode,this.affiliationEmailAddress=e.affiliation_email_address,this.totalPendingSuggestions=e.total_pending_suggestions,this.totalPendingInvitations=e.total_pending_invitations;let t=e.affiliation_verification??e.verification;if(t){let e={status:t.status,strategy:t.strategy,attempts:t.attempts,expiresAt:tq(t.expires_at)};this.affiliationVerification=e,this.verification=e}else this.affiliationVerification=null,this.verification=null;e.ownership_verification?this.ownershipVerification={status:e.ownership_verification.status,strategy:e.ownership_verification.strategy,attempts:e.ownership_verification.attempts,expiresAt:e.ownership_verification.expire_at?tq(e.ownership_verification.expire_at):null,verifiedAt:e.ownership_verification.verified_at?tq(e.ownership_verification.verified_at):null,txtRecordName:e.ownership_verification.txt_record_name??null,txtRecordValue:e.ownership_verification.txt_record_value??null}:this.ownershipVerification=null}return this}}class r6 extends au{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=tq(e.created_at),this.updatedAt=tq(e.updated_at),e.public_user_data&&(this.publicUserData=new nc(e.public_user_data))),this}}class r8 extends au{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=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}}class r4 extends au{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 r8(e)),this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}}class r7 extends au{pathRoot="/organizations";id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;selfServeSSOEnabled=!1;exclusiveMembership=!1;constructor(e){super(),this.fromJSON(e)}static async create(e){return new r7((await au._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new r7((await au._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await au._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:aT(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a,has_role_set_migration:r}=e?.response;return{data:t.map(e=>new r4(e)),total_count:a,has_role_set_migration:r}});getDomains=async e=>{let{enrollmentMode:t,...a}=e||{},r=aT(a);return t&&r.set("enrollment_mode",t),await au._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:r},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new r5(e))}})};getDomain=async({domainId:e})=>new r5((await au._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getEnterpriseConnections=async e=>{let{withOrganizationAccountLinking:t}=e||{};return((await au._fetch({path:`/organizations/${this.id}/enterprise_connections`,method:"GET",...void 0!==t?{search:{with_organization_account_linking:String(t)}}:{}}))?.response||[]).map(e=>new rJ(e))};createEnterpriseConnection=async e=>new rJ((await au._fetch({path:`/organizations/${this.id}/enterprise_connections`,method:"POST",body:r9(e,{omitOrganizationId:!0})}))?.response);updateEnterpriseConnection=async(e,t)=>new rJ((await au._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}`,method:"PATCH",body:r9(t,{omitOrganizationId:!0})}))?.response);deleteEnterpriseConnection=async e=>new rA((await au._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}`,method:"DELETE"}))?.response);createEnterpriseConnectionTestRun=async e=>({url:((await au._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/test_runs`,method:"POST"}))?.response).url});getEnterpriseConnectionTestRuns=async(e,t)=>{let{status:a,...r}=t||{},n=aT(r);if(a?.length)for(let e of a)n.append("status",e);let i=await au._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/test_runs`,method:"GET",search:n}),s=i?.response;return{total_count:s?.total_count??0,data:(s?.data??[]).map(e=>new rZ(e))}};getMembershipRequests=async e=>await au._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:aT(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new r6(e))}});createDomain=async(e,t)=>r5.create(this.id,{name:e,enrollmentMode:t?.enrollmentMode});prepareOwnershipVerification=async e=>this.bulkOwnershipVerification("prepare_ownership_verification",e);attemptOwnershipVerification=async e=>this.bulkOwnershipVerification("attempt_ownership_verification",e);bulkOwnershipVerification=async(e,t)=>{let{data:a,errors:r}=(await au._fetch({path:`/organizations/${this.id}/domains/${e}/bulk`,method:"POST",body:{organization_domain_ids:t}},{forceUpdateClient:!0}))?.response;return{data:(a??[]).map(e=>new r5(e)),errors:r??[]}};getMemberships=async e=>await au._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:aT({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new nt(e))}});getInvitations=async e=>await au._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:aT(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new ne(e))}});addMember=async({userId:e,role:t})=>await au._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new nt(e?.response));inviteMember=async e=>ne.create(this.id,e);inviteMembers=async e=>ne.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await au._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new nt(e?.response));removeMember=async e=>await au._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new nt(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,a;return null===e?await au._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new r7(e?.response)):("string"==typeof e?(t=e,a=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await au._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:a}).then(e=>new r7(e?.response)))};initializePaymentMethod=e=>a2({...e,orgId:this.id});addPaymentMethod=e=>a9({...e,orgId:this.id});getPaymentMethods=e=>a3({...e,orgId:this.id});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.slug=e.slug,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.publicMetadata=e.public_metadata||{},this.membersCount=e.members_count||0,this.pendingInvitationsCount=e.pending_invitations_count||0,this.maxAllowedMemberships=e.max_allowed_memberships||0,this.adminDeleteEnabled=e.admin_delete_enabled||!1,this.selfServeSSOEnabled=e.self_serve_sso_enabled||!1,this.exclusiveMembership=e.exclusive_membership||!1,this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization",id:this.id,name:this.name,slug:this.slug,image_url:this.imageUrl,has_image:this.hasImage,public_metadata:this.publicMetadata,members_count:this.membersCount,pending_invitations_count:this.pendingInvitationsCount,max_allowed_memberships:this.maxAllowedMemberships,admin_delete_enabled:this.adminDeleteEnabled,self_serve_sso_enabled:this.selfServeSSOEnabled,exclusive_membership:this.exclusiveMembership,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:t}=e||{},a=(await au._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(a)}}class ne extends au{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:a}){return new ne((await au._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:a}}))?.response)}static async createBulk(e,t){let{emailAddresses:a,role:r}=t;return((await au._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:a,role:r}}))?.response).map(e=>new ne(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=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}}class nt extends au{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await au._fetch({path:"/me/organization_memberships",method:"GET",search:aT({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new nt(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 r7(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new nc(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tq(e.created_at),this.updatedAt=tq(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){ae("OrganizationMembership")}}class na extends au{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await au._fetch({path:"/me/organization_suggestions",method:"GET",search:aT(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new na(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=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}}function nr(){return"u">typeof window&&w()&&"function"==typeof window.PublicKeyCredential}async function nn(){try{return nr()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function ni(){try{return"u">typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class ns extends au{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return au._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new ns(e?.response))}static async attemptVerification(e,t){let a,r=(a=t.response,{...rN(t),response:{clientDataJSON:rD(a.clientDataJSON),attestationObject:rD(a.attestationObject),transports:a.getTransports()}});return au._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new ns(e?.response))}static async registerPasskey(){let e=ns.clerk.__internal_isWebAuthnSupported||nr,t=ns.clerk.__internal_createPublicCredentials||rO,a=ns.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||ni;if(!e())throw new K("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:n}=r,i=n?.publicKey;if(i||at("create"),i.authenticatorSelection?.authenticatorAttachment==="platform"&&!await a())throw new K("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:s,error:o}=await t(i);if(!s)throw o;return this.attemptVerification(r.id,s)}update=e=>this._basePatch({body:e});delete=async()=>new rA((await au._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?tq(e.last_used_at):null,this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at),e.verification&&(this.verification=new rW(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 no extends au{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 rL(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new r0(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 nl extends au{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 nc{firstName;lastName;imageUrl;hasImage;identifier;userId;username;banned;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name||null,this.lastName=e.last_name||null,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.identifier=e.identifier||"",this.userId=e.user_id,this.username=e.username,this.banned=e.banned??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,has_image:this.hasImage,identifier:this.identifier,user_id:this.userId,username:this.username,banned:this.banned}}}let nu={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"}},nd=new Set(["first_factor","second_factor","multi_factor"]),nh=new Set(["strict_mfa","strict","moderate","lax"]),nm=new Set(["o","org","organization"]),np=new Set(["u","user"]),nf=e=>"number"==typeof e&&Number.isFinite(e)&&(-1===e||e>=0),ng=(e,t)=>{let{org:a,user:r}=nb(e),[n,i]=t.split(":"),s=void 0!==i,o=i||n;if(s&&!nm.has(n)&&!np.has(n))throw Error(`Invalid scope: ${n}`);if(s){if(nm.has(n))return a.includes(o);if(np.has(n))return r.includes(o)}return[...a,...r].includes(o)},nb=e=>{let t=[],a=[];if(!e)return{org:t,user:a};let r=e.split(",");for(let e=0;e<r.length;e++){let n=r[e].trim(),i=n.indexOf(":");if(-1===i)throw Error(`Invalid claim element (missing colon): ${n}`);let s=n.slice(0,i),o=n.slice(i+1);"o"===s?t.push(o):"u"===s?a.push(o):("ou"===s||"uo"===s)&&(t.push(o),a.push(o))}return{org:t,user:a}};class ny extends au{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new rL(null);secondFactorVerification=new rL(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new nk(e.session),this.level=e.level,this.supportedFirstFactors=eg(e.supported_first_factors),this.supportedSecondFactors=eg(e.supported_second_factors),this.firstFactorVerification=new rL(e.first_factor_verification),this.secondFactorVerification=new rL(e.second_factor_verification)),this}}let nw=e=>!1===rh()?{}:{onRefresh:e};class nk extends au{pathRoot="/client/sessions";static #em=new Set;id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;agent;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof nk}constructor(e){super(),this.fromJSON(e),this.#ep(this.lastActiveToken)}end=()=>(rj.clear(),this._basePost({action:"end"}));remove=()=>(rj.clear(),this._basePost({action:"remove"}));_touchPost=async({intent:e,skipUpdateClient:t}={skipUpdateClient:!1})=>{let a=await au._fetch({method:"POST",path:this.path("touch"),body:{active_organization_id:this.lastActiveOrganizationId,intent:e}},{skipUpdateClient:t});return this.fromJSON(a?.response||a),a};touch=async({intent:e}={})=>(await this._touchPost({intent:e,skipUpdateClient:!1}),this.lastActiveToken&&rs.emit(ra,{token:this.lastActiveToken}),this);__internal_touch=async({intent:e}={})=>rz(await this._touchPost({intent:e,skipUpdateClient:!0}));clearCache=()=>rj.clear();getToken=async e=>{try{let t=await tA(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>(!V(e)||e?.status===429)&&(v()?t<=8:t<=3)});if(!t&&!v())throw new N("Network request failed while offline. The browser appears to be disconnected.");return t}catch(e){if(!v())throw new N("Network request failed while offline. The browser appears to be disconnected.");throw e}};checkAuthorization=e=>{let t,a=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(t={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:a?.organization?.id,orgRole:a?.role,orgPermissions:a?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{let a;return!!t.userId&&(a=[((e,t)=>{let{orgId:a,orgRole:r,orgPermissions:n}=t,i=void 0!==e.role,s=void 0!==e.permission;return i||s?i&&"string"!=typeof e.role||s&&"string"!=typeof e.permission||!a||i&&("string"!=typeof r||!r||r.replace(/^(org:)*/,"org:")!==e.role.replace(/^(org:)*/,"org:"))||s&&(!Array.isArray(n)||!n.includes(e.permission.replace(/^(org:)*/,"org:")))?"fail":"pass":"skip"})(e,t),((e,t)=>{let{features:a,plans:r}=t,n=void 0!==e.feature,i=void 0!==e.plan;if(!n&&!i)return"skip";if(n&&"string"!=typeof e.feature||i&&"string"!=typeof e.plan)return"fail";if(n){if("string"!=typeof a||!a)return"fail";try{if(!ng(a,e.feature))return"fail"}catch{return"fail"}}if(i){if("string"!=typeof r||!r)return"fail";try{if(!ng(r,e.plan))return"fail"}catch{return"fail"}}return"pass"})(e,t),((e,{factorVerificationAge:t})=>{if(void 0===e.reverification)return"skip";if(!t||!Array.isArray(t)||2!==t.length||!nf(t[0])||!nf(t[1]))return"fail";let a=(e=>{let t,a;if(!e)return!1;let r="string"==typeof e&&nh.has(e),n="object"==typeof e&&(t=e.level,nd.has(t))&&"number"==typeof(a=e.afterMinutes)&&a>0;return(!!r||!!n)&&(e=>"string"==typeof e?nu[e]:e).bind(null,e)})(e.reverification);if(!a)return"fail";let{level:r,afterMinutes:n}=a(),[i,s]=t;if(-1===i&&-1===s)return"fail";let o=-1!==i&&n>i,l=-1!==s&&n>s;switch(r){case"first_factor":return o?"pass":"fail";case"second_factor":if(-1===s)return o?"pass":"fail";return l?"pass":"fail";case"multi_factor":if(-1===s)return o?"pass":"fail";if(-1===i)return"fail";return o&&l?"pass":"fail"}})(e,t)]).some(e=>"pass"===e)&&a.every(e=>"pass"===e||"skip"===e)})(e)};#ep=e=>{if(e){let t=this.#ef();rj.set({tokenId:t,tokenResolver:Promise.resolve(e),...nw(()=>this.#eg(void 0,this.lastActiveOrganizationId,t,!0))})}};#ef(e,t){let a=void 0===t?this.lastActiveOrganizationId:t;return ro.build(this.id,e,a)}startVerification=async({level:e})=>new ny((await au._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:t6("Session.prepareFirstFactorVerification",e.strategy)}return new ny((await au._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(rB(e.publicKeyCredential))}:{...e},new ny((await au._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=nk.clerk.__internal_isWebAuthnSupported||nr,a=nk.clerk.__internal_getPublicCredentials||rU;if(!t())throw new K("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?rR(JSON.parse(e)):null;r||at("get");let{publicKeyCredential:n,error:i}=await a({publicKeyOptions:r,conditionalUI:!1});if(!n)throw i;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:n})};prepareSecondFactorVerification=async e=>new ny((await au._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new ny((await au._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=tq(e.expire_at),this.abandonAt=tq(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tq(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.agent=e.actor?.type==="agent"?e.actor:null,this.createdAt=tq(e.created_at),this.updatedAt=tq(e.updated_at),this.user=new nY(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new nc(e.public_user_data)),this.lastActiveToken=e.last_active_token?new nW(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){let t;if(!this.user)return null;let{skipCache:a=!1,template:r}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId,i=this.#ef(r,n),s=a?void 0:rj.get({tokenId:i}),o=!r&&n===this.lastActiveOrganizationId;if(s){let e=s.entry.resolvedToken??await s.entry.tokenResolver;o&&e.getRawString()&&rs.emit(ra,{token:e}),t=e.getRawString()||null}else if(k())t=await this.#eb(r,n,i,o,a);else throw new q("Browser is offline, skipping token fetch",{code:"network_error"});if(null===t&&!v())throw new q("Network request failed while offline",{code:"network_error"});return t}#ey(e,t,a){let r=e?`${this.path()}/tokens/${e}`:`${this.path()}/tokens`,n=nk.clerk?.__internal_environment?.authConfig?.sessionMinter,i=e?void 0:(()=>{let e=rh();if(void 0!==e){if(e)return"focused";try{return"visible"===document.visibilityState?"visible":"hidden"}catch{return}}})(),s=e?{}:{organizationId:t??null,...i?{tabState:i}:{},...n&&this.lastActiveToken?{token:this.lastActiveToken.getRawString()}:{},...n&&a?{forceOrigin:"true"}:{}};if(n)return nW.create(r,s,a?{debug:"skip_cache"}:void 0);let o=this.lastActiveToken?.getRawString();return nW.create(r,s,a?{debug:"skip_cache"}:void 0).catch(e=>{if(R.is(e)&&o)return nW.create(r,{...s},{expired_token:o});throw e})}#ew(e,t){!t||e.getRawString()&&(rs.emit(ra,{token:e}),e.jwt&&!this.#ek(e)&&(this.lastActiveToken=e,rs.emit(ri,null)))}#ek(e){let t=this.lastActiveToken;return!!t?.jwt&&rk(t)===rk(e)&&(rv(t)||"")===(rv(e)||"")&&ry(t,e)!==e}#eb(e,t,a,r,n){tj.info("Fetching new token from API",{organizationId:t,template:e,tokenId:a},"session");let i=this.#ey(e,t,n);return rj.set({tokenId:a,tokenResolver:i,...nw(()=>this.#eg(e,t,a,r))}),i.then(e=>{let t=e.getRawString();if(!t)throw new q("Token fetch returned empty response",{code:"network_error"});return this.#ew(e,r),t})}#eg(e,t,a,r){if(nk.#em.has(a))return;nk.#em.add(a);let n=nk.clerk?.__internal_getOption?.("experimental"),i=n?.runtimeEnvironment==="headless",s=this.lastActiveToken?.jwt?.claims?.exp;i&&s&&Date.now()/1e3>s?nk.#em.delete(a):this.#ey(e,t,!1).then(n=>{n.getRawString()&&(rj.set({tokenId:a,tokenResolver:Promise.resolve(n),...nw(()=>this.#eg(e,t,a,r))}),this.#ew(n,r))}).catch(e=>{tj.warn("Background token refresh failed",{error:e,tokenId:a},"session")}).finally(()=>{nk.#em.delete(a)})}get currentTask(){let[e]=this.tasks??[];return e}}class nv extends au{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=au.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new nv(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=tq(e.expire_at),this.abandonAt=tq(e.abandon_at),this.lastActiveAt=tq(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 n_=(e,t,a)=>{let{onValidation:r=rl.t,onValidationComplexity:n=rl.t}=a||{},{show_zxcvbn:i,validatePassword:s}=t,o=e=>((e,t)=>{let{max_length:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o}=t,l=(e=>{let t;if(e.allowed_special_characters){let a=e.allowed_special_characters.replace("[","\\[");a=a.replace("]","\\]"),t=RegExp(`[${a}]`)}else t=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:a,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=a,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:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o},u=new Map;for(let e in c)c[e]&&!l[e]&&u.set(e,!0);return Object.freeze(Object.fromEntries(u))})(e,t),l=(({min_zxcvbn_strength:e,onResult:t})=>a=>r=>{let n=a(r);return(t?.(n),n.score>=e&&n.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:n}:n.score>=e?{state:"excellent",result:n}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...n.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:n}})(t),c={};return(t,a)=>{let{onValidation:u=r,onValidationComplexity:d=n}=a||{};if(!s)return;let h=o(t);d(0===Object.keys(h).length),c={...c,complexity:h},i&&e().then(e=>{let a=l(e)(t);u({...c={...c,strength:a},strength:a})}),c.complexity&&0===Object.keys(c.complexity).length&&i||u(c)}};function nx(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function nj(e,t,a,r,n){if(!e.client||!r.popup)return;let i=nx(e.frontendApi),{redirectUrl:s}=r,o=new URL(s);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",t);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${i}/popup-callback`),u=e.buildUrlWithAuth(`${i}/popup-callback?return_url=${encodeURIComponent(l)}`),d=async t=>{if(t.origin!==i)return;let a=!1;if(t.data.session){if(!e.client?.sessions.find(e=>e.id===t.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:t.data.session,redirectUrl:r.redirectUrlComplete}),a=!0}else t.data.return_url&&(e.navigate(t.data.return_url),a=!0);a&&window.removeEventListener("message",d)};window.addEventListener("message",d),await a({...r,redirectUrlComplete:c,redirectUrl:u},n)}function nz(e,{redirectCallbackUrl:t,redirectUrl:a}){let r=nx(e.frontendApi),n=new URL(t);n.searchParams.set("sign_in_force_redirect_url",a),n.searchParams.set("sign_up_force_redirect_url",a);let i=e.buildUrlWithAuth(n.toString()),s=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(i)}`),redirectUrl:s}}function nS(e,t){return new Promise((a,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===nx(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",n),a()):r())};window.addEventListener("message",n),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}let nI="oauth_callback_failed",nA=new Set(["external_account_not_found",ec]),nC={oauth_access_denied:"You did not grant access to your account."};async function nE(e){try{await e.create({})}catch{}}async function nP(e){let t,a=String(await e.transport.getRedirectUrl());if(await e.authenticateMethod({...e.params,redirectUrl:a},e=>{t=e}),!t)throw new q("OAuth transport did not receive a verification URL.",{code:"oauth_transport_missing_verification_url"});let{callbackUrl:r}=await e.transport.open(new URL(t.toString())),n=function(e){let t=new URL(e).searchParams;if("failed"!==t.get("__clerk_status"))return null;let a=t.get("__clerk_error_code")||nI;if(nA.has(a))return null;let r=nC[a]?a:nI;return{code:r,message:nC[r]||"OAuth callback failed."}}(r);if(n)throw await nE(e.resource),new q(n.message,{code:n.code});let i=new URL(r).searchParams.get("rotating_token_nonce");i?await e.resource.reload({rotatingTokenNonce:i}):await e.resource.reload(),await e.clerk.__internal_handleResourceCallback(e.resource,e.callbackParams)}async function nq(e,t){rs.emit("resource:error",{resource:e,error:null}),rs.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return rs.emit("resource:error",{resource:e,error:t}),{error:t}}finally{rs.emit("resource:fetch",{resource:e,status:"idle"})}}let nO=()=>{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:a,zxcvbn:r}=e,{dictionary:n,adjacencyGraphs:i}=t;return a.setOptions({dictionary:{...n},graphs:i}),r})}).loadZxcvbn};class nT extends au{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new rL(null);secondFactorVerification=new rL(null);identifier=null;createdSessionId=null;userData=new nQ(null);clientTrustState;protectCheck=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tj.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new nU(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{tj.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t={...e},a=tV();if(a&&(t.locale=a),this.shouldRequireCaptcha(e)&&!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new al(nT.clerk),a=await e.managedOrInvisible({action:"signin"});if(!a)throw new q("",{code:"captcha_unavailable"});t={...t,...a}}return this._basePost({path:this.pathRoot,body:t})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(tj.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:t6("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor"})};submitProtectCheck=e=>(tj.debug("SignIn.submitProtectCheck",{id:this.id}),this._basePatch({action:"protect_check",body:{proof_token:e.proofToken}}));attemptFirstFactor=e=>{let t;return tj.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(rB(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=rE();return{startEmailLinkFlow:async({emailAddressId:a,redirectUrl:r})=>{this.id||t5("SignIn");let n={strategy:"email_link",emailAddressId:a,redirectUrl:r},i="needs_second_factor"===this.status||"needs_client_trust"===this.status,s=i?"secondFactorVerification":"firstFactorVerification";return i?await this.prepareSecondFactor(n):await this.prepareFirstFactor(n),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e[s].status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(tj.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(tj.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:a,redirectUrlComplete:r,identifier:n,oidcPrompt:i,continueSignIn:s,enterpriseConnectionId:o}=e||{},l=nT.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&s||await this.create({strategy:a,identifier:n,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===a&&await this.prepareFirstFactor({strategy:a,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:i,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:u}=this.firstFactorVerification;"unverified"===c&&u?t(u):t7(c,nT.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>{let t=nT.clerk.__internal_oauthTransport;return t?nP({clerk:nT.clerk,transport:t,resource:this,authenticateMethod:this.authenticateWithRedirectOrPopup,params:e,callbackParams:e.__internal_callbackParams??{}}):this.authenticateWithRedirectOrPopup(e,nT.clerk.__internal_windowNavigate)};authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||t4("popup"),nj(nT.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:a,generateSignature:r,strategy:n="web3_metamask_signature",walletName:i}=e||{},s=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&t4("generateSignature"),"solana"!==s||i||t4("walletName"),await this.create({identifier:a});let o=this.supportedFirstFactors?.find(e=>e.strategy===n);o||t8("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||t8("SignIn");try{t=await r({identifier:a,nonce:l,walletName:i,provider:s})}catch(e){if("coinbase_wallet"===s&&4001===e.code)t=await r({identifier:a,nonce:l,provider:s,walletName:i});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await tY().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await tY().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await tY().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await tY().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let t=await tY().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:t,generateSignature:t=>tY().generateSignatureWithSolana({...t,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},a=nT.clerk.__internal_isWebAuthnSupported||nr,r=nT.clerk.__internal_getPublicCredentials||rU,n=nT.clerk.__internal_isWebAuthnAutofillSupported||nn;if(!a())throw new K("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(`${t2} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:i}=this.firstFactorVerification,s=i?rR(JSON.parse(i)):null;s||at("get");let o=!1;"autofill"===t&&(o=await n());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:s,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(nT.clerk.__internal_environment?.userSettings.passwordSettings)return n_(nO(),{...nT.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=eg(e.supported_first_factors),this.supportedSecondFactors=eg(e.supported_second_factors),this.firstFactorVerification=new rL(e.first_factor_verification),this.secondFactorVerification=new rL(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new nQ(e.user_data),this.clientTrustState=e.client_trust_state??void 0,this.protectCheck=e.protect_check?{status:e.protect_check.status,token:e.protect_check.token,sdkUrl:e.protect_check.sdk_url,expiresAt:e.protect_check.expires_at,uiHints:e.protect_check.ui_hints}:null),rs.emit("resource:update",{resource:this}),this}clientBypass(){return nT.clerk.client?.captchaBypass}shouldRequireCaptcha(e){return"signUpIfMissing"in e&&!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=nT.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&nT.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=nT.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return"strategy"in e&&!!e.strategy&&t.some(t=>t===e.strategy)}__internal_updateFromJSON(e){return this.fromJSON(e)}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:ef(this.supportedFirstFactors),supported_second_factors:ef(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(),protect_check:this.protectCheck?{status:this.protectCheck.status,token:this.protectCheck.token,sdk_url:this.protectCheck.sdkUrl,...void 0!==this.protectCheck.expiresAt&&{expires_at:this.protectCheck.expiresAt},...void 0!==this.protectCheck.uiHints&&{ui_hints:this.protectCheck.uiHints}}:null}}}class nU{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(!f())return null;const e=eQ("__clerk_status"),t=eQ("__clerk_created_session");if(!e||!t)return null;const a="verified"===e&&void 0!==nT.clerk.client&&nT.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:a}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};resetPasswordPhoneCode={sendCode:this.sendResetPasswordPhoneCode.bind(this),verifyCode:this.verifyResetPasswordPhoneCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};phoneCode={sendCode:this.sendPhoneCode.bind(this),verifyCode:this.verifyPhoneCode.bind(this)};mfa={sendPhoneCode:this.sendMFAPhoneCode.bind(this),verifyPhoneCode:this.verifyMFAPhoneCode.bind(this),sendEmailCode:this.sendMFAEmailCode.bind(this),verifyEmailCode:this.verifyMFAEmailCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#ev=!1;#e_;constructor(e){this.#e_=e}get id(){return this.#e_.id}get identifier(){return this.#e_.identifier}get createdSessionId(){return this.#e_.createdSessionId}get userData(){return this.#e_.userData}get status(){return this.#e_.status||"needs_identifier"}get supportedFirstFactors(){return this.#e_.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#e_.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#e_.firstFactorVerification.status}get existingSession(){if("failed"===this.#e_.firstFactorVerification.status&&this.#e_.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#e_.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#e_.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#e_.firstFactorVerification}get secondFactorVerification(){return this.#e_.secondFactorVerification}get protectCheck(){return this.#e_.protectCheck}async submitProtectCheck(e){return nq(this.#e_,async()=>{await this.#e_.__internal_basePatch({action:"protect_check",body:{proof_token:e.proofToken}})})}get canBeDiscarded(){return this.#ev}async sendResetPasswordEmailCode(){if(!this.#e_.id)throw Error("Cannot reset password without a sign in.");return nq(this.#e_,async()=>{let e=this.#e_.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new q("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#e_.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async sendResetPasswordPhoneCode(e={}){let{phoneNumber:t}=e;if(!this.#e_.id&&!t)throw Error("signIn.resetPasswordPhoneCode.sendCode() cannot be called without a phoneNumber if an existing signIn does not exist.");return nq(this.#e_,async()=>{t&&await this._create({identifier:t});let e=this.#e_.supportedFirstFactors?.find(e=>"reset_password_phone_code"===e.strategy);if(!e)throw new q("Reset password phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:a}=e;await this.#e_.__internal_basePost({body:{phoneNumberId:a,strategy:"reset_password_phone_code"},action:"prepare_first_factor"})})}async verifyResetPasswordPhoneCode(e){let{code:t}=e;return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"reset_password_phone_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:a=!0}=e;return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{password:t,signOutOfOtherSessions:a},action:"reset_password"})})}shouldRequireCaptcha(e){return!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=nT.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&nT.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=nT.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return!!e.strategy&&t.some(t=>t===e.strategy)}async getCaptchaToken(e={}){if(!this.shouldRequireCaptcha(e)||nT.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new al(nT.clerk),a=await t.managedOrInvisible({action:"signin"});if(!a)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:i}=a;return{captchaToken:n,captchaWidgetType:i,captchaError:r}}async _create(e){let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(e),n={...e,captchaToken:t,captchaWidgetType:a,captchaError:r,locale:tV()||void 0};await this.#e_.__internal_basePost({path:this.#e_.pathRoot,body:n})}async create(e){return nq(this.#e_,async()=>{await this._create(e)})}async password(e){if([e.identifier,e.emailAddress,e.phoneNumber].filter(Boolean).length>1)throw Error("Only one of identifier, emailAddress, or phoneNumber can be provided");return nq(this.#e_,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,a=this.#e_.identifier,r=tV();await this.#e_.__internal_basePost({path:this.#e_.pathRoot,body:{identifier:t||a,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:a}=e;if(!this.#e_.id&&a)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#e_.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return nq(this.#e_,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:a});if(!e)throw new q("Email code factor not found",{code:"factor_not_found"});await this.#e_.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:a,emailAddressId:r}=e;if(!this.#e_.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#e_.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return nq(this.#e_,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new q("Email link factor not found",{code:"factor_not_found"});let n=a;try{new URL(a)}catch{n=window.location.origin+a}await this.#e_.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return nq(this.#e_,async()=>{let{run:e,stop:t}=rE();await new Promise((a,r)=>{e(async()=>{try{let e=await this.#e_.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(t(),a(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:a,channel:r="sms"}=e;if(!this.#e_.id&&a)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#e_.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return nq(this.#e_,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:a});if(!e)throw new q("Phone code factor not found",{code:"factor_not_found"});await this.#e_.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,popup:n,oidcPrompt:i,enterpriseConnectionId:s,identifier:o}=e;return nq(this.#e_,async()=>{let e=a;try{new URL(a)}catch{e=window.location.origin+a}let l={redirectUrl:nT.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=nz(nT.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=t.redirectCallbackUrl,l.actionCompleteRedirectUrl=t.redirectUrl}let c=!!this.#e_.firstFactorVerification.externalVerificationRedirectURL,u="enterprise_sso"!==t&&c;(!this.#e_.id||u)&&await this._create({strategy:t,...l,identifier:o}),"enterprise_sso"===t&&await this.#e_.__internal_basePost({body:{...l,oidcPrompt:i,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:d,externalVerificationRedirectURL:h}=this.#e_.firstFactorVerification;"unverified"===d&&h&&(n?(await nS(nT.clerk,{popup:n,externalVerificationRedirectURL:h}),await this.#e_.reload()):nT.clerk.__internal_windowNavigate(h))})}async web3(e){let{strategy:t}=e,a=t.replace("web3_","").replace("_signature","");return nq(this.#e_,async()=>{let r,n,i;switch(a){case"metamask":r=await tY().getMetamaskIdentifier(),n=tY().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await tY().getCoinbaseWalletIdentifier(),n=tY().generateSignatureWithCoinbaseWallet;break;case"base":r=await tY().getBaseIdentifier(),n=tY().generateSignatureWithBase;break;case"okx_wallet":r=await tY().getOKXWalletIdentifier(),n=tY().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new q("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await tY().getSolanaIdentifier(e.walletName),n=t=>tY().generateSignatureWithSolana({...t,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${a}`)}await this._create({identifier:r});let s=this.#e_.supportedFirstFactors?.find(e=>e.strategy===t);if(!s)throw new q("Web3 first factor not found",{code:"factor_not_found"});await this.#e_.__internal_basePost({body:{web3WalletId:s.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new q("Web3 nonce not found",{code:"web3_nonce_not_found"});try{i=await n({identifier:r,nonce:o,walletName:e?.walletName,provider:a})}catch(e){if("coinbase_wallet"===a&&4001===e.code)i=await n({identifier:r,nonce:o,provider:a});else throw e}await this.#e_.__internal_basePost({body:{signature:i,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},a=nT.clerk.__internal_isWebAuthnSupported||nr,r=nT.clerk.__internal_getPublicCredentials||rU,n=nT.clerk.__internal_isWebAuthnAutofillSupported||nn;if(!a())throw new K("Passkeys are not supported",{code:"passkey_not_supported"});return nq(this.#e_,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new q("Passkey factor not found",{code:"factor_not_found"});await this.#e_.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,a=e?rR(JSON.parse(e)):null;if(!a)throw new q("Missing public key options",{code:"missing_public_key_options"});let i=!1;"autofill"===t&&(i=await n());let{publicKeyCredential:s,error:o}=await r({publicKeyOptions:a,conditionalUI:i});if(!s)throw new K(o.message,{code:"passkey_retrieval_failed"});await this.#e_.__internal_basePost({body:{publicKeyCredential:JSON.stringify(rB(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return nq(this.#e_,async()=>{let e=this.#e_.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new q("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#e_.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async sendMFAEmailCode(){return nq(this.#e_,async()=>{let e=this.#e_.supportedSecondFactors?.find(e=>"email_code"===e.strategy);if(!e)throw new q("Email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#e_.__internal_basePost({body:{emailAddressId:t,strategy:"email_code"},action:"prepare_second_factor"})})}async verifyMFAEmailCode(e){let{code:t}=e;return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eQ("__clerk_ticket");return this.create({strategy:"ticket",ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.#e_.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return nq(this.#e_,async()=>{nT.clerk.client&&!nT.clerk.client.sessions.some(e=>e.id===this.#e_.createdSessionId)&&await nT.clerk.client.reload(),this.#ev=!0,await nT.clerk.setActive({session:this.#e_.createdSessionId,navigate:t})})}reset(){if(!nT.clerk.client)throw Error("Cannot reset sign-in without a client.");return this.#ev=!0,nT.clerk.client.resetSignIn(),Promise.resolve({error:null})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:a}){if(!this.#e_.supportedFirstFactors)return null;if(t){let a=this.#e_.supportedFirstFactors.find(a=>a.strategy===e&&a.emailAddressId===t);if(a)return a}if(a){let t=this.#e_.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===a);if(t)return t}let r=this.#e_.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#e_.identifier);if(r)return r;let n=this.#e_.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function nM(e){let{unsafeMetadata:t}={...e},a=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:a}:{}}}class nR extends au{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new rK(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};protectCheck=null;createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tj.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new nF(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{tj.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=tV();e&&(t.locale=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new al(nR.clerk),a=await e.managedOrInvisible({action:"signup"});if(!a)throw new q("",{code:"captcha_unavailable"});t={...t,...a}}return this._basePost({path:this.pathRoot,body:nM(t)})};prepareVerification=e=>(tj.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(tj.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));submitProtectCheck=e=>(tj.debug("SignUp.submitProtectCheck",{id:this.id}),this._basePatch({action:"protect_check",body:{proof_token:e.proofToken}}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:t}=rE();return{startEmailLinkFlow:async({redirectUrl:a})=>(this.id||t5("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};preparePhoneNumberVerification=e=>this.prepareVerification(e||{strategy:"phone_code"});attemptPhoneNumberVerification=e=>this.attemptVerification({...e,strategy:"phone_code"});prepareWeb3WalletVerification=e=>this.prepareVerification({strategy:"web3_metamask_signature",...e});attemptWeb3WalletVerification=async e=>{let{signature:t,strategy:a="web3_metamask_signature"}=e;return this.attemptVerification({signature:t,strategy:a})};authenticateWithWeb3=async e=>{let t,{generateSignature:a,identifier:r,unsafeMetadata:n,strategy:i="web3_metamask_signature",legalAccepted:s,walletName:o}=e||{},l=i.replace("web3_","").replace("_signature","");"function"!=typeof a&&t4("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:n,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:i});let{message:u}=this.verifications.web3Wallet;u||t8("SignUp");try{t=await a({identifier:r,nonce:u,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)t=await a({identifier:r,nonce:u,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:i})};authenticateWithMetamask=async e=>{let t=await tY().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await tY().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await tY().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await tY().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:t,legalAccepted:a})=>{let r=await tY().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:t=>tY().generateSignatureWithSolana({...t,walletName:e}),unsafeMetadata:t,strategy:"web3_solana_signature",legalAccepted:a,walletName:e})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:a,redirectUrlComplete:r,strategy:n,continueSignUp:i=!1,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u}=e,d=nR.clerk.buildUrlWithAuth(a),h=()=>{let e={strategy:n,redirectUrl:d,actionCompleteRedirectUrl:r,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u};return i&&this.id?this.update(e):this.create(e)},{verifications:m}=await h().catch(async e=>{if(M(e)&&H(e))return await nR.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:f,externalVerificationRedirectURL:g}=p;"unverified"===f&&g?t(g):t7(f,nR.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>{let t=nR.clerk.__internal_oauthTransport;return t?nP({clerk:nR.clerk,transport:t,resource:this,authenticateMethod:this.authenticateWithRedirectOrPopup,params:e,callbackParams:e.__internal_callbackParams??{}}):this.authenticateWithRedirectOrPopup(e,nR.clerk.__internal_windowNavigate)};authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||t4("popup"),nj(nR.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(nR.clerk.__internal_environment?.userSettings.passwordSettings)return n_(nO(),{...nR.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 rK(e.verifications),this.protectCheck=e.protect_check?{status:e.protect_check.status,token:e.protect_check.token,sdkUrl:e.protect_check.sdk_url,expiresAt:e.protect_check.expires_at,uiHints:e.protect_check.ui_hints}:null,this.username=e.username,this.firstName=e.first_name,this.lastName=e.last_name,this.emailAddress=e.email_address,this.phoneNumber=e.phone_number,this.hasPassword=e.has_password,this.unsafeMetadata=e.unsafe_metadata,this.createdSessionId=e.created_session_id,this.createdUserId=e.created_user_id,this.abandonAt=e.abandon_at,this.web3wallet=e.web3_wallet,this.legalAcceptedAt=e.legal_accepted_at,this.locale=e.locale),rs.emit("resource:update",{resource:this}),this}__internal_updateFromJSON(e){return this.fromJSON(e)}__internal_toSnapshot(){return{object:"sign_up",id:this.id||"",status:this.status||null,required_fields:this.requiredFields,optional_fields:this.optionalFields,missing_fields:this.missingFields,unverified_fields:this.unverifiedFields,verifications:this.verifications.__internal_toSnapshot(),protect_check:this.protectCheck?{status:this.protectCheck.status,token:this.protectCheck.token,sdk_url:this.protectCheck.sdkUrl,...void 0!==this.protectCheck.expiresAt&&{expires_at:this.protectCheck.expiresAt},...void 0!==this.protectCheck.uiHints&&{ui_hints:this.protectCheck.uiHints}}:null,username:this.username,first_name:this.firstName,last_name:this.lastName,email_address:this.emailAddress,phone_number:this.phoneNumber,has_password:this.hasPassword,unsafe_metadata:this.unsafeMetadata,created_session_id:this.createdSessionId,created_user_id:this.createdUserId,abandon_at:this.abandonAt,web3_wallet:this.web3wallet,legal_accepted_at:this.legalAcceptedAt,locale:this.locale,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return nR.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){let t=nR.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=nR.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||nB(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}__experimental_getEnterpriseConnections=()=>au._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new nL(e)))}let nN=new Set(["email_link","email_code","phone_code"]);function nB(e){return!!e&&(nN.has(e)||e.startsWith("web3_"))}class nD{#e_;sendEmailCode;verifyEmailCode;sendEmailLink;waitForEmailLinkVerification;sendPhoneCode;verifyPhoneCode;constructor(e,t){this.#e_=e,this.sendEmailCode=t.sendEmailCode,this.verifyEmailCode=t.verifyEmailCode,this.sendEmailLink=t.sendEmailLink,this.waitForEmailLinkVerification=t.waitForEmailLinkVerification,this.sendPhoneCode=t.sendPhoneCode,this.verifyPhoneCode=t.verifyPhoneCode}get emailAddress(){return this.#e_.verifications.emailAddress}get phoneNumber(){return this.#e_.verifications.phoneNumber}get web3Wallet(){return this.#e_.verifications.web3Wallet}get externalAccount(){return this.#e_.verifications.externalAccount}get emailLinkVerification(){if(!f())return null;let e=eQ("__clerk_status"),t=eQ("__clerk_created_session");if(!e||!t)return null;let a="verified"===e&&void 0!==nR.clerk.client&&nR.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:a}}}class nF{verifications;#ev=!1;#e_;constructor(e){this.#e_=e,this.verifications=new nD(this.#e_,{sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendEmailLink:this.sendEmailLink.bind(this),waitForEmailLinkVerification:this.waitForEmailLinkVerification.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)})}get id(){return this.#e_.id}get requiredFields(){return this.#e_.requiredFields}get optionalFields(){return this.#e_.optionalFields}get missingFields(){return this.#e_.missingFields}get status(){return this.#e_.status||"missing_requirements"}get username(){return this.#e_.username}get firstName(){return this.#e_.firstName}get lastName(){return this.#e_.lastName}get emailAddress(){return this.#e_.emailAddress}get phoneNumber(){return this.#e_.phoneNumber}get web3Wallet(){return this.#e_.web3wallet}get hasPassword(){return this.#e_.hasPassword}get unsafeMetadata(){return this.#e_.unsafeMetadata}get createdSessionId(){return this.#e_.createdSessionId}get createdUserId(){return this.#e_.createdUserId}get abandonAt(){return this.#e_.abandonAt}get legalAcceptedAt(){return this.#e_.legalAcceptedAt}get locale(){return this.#e_.locale}get unverifiedFields(){return this.#e_.unverifiedFields}get protectCheck(){return this.#e_.protectCheck}get isTransferable(){return"transferable"===this.#e_.verifications.externalAccount.status&&this.#e_.verifications.externalAccount.error?.code===ec}get existingSession(){if(("failed"===this.#e_.verifications.externalAccount.status||"unverified"===this.#e_.verifications.externalAccount.status)&&this.#e_.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#e_.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#e_.verifications.externalAccount.error?.meta?.sessionId}}get canBeDiscarded(){return this.#ev}shouldBypassCaptchaForAttempt(e){let t=nR.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=nR.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||nB(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}async getCaptchaToken(e={}){if(nR.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new al(nR.clerk),a=await t.managedOrInvisible({action:"signup"});if(!a)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:i}=a;return{captchaToken:n,captchaWidgetType:i,captchaError:r}}async _create(e){let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(e),n={transfer:e.transfer,captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?nM(e.unsafeMetadata):void 0,locale:e.locale??tV()};await this.#e_.__internal_basePost({path:this.#e_.pathRoot,body:n})}async create(e){return nq(this.#e_,async()=>{await this._create(e)})}async update(e){return nq(this.#e_,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?nM(e.unsafeMetadata):void 0};await this.#e_.__internal_basePatch({body:t})})}async password(e){return nq(this.#e_,async()=>{let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?nM(e.unsafeMetadata):void 0};this.#e_.id?await this.#e_.__internal_basePatch({body:n}):(n.locale=e.locale??tV(),await this.#e_.__internal_basePost({path:this.#e_.pathRoot,body:n}))})}async sendEmailCode(){return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{channel:t="sms"}=e||{};return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return nq(this.#e_,async()=>{await this.#e_.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sendEmailLink(e){let{verificationUrl:t}=e;return nq(this.#e_,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}await this.#e_.__internal_basePost({body:{strategy:"email_link",redirectUrl:e},action:"prepare_verification"})})}async waitForEmailLinkVerification(){return nq(this.#e_,async()=>{let{run:e,stop:t}=rE();await new Promise((a,r)=>{e(()=>this.#e_.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,popup:c,locale:u}=e;return nq(this.#e_,async()=>{let{captchaToken:e,captchaWidgetType:d,captchaError:h}=await this.getCaptchaToken({strategy:t}),m=a;try{new URL(a)}catch{m=window.location.origin+a}let p={redirectUrl:nR.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:m};if(c){let e=nz(nR.clerk,{redirectCallbackUrl:p.redirectUrl,redirectUrl:m});p.redirectUrl=e.redirectCallbackUrl,p.actionCompleteRedirectUrl=e.redirectUrl}let f=()=>{let a={strategy:t,...p,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:h,locale:u};return this.#e_.id?this.#e_.__internal_basePatch({body:a}):(a.locale=u??tV(),this.#e_.__internal_basePost({path:this.#e_.pathRoot,body:a}))};await f().catch(async e=>{if(M(e)&&H(e))return await nR.clerk.__internal_environment.reload(),f();throw e});let{status:g,externalVerificationRedirectURL:b}=this.#e_.verifications.externalAccount;"unverified"===g&&b&&(c?(await nS(nR.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.#e_.reload()):nR.clerk.__internal_windowNavigate(b))})}async web3(e){let{strategy:t,unsafeMetadata:a,legalAccepted:r,firstName:n,lastName:i,locale:s}=e,o=t.replace("web3_","").replace("_signature","");return nq(this.#e_,async()=>{let e,l,c;switch(o){case"metamask":e=await tY().getMetamaskIdentifier(),l=tY().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tY().getCoinbaseWalletIdentifier(),l=tY().generateSignatureWithCoinbaseWallet;break;case"base":e=await tY().getBaseIdentifier(),l=tY().generateSignatureWithBase;break;case"okx_wallet":e=await tY().getOKXWalletIdentifier(),l=tY().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${o}`)}let u=e||this.#e_.web3wallet;await this._create({web3Wallet:u,unsafeMetadata:a,legalAccepted:r,firstName:n,lastName:i,locale:s}),await this.#e_.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:d}=this.#e_.verifications.web3Wallet;d||t8("SignUp");try{c=await l({identifier:e,nonce:d})}catch(t){if("coinbase_wallet"===o&&4001===t.code)c=await l({identifier:e,nonce:d});else throw t}await this.#e_.__internal_basePost({body:{signature:c,strategy:t},action:"attempt_verification"})})}async submitProtectCheck(e){return nq(this.#e_,async()=>{await this.#e_.__internal_basePatch({action:"protect_check",body:{proof_token:e.proofToken}})})}async ticket(e){let t=e?.ticket??eQ("__clerk_ticket");return this.create({...e,strategy:"ticket",ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return nq(this.#e_,async()=>{if(!this.#e_.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#ev=!0,await nR.clerk.setActive({session:this.#e_.createdSessionId,navigate:t})})}reset(){if(!nR.clerk.client)throw Error("Cannot reset sign-up without a client.");return this.#ev=!0,nR.clerk.client.resetSignUp(),Promise.resolve({error:null})}}class nL extends au{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class nW extends au{pathRoot="tokens";jwt;static async create(e,t={},a={}){return new nW(await au._fetch({method:"POST",path:e,body:t,search:a}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=tH(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=tH(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class nK extends au{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=tq(e.updated_at),this.createdAt=tq(e.created_at)),this}}var nH=Object.prototype.hasOwnProperty;function nV(e,t,a){for(a of e.keys())if(nG(a,t))return a}function nG(e,t){var a,r,n;if(e===t)return!0;if(e&&t&&(a=e.constructor)===t.constructor){if(a===Date)return e.getTime()===t.getTime();if(a===RegExp)return e.toString()===t.toString();if(a===Array){if((r=e.length)===t.length)for(;r--&&nG(e[r],t[r]););return -1===r}if(a===Set){if(e.size!==t.size)return!1;for(r of e)if((n=r)&&"object"==typeof n&&!(n=nV(t,n))||!t.has(n))return!1;return!0}if(a===Map){if(e.size!==t.size)return!1;for(r of e)if((n=r[0])&&"object"==typeof n&&!(n=nV(t,n))||!nG(r[1],t.get(n)))return!1;return!0}if(a===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(a===DataView){if((r=e.byteLength)===t.byteLength)for(;r--&&e.getInt8(r)===t.getInt8(r););return -1===r}if(ArrayBuffer.isView(e)){if((r=e.byteLength)===t.byteLength)for(;r--&&e[r]===t[r];);return -1===r}if(!a||"object"==typeof e){for(a in r=0,e)if(nH.call(e,a)&&++r&&!nH.call(t,a)||!(a in t)||!nG(e[a],t[a]))return!1;return Object.keys(t).length===r}}return e!=e&&t!=t}function nJ(e){if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}class nZ extends au{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=tq(e.updated_at),this.createdAt=tq(e.created_at)),this}}class n$ extends au{advisory=null;form={name:"",slug:"",logo:null,blurHash:null};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.advisory&&(this.advisory=this.withDefault(e.advisory,this.advisory??null)),e.form&&(this.form.name=this.withDefault(e.form.name,this.form.name),this.form.slug=this.withDefault(e.form.slug,this.form.slug),this.form.logo=this.withDefault(e.form.logo,this.form.logo),this.form.blurHash=this.withDefault(e.form.blur_hash,this.form.blurHash))),this}static async retrieve(){return await au._fetch({path:"/me/organization_creation_defaults",method:"GET"}).then(e=>new n$(e?.response))}__internal_toSnapshot(){return{advisory:this.advisory?{code:this.advisory.code,meta:this.advisory.meta,severity:this.advisory.severity}:null,form:{name:this.form.name,slug:this.form.slug,logo:this.form.logo,blur_hash:this.form.blurHash}}}}class nY extends au{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 nY}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case rP:return this.primaryEmailAddressId===e.id;case no:return this.primaryPhoneNumberId===e.id;case n2:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new rP({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>ns.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new no({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new n2({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:a,additionalScopes:r,enterpriseConnectionId:n}=e||{};return new rX((await au._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:a,additional_scope:r,enterprise_connection_id:n}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new nK((await au._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new nK((await au._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new rA((await au._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new nZ((await au._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=async e=>{var t;let{unsafeMetadata:a,...r}=e,n=void 0!==a,i=Object.keys(r).length>0;if(!n)return this._basePatch({body:nM(e)});((t=au.clerk.publishableKey).startsWith("test_")||t.startsWith("pk_test_"))&&console.warn('Clerk - DEPRECATION WARNING: "user.update({ unsafeMetadata })" is deprecated and will be removed in the next major release.\nUse user.updateMetadata({ unsafeMetadata }) for partial updates (deep merge) instead.'),i?await this._basePatch({body:nM(r)}):await this.reload();let s=function e(t,a){if(null===a)return null;if(!nJ(t)||!nJ(a))return a;let r={};for(let n of Object.keys(a)){let i=t[n],s=a[n];if(!(n in t)){r[n]=s;continue}if(nJ(i)&&nJ(s)){let t=e(i,s);if(nJ(t)&&0===Object.keys(t).length)continue;r[n]=t}else nG(i,s)||(r[n]=s)}for(let e of Object.keys(t))e in a||(r[e]=null);return r}(this.unsafeMetadata,a);return null!==s&&"object"==typeof s&&0===Object.keys(s).length?this:this.updateMetadata({unsafeMetadata:s})};updateMetadata=e=>this._basePatch({path:`${this.path()}/metadata`,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=>(rs.emit(rr,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await nv.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?r2.delete(`${this.path()}/profile_image`):r2.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>nX.retrieve(e);getOrganizationSuggestions=e=>na.retrieve(e);getOrganizationMemberships=e=>nt.retrieve(e);getOrganizationCreationDefaults=()=>n$.retrieve();leaveOrganization=async e=>new rA((await au._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);getEnterpriseConnections=async e=>{let{withOrganizationAccountLinking:t}=e||{};return((await au._fetch({path:"/me/enterprise_connections",method:"GET",...void 0!==t?{search:{with_organization_account_linking:String(t)}}:{}}))?.response||[]).map(e=>new rJ(e))};initializePaymentMethod=e=>a2(e);addPaymentMethod=e=>a9(e);getPaymentMethods=e=>a3(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:a})=>a||[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 rP(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 no(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 n2(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 rX(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new ns(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new nt(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new rV(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=tq(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tq(e.legal_accepted_at)),this.updatedAt=tq(e.updated_at||void 0),this.createdAt=tq(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 nQ{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 nX extends au{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await au._fetch({path:"/me/organization_invitations",method:"GET",search:aT(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new nX(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=tq(e.created_at),this.updatedAt=tq(e.updated_at)),this}}let n1={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 n0 extends au{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:{...n1,name:"phone_number"},username:{...n1,name:"username"},web3_wallet:{...n1,name:"web3_wallet"},first_name:{...n1,name:"first_name"},last_name:{...n1,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:{...n1,name:"authenticator_app"},backup_code:{...n1,name:"backup_code"},passkey:{...n1,name:"passkey"}};enterpriseSSO={enabled:!1,self_serve_sso:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0,mfa:{required:!1}};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!this.attributes?.password?.enabled}get hasValidAuthFactor(){return!!(this.attributes?.email_address?.enabled||this.attributes?.phone_number?.enabled||this.attributes.password?.required&&this.attributes.username?.required)}fromJSON(e){return e&&(this.attributes=this.withDefault(e.attributes?Object.fromEntries(Object.entries(e.attributes).map(e=>[e[0],{...e[1],name:e[0]}])):null,this.attributes),this.actions=this.withDefault(e.actions,this.actions),this.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 n2 extends au{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 rL(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class n9 extends au{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tq(e.updated_at),this.createdAt=tq(e.created_at),rs.emit("resource:update",{resource:this})),this}async join(e){return nq(this,async()=>{await n9.join(e)})}static async join(e){return new n9(await au._fetch({path:"/waitlist",method:"POST",body:e}))}}function n3(e,t){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(a=t,r=e,a.organizationMemberships.length!==r.organizationMemberships.length||a.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function n5(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(rS.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(nk.isSessionResource(e)){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==t.lastActiveToken?.jwt?.claims?.__raw||function(e,t){if(e.lastActiveOrganizationId!==t.lastActiveOrganizationId)return!0;let a=e.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId),r=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return a?.permissions?.length!==r?.permissions?.length}(e,t)||(a=e,r=t,!!a.user!=!!r.user||!!a.user&&!!r.user&&n3(a.user,r.user))}if(nY.isUserResource(e))return n3(e,t)}catch{}return!0}(e,t)?e:t}let n6="__clerk_db_jwt";function n8(e,t){let a=new URL(e),r=a.searchParams.get(n6);a.searchParams.delete(n6);let n=r||t;return n&&a.searchParams.set(n6,n),a}let n4=e=>{let t=new URL(e);return t.searchParams.delete(n6),t},n7=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 ie(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)"__proto__"!==r&&(e[r]=a[r])}return e}var it=function e(t,a){function r(e,r,n){if("u">typeof document){"number"==typeof(n=ie({},a,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var s in n)n[s]&&(i+="; "+s,!0!==n[s]&&(i+="="+n[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var a=document.cookie?document.cookie.split("; "):[],r={},n=0;n<a.length;n++){var i=a[n].split("="),s=i.slice(1).join("=");try{var o=decodeURIComponent(i[0]);if(o in r||(r[o]=t.read(s,o)),e===o)break}catch{}}return e?r[e]:r}},remove:function(e,t){r(e,"",ie({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,ie({},this.attributes,t))},withConverter:function(t){return e(ie({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(a)},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 ia(e){return{get:()=>it.get(e),set(t,a={}){it.set(e,t,a)},remove(t){it.remove(e,t)}}}let ir=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function ii(e,t){let a=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return a.setFullYear(a.getFullYear()+t),a}let is=ia("__clerk_test_etld"),io=[".lovable.app",".lovableproject.com",".webcontainer-api.io",".vusercontent.net",".v0.dev",".v0.app",".lp.dev",".replit.dev"];function il(){try{return io.some(e=>window.location.hostname.endsWith(e))}catch{return!1}}let ic="__client_uat",iu="__session",id=e=>{let t=e.usePartitionedCookies(),a=t||tJ()||il()?"None":"Lax",r=ir(a);return{sameSite:a,secure:r,partitioned:t&&r}};async function ih(e){let t;try{t=await eA(e)}catch(o){var a;a=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,eO.has(a)||(console.log(a),eO.add(a));let{default:r}=await Promise.resolve().then(n.t.bind(n,3515,23)),{default:i}=await Promise.resolve().then(n.t.bind(n,5662,23)),s=r(e);t=i.stringify(s).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let im=e=>{let t=e.usePartitionedCookies(),a=t||tJ()||il()?"None":"Lax",r=ir(a);return{sameSite:a,secure:r,partitioned:t&&r}},ip={sameSite:"None",secure:!0,partitioned:!0};class ig{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,a,r){let n=await ih(e.publishableKey),i=new ig(e,t,n,a,r);return await i.setup(),i}constructor(e,t,r,n,i){this.clerk=e,this.instanceType=n,this.clerkEventBus=i,rs.on(ra,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),rs.on(rr,()=>this.handleSignOut()),rs.on(rn,()=>{this.devBrowser.refreshCookies()}),this.refreshTokenOnFocus(),this.startPollingForToken();const s={usePartitionedCookies:()=>rQ.getInstance().partitionedCookies};this.clientUat=((e,t)=>{let r=ia(ic),n=ia(eC(ic,e));return{set:e=>{let i=ii(Date.now(),1),s=t.usePartitionedCookies(),o=s||tJ()||il()?"None":"Strict",l=ir(o),c=s&&l,u=function(e=window.location.hostname,t=is,r){if(a)return a;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 i=n.slice(e).join(".");if(t.set("1",{...r,domain:i}),"1"===t.get())return t.remove({...r,domain:i}),a=i,i;t.remove({...r,domain:i})}return a=e,e}(void 0,void 0,{sameSite:o,secure:l}),d="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(d=Math.floor(e.updatedAt.getTime()/1e3).toString()),n.remove(),r.remove(),n.set(d,{domain:u,expires:i,partitioned:c,sameSite:o,secure:l}),r.set(d,{domain:u,expires:i,partitioned:c,sameSite:o,secure:l})},get:()=>parseInt(n.get()||r.get()||"0",10)}})(r,s),this.sessionCookie=((e,t)=>{let a=ia(iu),r=ia(eC(iu,e));return{set:e=>{let n=ii(Date.now(),1),{sameSite:i,secure:s,partitioned:o}=id(t);o&&(a.remove(),r.remove()),a.set(e,{expires:n,sameSite:i,secure:s,partitioned:o}),r.set(e,{expires:n,sameSite:i,secure:s,partitioned:o})},remove:()=>{let e=id(t);a.remove(e),r.remove(e),e.partitioned&&(a.remove(),r.remove())},get:()=>r.get()||a.get()}})(r,s),this.activeCookie=(()=>{let e=ia("clerk_active_context"),t={secure:ir("None")};return{set:a=>{e.set(a,t)},get:()=>e.get(),remove:()=>e.remove(t)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:a,cookieOptions:r}){let n,i,s,o,l=(i=ia(n6),s=ia(eC(n6,e)),o=()=>{let e=im(r);for(let t of[s,i])t.remove(e),t.remove(),t.remove(ip)},{get:()=>s.get()||i.get(),set:e=>{let t=ii(Date.now(),1),{sameSite:a,secure:n,partitioned:l}=im(r);o(),s.set(e,{expires:t,sameSite:a,secure:n,partitioned:l}),i.set(e,{expires:t,sameSite:a,secure:n,partitioned:l})},remove:()=>o()});function c(){return n||l.get()}function u(e){n=e,l.set(e)}function d(){n=void 0,l.remove()}return{clear:function(){d()},setup:async function e(){var e;let r,i;if(!eB(t))return;a.onBeforeRequest(e=>{let t=c();t&&e?.url&&(e.url=n8(e.url,t))}),a.onAfterResponse((e,t)=>{let a=t?.headers?.get("Clerk-Db-Jwt");a&&u(a)});let s=(r=(e=new URL(window.location.href)).searchParams.get("__clerk_db_jwt")||"",(i=n4(n7(e))).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",i),r);if(s)return void u(s);let o=l.get();if(o){n=o;return}let d=a.buildUrl({path:"/dev_browser"}),h=await fetch(d.toString(),{method:"POST"});if(!h.ok){let e=function(e=[]){return e.length>0?e.map(e=>new T(e)):[]}((await h.json()).errors);e[0]?t9(e[0].longMessage):t9()}let m=await h.json();u(m?.id)},getDevBrowser:c,setDevBrowser:u,removeDevBrowser:d,refreshCookies:function(){let e=c();e&&u(e)}}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:r,cookieOptions:s})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let t=this.devBrowser.getDevBrowser();if(!t)throw Error(`${t2} Missing dev browser. Please contact support.`);return n8(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new rf,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){let e=()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})};window.addEventListener("focus",e),"u">typeof document&&document.addEventListener("visibilitychange",e)}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if((document.hasFocus()||this.inVisibleCrossOriginIframe()||this.isCurrentContextActive())&&!(e&&this.#ex(e)))return e||v()||tj.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}#ex(e){let t=this.#ej(e);if(!t||null==rw(t))return!1;let a=this.#ej(this.sessionCookie.get());if(!a||null==rw(a))return!1;let r=a.jwt?.claims?.exp;return!("number"!=typeof r||r<=Math.floor(Date.now()/1e3))&&rk(a)===rk(t)&&(rv(a)||"")===(rv(t)||"")&&ry(a,t)===a}#ej(e){if(!e)return null;try{let t=new nW({id:"__session",jwt:e,object:"token"});return t.jwt?t:null}catch{return null}}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(M(e)||O(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(J(e))return void this.clerk.handleUnauthenticated().catch(tb.lQ);this.clerkEventBus.emit(S,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",t=this.clerk.organization?.id||"",a=`${e}:${t}`;":"!==a?this.activeCookie.set(a):this.activeCookie.remove()}inVisibleCrossOriginIframe(){return tJ()&&"visible"===document.visibilityState}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[t,a]=e.split(":"),r=this.clerk.session?.id||"",n=this.clerk.organization?.id||"";return t===r&&a===n}getSessionCookie(){return this.sessionCookie.get()}}class ib{clerk;captchaChallenge;timers;constructor(e,t=new al(e),a=rd()){this.clerk=e,this.captchaChallenge=t,this.timers=a}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 iy=["/client","/waitlist"];function iw(e){let t;try{t=new nW({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(rS.clearInstance(),!t?.jwt)return rS.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:a,userId:r,orgId:n,orgRole:i,orgPermissions:s,orgSlug:o,factorVerificationAge:l}=(e=>{let t,a,r,n,i=e.fva??null,s=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,r=e.o?.slg,e.o?.rol&&(a=`org:${e.o?.rol}`);let{org:i}=nb(e.fea),{permissions:s,featurePermissionMap:o}=(({per:e,fpm:t})=>{if(!e||!t)return{permissions:[],featurePermissionMap:[]};let a=e.split(",").map(e=>e.trim());return{permissions:a,featurePermissionMap:t.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(a.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});n=function({features:e,permissions:t,featurePermissionMap:a}){if(!e||!t||!a)return[];let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(n>=a.length)continue;let s=a[n];if(s)for(let e=0;e<s.length;e++)1===s[e]&&r.push(`org:${i}:${t[e]}`)}return r}({features:i,featurePermissionMap:o,permissions:s})}}else t=e.org_id,a=e.org_role,r=e.org_slug,n=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:s,actor:e.act,userId:e.sub,orgId:t,orgRole:a,orgSlug:r,orgPermissions:n,factorVerificationAge:i}})(t.jwt.claims),c={object:"client",last_active_session_id:a,id:"client_init",sessions:[{object:"session",id:a,status:"active",last_active_organization_id:n||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:r},user:{object:"user",id:r,updated_at:1,organization_memberships:n&&o&&i?[{object:"organization_membership",id:n,role:i,permissions:s||[],organization:{object:"organization",id:n,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return rS.getOrCreateInstance(c)}class ik{static #eh="/api_keys";async #ez(){let e=await au.clerk.session?.getToken();if(!e)throw new q("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 au._fetch({...await this.#ez(),method:"GET",path:ik.#eh,search:aT({...e,subject:e?.subject??au.clerk.organization?.id??au.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new ad(e))}})}async create(e){return new ad(await au._fetch({...await this.#ez(),path:ik.#eh,method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??au.clerk.organization?.id??au.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new ad(await au._fetch({...await this.#ez(),method:"POST",path:`${ik.#eh}/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let iv=new Map;class i_{async getConsentInfo(e){let{oauthClientId:t,scope:a,redirectUri:r}=e,n={...void 0!==a&&{scope:a},...void 0!==r&&{redirect_uri:r}},i=await au._fetch({method:"GET",path:`/me/oauth/consent/${encodeURIComponent(t)}`,search:Object.keys(n).length>0?n:void 0},{skipUpdateClient:!0});if(!i)throw new q("Network request failed while offline",{code:"network_error"});let s=i.response??i;return{oauthApplicationName:s.oauth_application_name,oauthApplicationLogoUrl:s.oauth_application_logo_url,oauthApplicationUrl:s.oauth_application_url,clientId:s.client_id,state:s.state,redirectDomain:s.redirect_domain,scopes:s.scopes?.map(e=>({scope:e.scope,description:e.description,requiresConsent:e.requires_consent}))??[]}}buildConsentActionUrl({clientId:e}){let t=au.fapiClient.buildUrl({path:`/me/oauth/consent/${encodeURIComponent(e)}`,sessionId:au.clerk.session?.id});return au.clerk.buildUrlWithAuth(t.toString())}}class ix{#el=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#el){if(f())for(let e of(this.#el=!0,t.loaders))try{this.applyLoader(e)}catch(e){eT(`[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 eT(`[protect] loader rollout value is invalid: ${t}`);if(0===t||Math.random()>t)return}let t=e.type||"script",a=e.target||"body",r=document.createElement(t);if(e.attributes)for(let[t,a]of Object.entries(e.attributes))switch(typeof a){case"string":case"number":case"boolean":r.setAttribute(t,String(a));break;default:eT(`[protect] loader attribute is invalid type: ${t}=${a}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),a){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(a?.startsWith("#")){let e=document.getElementById(a.substring(1));if(!e)return void eT(`[protect] loader target element not found: ${a}`);e.appendChild(r);return}eT(`[protect] loader target is invalid: ${a}`)}}}class ij{signInResourceSignal=aM;signInErrorSignal=aR;signInFetchSignal=aN;signInSignal=aB;signUpResourceSignal=aD;signUpErrorSignal=aF;signUpFetchSignal=aL;signUpSignal=aW;waitlistResourceSignal=aK;waitlistErrorSignal=aH;waitlistFetchSignal=aV;waitlistSignal=aG;_waitlistInstance;__internal_effect=aI;__internal_computed=aS;constructor(){rs.on("resource:update",this.onResourceUpdated),rs.on("resource:error",this.onResourceError),rs.on("resource:fetch",this.onResourceFetch),this._waitlistInstance=new n9(null),this.waitlistResourceSignal({resource:this._waitlistInstance})}get __internal_waitlist(){return this._waitlistInstance}onResourceError=e=>{e.resource instanceof nT&&this.signInErrorSignal({error:e.error}),e.resource instanceof nR&&this.signUpErrorSignal({error:e.error}),e.resource instanceof n9&&this.waitlistErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof nT){if(iz(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof nR){if(iz(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}e.resource instanceof n9&&(this._waitlistInstance=e.resource,this.waitlistResourceSignal({resource:e.resource}))};onResourceFetch=e=>{e.resource instanceof nT&&this.signInFetchSignal({status:e.status}),e.resource instanceof nR&&this.signUpFetchSignal({status:e.status}),e.resource instanceof n9&&this.waitlistFetchSignal({status:e.status})}}function iz(e,t){return!t?.id&&e&&e.__internal_future?.canBeDiscarded===!1}let iS="cannot_render_billing_disabled",iI="cannot_render_user_missing",iA="cannot_render_organizations_disabled",iC="cannot_render_organization_missing",iE="cannot_render_single_session_enabled",iP={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 iq{static version="6.25.9";static sdkMetadata={name:"@clerk/clerk-js",version:"6.25.9"};static _billing;static _apiKeys;static _oauthApplication;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new ij;internal_last_error=null;environment;#eS;#eI="";#eA;#eC;#eE;#eP;#eq;#eO=null;#eT;#eU;#eM;#eR="loading";#eN=[];#eB=[];#eD={};#eF=null;#eL=null;#eW=0;#eK=z();#eH=new tE;get __internal_moduleManager(){return this.#eH}get __internal_queryClient(){return this.#eS||Promise.resolve().then(n.bind(n,6125)).then(e=>e.QueryClient).then(e=>{this.#eS||(this.#eS=new e,this.#eK.emit("queryClientStatus","ready"))}),this.#eS?{__tag:"clerk-rq-client",client:this.#eS}:void 0}get __internal_hasOAuthTransport(){return null!==this.#eF}get __internal_oauthTransport(){return this.#eF}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eI}get version(){return iq.version}get uiVersion(){let e="u">typeof window?window.__internal_ClerkUICtor:void 0,t=this.#eD.ui?.ClerkUI;return e?.version??(t instanceof Promise?void 0:t?.version)}set sdkMetadata(e){iq.sdkMetadata=e}get sdkMetadata(){return iq.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eR}get isSatellite(){return!!tG()&&(0,tb.VK)(this.#eD.isSatellite,new URL(window.location.href),!1)}get domain(){if(tG()){let e=eP((0,tb.VK)(this.#eA,new URL(window.location.href)));if("production"===this.#eM){let t;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))t=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;t=/^(clerk\.)*/gi}return`clerk.${e.replace(t,"")}`}return e}return"function"==typeof this.#eA?(eT(e6.domainAsFunctionNotSupported),""):eP(this.#eA||"")}get proxyUrl(){if(tG()){var e;let t=(0,tb.VK)(this.#eC,new URL(window.location.href));!t||te(t)||tt(t)||tW.throwInvalidProxyUrl({url:t});let a=t?!tt(t)||"u"<typeof window||!window.location?.origin?t:new URL(t,window.location.origin).toString():"";if(a)return a;if(!this.#eA&&"production"===this.#eM&&(e=window.location.hostname,ta.some(t=>e?.endsWith(t))))return`${window.location.origin}/__clerk`}return"function"==typeof this.#eC?(eT(e6.proxyUrlAsFunctionNotSupported),""):this.#eC||""}get frontendApi(){let e=eS(this.publishableKey);return e?e.frontendApi:tW.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#eM}get isStandardBrowser(){return this.#eD.standardBrowser||!1}get billing(){return iq._billing||(iq._billing=new aU),iq._billing}get apiKeys(){return iq._apiKeys||(iq._apiKeys=new ik),iq._apiKeys}get oauthApplication(){return iq._oauthApplication||(iq._oauthApplication=new i_),iq._oauthApplication}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let a,r,n,i,{for:s,planId:o,planPeriod:l,seatsQuantity:c,priceId:u}=t;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===s&&null===e.organization)throw Error("Clerk: The current session does not have an active organization. Use `setActive` to set the organization");let d=function(e){let{userId:t,orgId:a,planId:r,planPeriod:n,seatsQuantity:i,priceId:s}=e;return`${t}-${a||"user"}-${r}-${n}-${i}-${s}`}({userId:e.user?.id||"",orgId:"organization"===s?e.organization?.id:void 0,planId:o,planPeriod:l,seatsQuantity:c,priceId:u}),h=iv.get(d);if(h)return h.signals.computedSignal();let m=(a=az({resource:null}),r=az({error:null}),n=az({status:"idle"}),i=aS(()=>{let e=a().resource,t=r().error,i=n().status;return{errors:aJ(t,{}),fetchStatus:i,checkout:e}}),{resourceSignal:a,errorSignal:r,fetchSignal:n,computedSignal:i}),p=new aY(m,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l,seatsQuantity:c,priceId:u});return iv.set(d,{resource:p,signals:m}),m.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eD[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return tW.throwMissingPublishableKeyError();const a=eS(e);if(!a)return tW.throwInvalidPublishableKeyError({key:e});this.#eA=t?.domain,this.#eC=t?.proxyUrl,this.environment=rQ.getInstance(),this.#eM=a.instanceType,this.#eI=e,this.#eU=function(e){let t=[],a=[];async function r(e){for await(let a of["u">typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await a(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["u">typeof window&&window.__internal_onAfterResponse,...a].filter(e=>e))if(await r(e,t)===!1)return!1;return!0}function i({method:t,path:a,sessionId:r,search:n,rotatingTokenNonce:s}){let o=new URLSearchParams(n);return o.append("__clerk_api_version","2026-05-12"),o.append("_clerk_js_version","6.25.9"),s&&o.append("rotating_token_nonce",s),e.domain&&"development"===e.instanceType&&e.isSatellite&&o.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&o.append("_method",t),a&&!iy.some(e=>a.startsWith(e))&&r&&o.append("_clerk_session_id",r),eM([...o.entries()].reduce((e,[t,a])=>(e[t]=a.includes(",")?a.split(","):a,e),{}))}function s(t){let{path:a,pathPrefix:r="v1"}=t;if(e.proxyUrl){let n=new URL(e.proxyUrl),s=n.pathname.slice(1);return s.endsWith("/")&&(s=s.slice(0,-1)),eL({base:n.origin,pathname:`${s}/${r}${a}`,search:i(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return eL({base:`https://${n||e.frontendApi}`,pathname:`${r}${a}`,search:i(t)},{stringify:!1})}async function o(t,a){let i,o={...t},{method:l="GET",body:c}=o;!c||"object"!=typeof c||c instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let t={};for(let[a,r]of Object.entries(e))void 0!==r&&(t[a]=r);return t}(c)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||c instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=c?eM(c,{keyEncoder:em}):c);let u=await r(o),d="GET"===l?"GET":"POST",h=o.url,m={...o,method:d,credentials:o.credentials||"include"};try{if(u){let e=a?.fetchMaxTries??(k()?4:11);i=await tA(()=>fetch(h,m),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,a)=>"GET"===d&&a<e&&!m.signal?.aborted,onBeforeRetry:e=>{h.searchParams.set("_clerk_retry_attempt",e.toString())}})}else i=new Response("{}",o)}catch(t){let e=h.toString();tj.error("network error",{error:t,url:e,method:l},"fapiClient");throw Error(`${t2} Network error at "${e}" - ${t}. Please try again.`)}let p=204!==i.status?await i.json():null,f=Object.assign(i,{payload:p});return i.ok||tj.error("request failed",{method:l,path:o.path,status:i.status},"fapiClient"),await n(o,f),f}return{buildEmailAddress:function(t){return function({localPart:e,frontendApi:t}){return`${e}@${t?t.replace("clerk.",""):"clerk.com"}`}({localPart:t,frontendApi:e.frontendApi})},buildUrl:s,onAfterResponse:function(e){a.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.#eK.emit(S,"loading"),this.#eK.prioritizedOn(S,e=>this.#eR=e),this.#eK.on(S,e=>{tG()&&("ready"===e||"degraded"===e?window.__clerk_internal_ready?.__resolve&&this.#eV()&&window.__clerk_internal_ready.__resolve(this):"error"===e&&window.__clerk_internal_ready?.__reject&&window.__clerk_internal_ready.__reject(new q("Clerk failed to initialize.",{code:"clerk_init_failed"})))}),tG()&&("ready"===this.#eR||"degraded"===this.#eR)&&this.#eV()&&window.__clerk_internal_ready?.__resolve&&window.__clerk_internal_ready.__resolve(this),au.clerk=this,this.#eP=new ix}getFapiClient=()=>this.#eU;load=async e=>{if(tj.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#eM||e?.unsafe_disableDevelopmentModeConsoleWarning||eT("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.#eD=this.#eG(e),this.#eF=this.#eD.__internal_oauthTransport??null,this.#eD.ui?.ClerkUI&&(this.#eT=Promise.resolve(this.#eD.ui.ClerkUI).then(e=>new e(()=>this,()=>this.environment,this.#eD,this.#eH))),"development"===this.#eM&&(this.#eD.routerPush||this.#eD.routerReplace)&&(!this.#eD.routerPush||!this.#eD.routerReplace)){let e=this.#eD.routerPush?"routerReplace":"routerPush";eT(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}rs.on(ri,()=>{this.#eJ(this.session)}),this.#eD.sdkMetadata&&(iq.sdkMetadata=this.#eD.sdkMetadata),!1!==this.#eD.telemetry&&(this.telemetry=new tu({clerkVersion:iq.version,samplingRate:1,perEventSampling:!this.#eD.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eD.telemetry}),this.#eD.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let a=e.theme;if(!a)return{};if(Array.isArray(a))for(let e of a){let a=tg(e);if(a){t=a;break}}else t=tg(a);return{themeName:t}}(this.#eD.appearance)}));try{this.#eD.standardBrowser?await this.#eZ():await this.#e$();let e=this.#eD.telemetry,t=!1!==e&&!e?.disabled,a=!!this.#eD.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,n=this.environment?.isProduction?.()??!1,i=r||a&&!n,s=a&&!r?"error":void 0;i&&function(e={}){if(tk)return;let{enabled:t=!1,...a}=e;t&&(ty=!0,tk=!0,tx(a))}({enabled:!0,...s?{logLevel:s}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#eP?.load(this.environment),tj.info("load() complete",{},"clerk")}catch(e){throw this.#eK.emit(S,"error"),tj.error("load() failed",{error:e},"clerk"),e}}};#eY(){let e;return!!(!this.#eD.signUpUrl&&this.#eD.signInUrl&&(e=this.#eD.signInUrl,!eq.test(e)))}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let a="u">typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:tb.lQ,r="u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tb.lQ,n=e&&"object"==typeof e?e:t||{},i=n?.redirectUrl||this.buildAfterSignOutUrl();tj.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:i,sessionTarget:n?.sessionId??null},"clerk");let s="function"==typeof e?e:void 0,o=async()=>{let e=tP(this.#eD.standardBrowser);rs.emit(rr,null),await e.track(async()=>{s?await s():await this.navigate(i)}),e.isUnloading()||(this.#eJ(),await r())};if(await a(),!n.sessionId||1===this.client.signedInSessions.length){this.#eQ(),this.#eD.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),tj.info("signOut() complete",{redirectUrl:eW(i)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId);l?.id&&this.session?.id===l.id?(this.#eQ(),await l?.remove(),await o(),tj.info("signOut() complete",{redirectUrl:eW(i)},"clerk")):await l?.remove()};openGoogleOneTap=e=>{this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(tf("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(ee(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotOpenSignInOrSignUp,{code:iE});return}this.assertComponentsReady(this.#eT);let t="SignIn";this.#eT.then(e=>e.ensureMounted({preloadHint:t})).then(t=>t.openModal("signIn",e||{}));let a={withSignUp:e?.withSignUp??this.#eY()};this.telemetry?.record(tf(t,e,a))};closeSignIn=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(et(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotRenderAnyBillingComponent("Checkout"),{code:iS});return}if(!this.user){if("development"===this.#eM)throw new q(e6.cannotOpenCheckout,{code:iI});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(et(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotRenderAnyBillingComponent("PlanDetails"),{code:iS});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(tf("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#eM)throw new q(e6.cannotOpenUserProfile,{code:iI});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(tf("UserVerification",e))};__internal_closeReverification=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:a}=e;if(this.user||"development"!==this.#eM||eT(`Clerk: "${a}" requires an active user session. Ensure a user is signed in before executing ${a}.`),"organizations"===t){let t;return(t=this.environment,t?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#eM&&this.__internal_openEnableOrganizationsPrompt({caller:a,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.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(tp("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#eT),this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await Promise.resolve().then(n.bind(n,7544));return e};openSignUp=e=>{if(ee(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotOpenSignInOrSignUp,{code:iE});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"SignUp"})).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(tf("SignUp",e))};closeSignUp=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#eM)throw new q(e6.cannotOpenUserProfile,{code:iI});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"UserProfile"})).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(tf("UserProfile",e,t))};closeUserProfile=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:iA})}});if(t){if(!this.organization){if("development"===this.#eM)throw new q(e6.createCannotRenderComponentWhenOrgDoesNotExist("OrganizationProfile"),{code:iC});return}this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"OrganizationProfile"})).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(tf("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:iA})}});t&&(this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"CreateOrganization"})).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(tf("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted({preloadHint:"Waitlist"})).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(tf("Waitlist",e))};closeWaitlist=()=>{this.#eT?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#eT);let a="SignIn";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#eY()};this.telemetry?.record(tp(a,t,r))};unmountSignIn=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#eT);let a="UserAvatar";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(tp(a,t))};unmountUserAvatar=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#eT);let a="SignUp";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(tp(a,t))};unmountSignUp=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#eM)throw new q(e6.cannotRenderComponentWhenUserDoesNotExist,{code:iI});return}this.assertComponentsReady(this.#eT);let a="UserProfile";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"userProfile",node:e,props:t}));let r=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(tp(a,t,r))};unmountUserProfile=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationProfile=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:iA})}});if(!a)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#eM)throw new q(e6.createCannotRenderComponentWhenOrgDoesNotExist("OrganizationProfile"),{code:iC});return}this.assertComponentsReady(this.#eT);let n="OrganizationProfile";this.#eT.then(e=>e.ensureMounted({preloadHint:n})).then(a=>a.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(tp(n,t))};unmountOrganizationProfile=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountCreateOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:iA})}});if(!a)return;this.assertComponentsReady(this.#eT);let r="CreateOrganization";this.#eT.then(e=>e.ensureMounted({preloadHint:r})).then(a=>a.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountCreateOrganization=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:iA})}});if(!a)return;this.assertComponentsReady(this.#eT);let r="OrganizationSwitcher";this.#eT.then(e=>e.ensureMounted({preloadHint:r})).then(a=>a.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(tp(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#eT),this.#eT.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:iA})}});if(!a)return;this.assertComponentsReady(this.#eT);let r="OrganizationList";this.#eT.then(e=>e.ensureMounted({preloadHint:r})).then(a=>a.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(tp(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#eT);let a="UserButton";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"userButton",node:e,props:t}));let r={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(tp(a,t,r))};unmountUserButton=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#eT);let a="Waitlist";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(tp(a,t))};unmountWaitlist=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(et(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotRenderAnyBillingComponent("PricingTable"),{code:iS});return}this.assertComponentsReady(this.#eT);let a="PricingTable";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(tp(a,t))};unmountPricingTable=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOAuthConsent=(e,t)=>{if(!this.user){if("development"===this.#eM)throw new q(e6.cannotRenderOAuthConsentComponentWhenUserDoesNotExist,{code:iI});return}this.assertComponentsReady(this.#eT);let a="OAuthConsent";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"__internal_oauthConsent",node:e,props:t}))};unmountOAuthConsent=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>this.mountOAuthConsent(e,t);__internal_unmountOAuthConsent=e=>this.unmountOAuthConsent(e);mountAPIKeys=(e,t)=>{let a;if(ea(this,a=this.environment)&&er(this,a)){if("development"===this.#eM)throw new q(e6.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&er(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(!this.organization&&ea(this,this.environment)){if("development"===this.#eM)throw new q(e6.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#eT);let r="APIKeys";this.#eT.then(e=>e.ensureMounted({preloadHint:r})).then(a=>a.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountAPIKeys=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountConfigureSSO=(e,t)=>{let a,r,{isEnabled:n}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"ConfigureSSO",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("ConfigureSSO"),{code:iA})}});if(!n)return;let i=!!this.user;if(!this.organization&&i){if("development"===this.#eM)throw new q(e6.createCannotRenderComponentWhenOrgDoesNotExist("ConfigureSSO"),{code:iC});return}if(a=this.environment,!a?.userSettings.enterpriseSSO.self_serve_sso||!this.organization?.selfServeSSOEnabled){if("development"===this.#eM)throw new q(e6.cannotRenderConfigureSSOComponentWhenDisabled,{code:"cannot_render_self_serve_sso_disabled"});return}if(r=this.environment,!r?.userSettings.attributes.email_address?.enabled){if("development"===this.#eM)throw new q(e6.cannotRenderConfigureSSOComponentWhenEmailAddressDisabled,{code:"cannot_render_configure_sso_email_address_disabled"});return}this.assertComponentsReady(this.#eT);let s="ConfigureSSO";this.#eT.then(e=>e.ensureMounted({preloadHint:s})).then(a=>a.mountComponent({name:s,appearanceKey:"configureSSO",node:e,props:t})),this.telemetry?.record(tp(s,t))};__internal_unmountConfigureSSO=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new q(e6.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:iA})}});if(!a)return;this.assertComponentsReady(this.#eT);let r="TaskChooseOrganization";this.#eT.then(e=>e.ensureMounted({preloadHint:r})).then(a=>a.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountTaskChooseOrganization=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#eT);let a="TaskResetPassword";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(tp("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskSetupMFA=(e,t)=>{this.assertComponentsReady(this.#eT);let a="TaskSetupMFA";this.#eT.then(e=>e.ensureMounted({preloadHint:a})).then(r=>r.mountComponent({name:a,appearanceKey:"taskSetupMfa",node:e,props:t})),this.telemetry?.record(tp("TaskSetupMFA",t))};unmountTaskSetupMFA=e=>{this.#eT?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:a,navigate:r}=e,{session:n}=e;this.__internal_setActiveInProgress=!0,tj.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof n?n:n?.id??n??null,organizationTarget:"string"==typeof t?t:t?.id??t??null,redirectUrl:a??null},"clerk");try{var i;let s;if(!this.client)throw tj.warn("Clerk setActive called before client is loaded",{},"clerk"),Error("setActive is being called before the client is loaded. Wait for init.");if(void 0===n&&!this.session)throw tj.warn("Clerk setActive precondition not met: no target session and no active session",{},"clerk"),Error("setActive should either be called with a session param or there should be already an active session.");"string"==typeof n&&(n=this.client.sessions.find(e=>e.id===n)||null);let o="u">typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:tb.lQ,l="u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tb.lQ,c=void 0===n?this.session:n;c?.status==="pending"&&(i={...this.#eD,...e},s=["taskUrls","navigate"],Object.keys(i).some(e=>s.includes(e))||eT('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let u=void 0!==t;if(c&&u){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let t=c.user.organizationMemberships.find(t=>t.organization.slug===e),a=t?.organization.id||null,r=null===a;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=a}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0);let d=c?.status==="pending"&&c?.currentTask&&this.#eD.taskUrls?.[c?.currentTask.key],h=!!(a||d||r),m=u?"select_org":"select_session";if(tG()&&globalThis.document.hasFocus()||!this.#eD.standardBrowser){let e;if(h&&c)try{(e=await c.__internal_touch({intent:m}))&&this.updateClient(e,{__internal_dangerouslySkipEmit:!0})}catch(e){if(J(e))this.handleUnauthenticated();else throw e}else await this.#eX(c,m);c=this.#e1(c?.id,e)}try{await c?.getToken()||rs.emit(ra,{token:null})}catch(e){if(N.is(e))tj.warn("Token fetch failed when setting active session (offline). Preserving existing auth state.",{sessionId:c?.id},"clerk");else throw e}let p=tP(this.#eD.standardBrowser);if(h&&await p.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eQ(),d){let e=a?eL({base:d,hashSearchParams:{redirectUrl:a}},{stringify:!0}):d;await this.navigate(e)}else if(r&&c){let e=!1,t=t=>{if(e=!0,!this.client?.isEligibleForTouch())return t;let a=new URL(t,window.location.href),r=this.client.buildTouchUrl({redirectUrl:a});return this.buildUrlWithAuth(r)};await r({session:c,decorateUrl:t}),"development"===this.#eM&&!e&&this.client.isEligibleForTouch()&&eT("Clerk: The navigate callback in setActive() did not call decorateUrl(). In Safari, sessions may be limited to 7 days due to Intelligent Tracking Prevention (ITP). Use decorateUrl() to wrap your destination URL to enable the ITP workaround. Learn more: https://clerk.com/docs/troubleshooting/safari-itp")}else if(a){if(this.client.isEligibleForTouch()){let e=new URL(a,window.location.href),t=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(t)}await this.navigate(a)}}}),p.isUnloading())return;this.#eJ(c),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=(e,t)=>{var a;let r;return a=e,e=e=>{var t;r||={...e},a(r={...{client:n5((t=r).client,e.client),session:n5(t.session,e.session),user:n5(t.user,e.user),organization:n5(t.organization,e.organization)}})},this.#eN.push(e),this.client&&!t?.skipInitialEmit&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#eN=this.#eN.filter(t=>t!==e)}};on=(...e)=>{this.#eK.on(...e)};off=(...e)=>{this.#eK.off(...e)};__internal_addNavigationListener=e=>(this.#eB.push(e),()=>{this.#eB=this.#eB.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tG())return;if(void 0===window.location){let a=t?.replace&&this.#eD.routerReplace?this.#eD.routerReplace:this.#eD.routerPush;return a?(tj.info(`Clerk is navigating to: ${e}`),await a(e,{windowNavigate:this.__internal_windowNavigate})):void 0}setTimeout(()=>{this.#e0()},0);let a=new URL(e,window.location.href);this.#e2.includes(a.protocol)||(console.warn(`Clerk: "${a.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),a=new URL("/",window.location.href));let r=t?.replace&&this.#eD.routerReplace?this.#eD.routerReplace:this.#eD.routerPush;if(tj.info(`Clerk is navigating to: ${a}`),this.#eD.routerDebug&&console.log(`Clerk is navigating to: ${a}`),"null"!==a.origin&&a.origin!==window.location.origin||!r)return void this.__internal_windowNavigate(a);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:this.__internal_windowNavigate};return await r(eW(a),n)};buildUrlWithAuth(e){if("production"===this.#eM)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#eE?this.#eE.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#e9(t));let a=this.isSatellite?this.#e3(e):e;return this.#e5("signInUrl",{...a,redirectUrl:t},e?.initialValues)}buildSignUpUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#e9(t));let a=this.isSatellite?this.#e3(e):e;return this.#e5("signUpUrl",{...a,redirectUrl:t},e?.initialValues)}#e9=e=>{try{let t=new URL(e,window.location.origin);return t.searchParams.set(en,ei),t.toString()}catch{return e}};#e3=e=>{if(!e)return e;let t={...e};return t.signInForceRedirectUrl&&(t.signInForceRedirectUrl=this.#e9(t.signInForceRedirectUrl)),t.signInFallbackRedirectUrl&&(t.signInFallbackRedirectUrl=this.#e9(t.signInFallbackRedirectUrl)),t.signUpForceRedirectUrl&&(t.signUpForceRedirectUrl=this.#e9(t.signUpForceRedirectUrl)),t.signUpFallbackRedirectUrl&&(t.signUpFallbackRedirectUrl=this.#e9(t.signUpFallbackRedirectUrl)),t};buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eZ(this.#eD,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eZ(this.#eD,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eD.afterSignOutUrl?this.buildUrlWithAuth(this.#eD.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eD.newSubscriptionRedirectUrl?this.#eD.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?eL({base:this.#eD.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eD.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eD.afterMultiSessionSingleSignOutUrl):this.#eD.signInUrl?this.buildUrlWithAuth(eL({base:this.#eD.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 a=this.#eD.taskUrls?.[t.key];return a||eL({base:this.buildSignInUrl(e),hashPath:e2(t)},{stringify:!0})}#e6=async()=>{if(!tG())return;let e=new URLSearchParams({[en]:es}),t=eQ(el);t&&te(t)||function(){throw Error(`${t2} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let a=eL({base:eQ(el),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(a))};redirectWithAuth=async e=>{if(tG())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tG())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tG())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tG())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tG())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tG())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tG())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tG())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tG())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tG())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tG())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let a=eQ("__clerk_status");if("expired"===a)throw new F(W.Expired);if("client_mismatch"===a)throw new F(W.ClientMismatch);if("verified"!==a)throw new F(W.Failed);let r=eQ("__clerk_created_session"),{signIn:n,signUp:i,sessions:s}=this.client,o=s.some(e=>e.id===r),l="needs_second_factor"===n.status||"missing_requirements"===i.status,c=e=>t&&"function"==typeof t?t(e):this.navigate(e),u=e.redirectUrl?()=>c(e.redirectUrl):tb.lQ;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?u():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};__internal_handleResourceCallback=async(e,t,a)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:n}=this.client,i="identifier"in(e||{})?e:r,s="missingFields"in(e||{})?e:n,o=e=>a&&"function"==typeof a?a(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:s,signIn:i,navigate:o})};handleGoogleOneTapCallback=async(e,t,a)=>this.__internal_handleResourceCallback(e,t,a);_handleRedirectCallback=async(e,{signIn:t,signUp:a,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await t.reload():"signUp"===e.reloadResource&&await a.reload()}catch{}let{displayConfig:n}=this.environment,{firstFactorVerification:i}=t,{externalAccount:s}=a.verifications,o={status:a.status,missingFields:a.missingFields,externalAccountStatus:s.status,externalAccountErrorCode:s.error?.code,externalAccountSessionId:s.error?.meta?.sessionId,sessionId:a.createdSessionId,protectCheck:a.protectCheck},l={status:t.status,firstFactorVerificationStatus:i.status,firstFactorVerificationErrorCode:i.error?.code,firstFactorVerificationSessionId:i.error?.meta?.sessionId,sessionId:t.createdSessionId,protectCheck:t.protectCheck},c=e=>()=>r(e),u=c(e.signInUrl||n.signInUrl),d=c(e.signUpUrl||n.signUpUrl),h=c(e.firstFactorUrl||eL({base:n.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||eL({base:n.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||eL({base:n.signInUrl,hashPath:"/reset-password"},{stringify:!0})),f=c(e.signInProtectCheckUrl||eL({base:n.signInUrl,hashPath:"/protect-check"},{stringify:!0})),g=new eZ(this.#eD,e),b=c(e.continueSignUpUrl||eL({base:n.signUpUrl,hashPath:"/continue"},{stringify:!0})),y=c(e.signUpProtectCheckUrl||eL({base:n.signUpUrl,hashPath:"/protect-check"},{stringify:!0})),w=({missingFields:t})=>a.protectCheck||t.includes("protect_check")?y():t.length?b():(({signUp:e,verifyEmailPath:t,verifyPhonePath:a,protectCheckPath:r,continuePath:n,navigate:i,handleComplete:s,redirectUrl:o="",redirectUrlComplete:l="",oidcPrompt:c})=>{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:o,redirectUrlComplete:l,continueSignUp:!0,oidcPrompt:c});let s=e1();if((e.protectCheck||e.missingFields.some(e=>"protect_check"===e))&&r)return i(r,{searchParams:s});if(e.unverifiedFields?.includes("email_address")&&t)return i(t,{searchParams:s});if(e.unverifiedFields?.includes("phone_number")&&a)return i(a,{searchParams:s});if(n)return i(n,{searchParams:s})}})({signUp:a,verifyEmailPath:e.verifyEmailAddressUrl||eL({base:n.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||eL({base:n.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),protectCheckPath:e.signUpProtectCheckUrl||eL({base:n.signUpUrl,hashPath:"/protect-check"},{stringify:!0}),navigate:r}),k=e.signInUrl||n.signInUrl,v=e.signUpUrl||n.signUpUrl,_=e.__internal_navigateOnSetActive,x=async({session:e,baseUrl:t,redirectUrl:a})=>{_?await _({session:e,redirectUrl:a,decorateUrl:e=>this.buildUrlWithAuth(e)}):e.currentTask?await e9(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(a)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await x({session:e,baseUrl:k,redirectUrl:g.getAfterSignInUrl()})}});if("signUp"!==e.reloadResource&&(l.protectCheck||"needs_protect_check"===l.status))return f();if("signIn"!==e.reloadResource&&o.protectCheck)return y();if("transferable"===o.externalAccountStatus&&o.externalAccountErrorCode===ec){let e=await t.create({transfer:!0});if(e.protectCheck||"needs_protect_check"===e.status)return f();switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await x({session:e,baseUrl:v,redirectUrl:g.getAfterSignInUrl()})}});case"needs_first_factor":return h();case"needs_second_factor":return m();case"needs_new_password":return p();default:t3("sign in")}}let j="user_locked"===o.externalAccountErrorCode,z="user_locked"===l.firstFactorVerificationErrorCode;if(j)return d();if(z)return u();if("needs_first_factor"===l.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return h();if("needs_new_password"===l.status)return p();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return u();let t=await a.create({transfer:!0,unsafeMetadata:e.unsafeMetadata});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await x({session:e,baseUrl:v,redirectUrl:g.getAfterSignUpUrl()})}});case"missing_requirements":return w({missingFields:t.missingFields});default:t3("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await x({session:e,baseUrl:v,redirectUrl:g.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return m();let S=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,I="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(S||I){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await x({session:e,baseUrl:S?v:k,redirectUrl:g.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(a)?d():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?w({missingFields:a.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):u()};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:a,signUp:r}=this.client,n=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:a,navigate:n})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await rS.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&rs.emit(rr,null),this.setActive({session:null})}catch(e){if(M(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};__internal_handleUnauthenticatedDevBrowser=async()=>{this.#eE&&await this.#eE.handleUnauthenticatedDevBrowser()};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if(M(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:a,unsafeMetadata:r,strategy:n,legalAccepted:i,secondFactorUrl:s,protectCheckUrl:o,signUpProtectCheckUrl:l,walletName:c})=>{let u,d;if(!this.client||!this.environment)return;let{displayConfig:h}=this.environment,m=n.replace("web3_","").replace("_signature",""),p=await tY().getWeb3Identifier({provider:m,walletName:c});switch(m){case"metamask":u=tY().generateSignatureWithMetamask;break;case"base":u=tY().generateSignatureWithBase;break;case"coinbase_wallet":u=tY().generateSignatureWithCoinbaseWallet;break;case"solana":if(!c)throw new q("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});u=e=>tY().generateSignatureWithSolana({...e,walletName:c});break;default:u=tY().generateSignatureWithOKXWallet}let f=e=>()=>a&&"function"==typeof a?a(e):this.navigate(e),g=f(s||eL({base:h.signInUrl,hashPath:"/factor-two"},{stringify:!0})),b=f(o||eL({base:h.signInUrl,hashPath:"/protect-check"},{stringify:!0})),y=f(l||eL({base:h.signUpUrl,hashPath:"/protect-check"},{stringify:!0})),w=f(t||eL({base:h.signUpUrl,hashPath:"/continue"},{stringify:!0})),k=!1;try{d=await this.client.signIn.authenticateWithWeb3({identifier:p,generateSignature:u,strategy:n,walletName:c})}catch(e){if(tL(e,"form_identifier_not_found"))k=!0,d=await this.client.signUp.authenticateWithWeb3({identifier:p,generateSignature:u,unsafeMetadata:r,strategy:n,legalAccepted:i,walletName:c}),t&&"missing_requirements"===d.status&&"verified"===d.verifications.web3Wallet.status&&!d.protectCheck&&await w();else throw e}let v=async({session:e,redirectUrl:t})=>{e.currentTask?await e9(e,{baseUrl:h.signInUrl,navigate:this.navigate}):await this.navigate(t)};if(d.protectCheck||"needs_protect_check"===d.status)return void await (k?y:b)();switch(d.status){case"needs_second_factor":await g();break;case"complete":d.createdSessionId&&await this.setActive({session:d.createdSessionId,navigate:async({session:t})=>{await v({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>r7.create({name:e,slug:t});getOrganization=async e=>r7.get(e);joinWaitlist=async({emailAddress:e})=>n9.join({emailAddress:e});updateEnvironment(e){this.environment=e}__internal_setCountry=e=>{this.__internal_country||(this.__internal_country=e)};get __internal_last_error(){let e=this.internal_last_error;return this.internal_last_error=null,e}set __internal_last_error(e){this.internal_last_error=e}updateClient=(e,t)=>{if(!this.client){let t=this.#eD.selectInitialSession?this.#eD.selectInitialSession(e):this.#e8(e);this.#eJ(t,{dangerouslySkipEmit:!0})}if(this.client=e,this.session){let t=this.#e1(this.session.id,e);"active"===this.session.status&&t?.status==="pending"&&("u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tb.lQ)(),this.#eJ(t,{dangerouslySkipEmit:!0}),this.session?.lastActiveToken||v()||tj.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),rs.emit(ra,{token:this.session?.lastActiveToken})}t?.__internal_dangerouslySkipEmit||this.#e4()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new rQ(e)};__internal_onBeforeRequest=e=>{this.#eU.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#eU.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#eG({...this.#eD,...e.options})};return this.#eT?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#e7=()=>{let e=new URLSearchParams({[el]:window.location.href});return eL({base:this.#eD.signInUrl,searchParams:e},{stringify:!0})};#te=()=>{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()||""};#tt=()=>{let e=eQ(en);return e!==es&&!!this.isSatellite&&(e===ei||!0===this.#eD.satelliteAutoSync&&!!this.#eE?.isSignedOut())};#ta=()=>"production"!==this.#eM&&!this.isSatellite&&!!eQ(el);#tr=async()=>{"development"===this.instanceType?await this.navigate(this.#e7()):"production"===this.instanceType&&await this.navigate(this.#te())};#tn=(e,t)=>{let a;try{a=new URL(e)}catch{throw Error(`${t2} The signInUrl needs to have a absolute url format.`)}a.origin===t&&function(){throw Error(`${t2} The signInUrl needs to be on a different origin than your satellite application.`)}()};#ti=()=>{this.isSatellite&&("development"!==this.#eM||this.#eD.signInUrl||function(){throw Error(`${t2} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${t2} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#eD.signInUrl&&this.#tn(this.#eD.signInUrl,window.location.origin))};#eZ=async()=>{if(this.#eE=await ig.create(this,this.#eU,this.#eM,this.#eK),this.#ti(),this.#tt())return void await this.#tr();if(this.#ta())return void await this.#e6();this.#eL=(()=>{if(!f())return{onPageFocus:tb.lQ};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"u">typeof BroadcastChannel&&(this.#eO=new BroadcastChannel("clerk")),this.#ts();let e=function(e=window.location.hostname){if(!e)return!1;let t=eD.get(e);void 0===t&&(t=ek.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||ev.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),eD.set(e,t));return t}(window?.location.hostname),t="development"===this.#eM&&!e,a=0,r=0;for(;r<2;){r++;try{let e=rQ.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++a;let e=t0.getItem(tQ,null);e&&this.updateEnvironment(new rQ(e))}),r=async()=>{let e=new AbortController;return(0,tb.zc)(rS.getOrCreateInstance().fetch({abortSignal:e.signal}),7e3,e).then(e=>this.updateClient(e)).catch(async e=>{if(V(e))throw e;++a,this.#eE?.stopPollingForToken();try{let e=this.#e8(iw(this.#eE?.getSessionCookie()));e?.clearCache();let t=e?await (0,tb.zc)(e.getToken(),7e3).catch(()=>(e.clearCache(),this.#eE?.getSessionCookie())):this.#eE?.getSessionCookie();this.updateClient(iw(t))}finally{this.#eE?.startPollingForToken()}return rS.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(tb.lQ),null})},[,n]=await (0,tb.vd)([e,r()]);if("rejected"===n.status){let e=n.reason;if(tL(e,"requires_captcha"))await r();else throw e}if(this.#eE?.setClientUatCookieForDevelopmentInstances(),await this.#to())return;break}catch(e){if(tL(e,"dev_browser_unauthenticated"))await this.#eE.handleUnauthenticatedDevBrowser();else if(!v())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${t2} Something went wrong initializing Clerk.`)}()}this.#eq=new ib(this),this.#eq.start(),this.#tl(),this.#tc(),this.#tu(),this.#eK.emit(S,a>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#e$=async()=>{let e,t,a=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([rQ.getInstance().fetch({touch:!1,fetchMaxTries:a}),rS.getOrCreateInstance().fetch({fetchMaxTries:a})])}catch(a){if(O(a)&&"network_error"===a.code&&this.shouldFallbackToCachedResources()){let a=await this.__internal_getCachedResources?.();e=new rQ(a?.environment),rS.clearInstance(),t=rS.getOrCreateInstance(a?.client),++r}else throw a}this.updateClient(t),this.updateEnvironment(e),this.#eK.emit(S,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([rQ.getInstance().fetch({touch:!1,fetchMaxTries:1}),rS.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#e4()};#e8=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#ts=()=>{f()&&(this.#eL?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eW>Date.now())&&(this.#eW=Date.now()+5e3,this.#eD.touchSession&&this.#eX(this.session,"focus"))}),this.#eO?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),rs.on(rr,()=>{this.#eO?.postMessage({type:"signout"})}),rs.on(rn,()=>{t0.setItem(tQ,this.environment?.__internal_toSnapshot(),864e5)}))};#eX=async(e,t="focus")=>{if(!e)return Promise.resolve();await e.touch({intent:t}).catch(e=>{if(J(e))this.handleUnauthenticated();else throw e})};__internal_lastEmittedResources;#e4=()=>{if(this.client){let e={client:this.client,session:this.session,user:this.user,organization:this.organization};for(let t of(this.__internal_lastEmittedResources=e,this.#eN))t(e)}};#e0=()=>{for(let e of this.#eB)e()};#eQ=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#e4()};#td=(e=this.session)=>(e?.user.organizationMemberships||[]).map(e=>e.organization).find(t=>t.id===e?.lastActiveOrganizationId)||null;#th=(e=this.session)=>({session:e||null,organization:this.#td(e),user:e?e.user:null});#eJ=(e,t)=>{let{session:a,organization:r,user:n}=this.#th(e);this.session=a,this.organization=r,this.user=n,t?.dangerouslySkipEmit||this.#e4()};#e1=(e,t=this.client)=>t?.signedInSessions.find(t=>t.id===e)||null;#tc=()=>{this.addListener(({session:e})=>{e?.actor&&this.#eT?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#tu=()=>{this.#eD.__internal_keyless_claimKeylessApplicationUrl&&this.#eT?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eD.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eD.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eD.__internal_keyless_dismissPrompt}})})};#e5=(e,t,a)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eD[e]||this.environment.displayConfig[e];this.#eY()&&(r=this.#eD.signInUrl);let n=new eZ(this.#eD,t).toSearchParams(),i=new URLSearchParams(a||{}),s=eL({base:r,hashPath:this.#eY()&&"signUpUrl"===e?"/create":"",hashSearchParams:[i,n]},{stringify:!0});return this.buildUrlWithAuth(s)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#to=async()=>{var e;let t,a,r,n,i=new URLSearchParams(window.location.search).get("redirect_url"),s="production"===this.instanceType,o=null!==i&&(e=this.frontendApi,a=(t=new URL(i,eR)).pathname,r=eG.includes(a)||eJ.includes(a),e===t.host&&r);if(s||!o)return!1;let l=this.session,c=this.#eD.signInUrl||this.environment?.displayConfig.signInUrl,u=c&&window.location.href.startsWith(c),d=this.#eD.signUpUrl||this.environment?.displayConfig.signUpUrl,h=d&&window.location.href.startsWith(d);return n=new URL(i,eR),(!eG.includes(n.pathname)||!!l||!u&&!h)&&(await this.navigate(this.buildUrlWithAuth(i)),!0)};#eG=e=>{let t=e?.clerkUICtor??e?.clerkUiCtor,a=t?{...e?.ui,ClerkUI:t}:e?.ui;return{...iP,...e,ui:a,allowedRedirectOrigins:function(e,t,a){if(Array.isArray(e)&&e.length)return e;let r=[];return"u">typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${eF(t)}`),r.push(`https://*.${eF(t)}`),"development"===a&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)}};#tl=()=>{try{eX(en),eX(e$),eX(eo),eX("__clerk_handshake"),eX("__clerk_handshake_nonce"),eX("__clerk_help")}catch{}};get #e2(){let e=e4;return this.#eD.allowedRedirectProtocols&&(e=e.concat(this.#eD.allowedRedirectProtocols)),e}__internal_windowNavigate=(e,t)=>{!function(e,t){if("string"==typeof e&&e7.test(function(e){let t=0;for(;t<e.length&&32>=e.charCodeAt(t);)t++;let a="";for(let r=t;r<e.length;r++){let t=e.charCodeAt(r);9!==t&&10!==t&&13!==t&&(a+=e[r])}return a}(e)))return console.warn(`Clerk: scheme-relative navigation to "${e}" is not allowed. Provide a same-origin path or an absolute URL.`);let a=new URL(e,window.location.href);(t?.allowedProtocols??e4).includes(a.protocol)?(window.dispatchEvent(new CustomEvent(e8)),window.location.href=a.href):console.warn(`Clerk: "${a.protocol}" is not a valid navigation protocol. Aborting navigation. If you think this is a mistake, please open an issue.`)}(e,{allowedProtocols:t?.useStaticAllowlistOnly?e4:this.#e2})};#eV(){return void 0!==this.client}}})();var s=exports;for(var o in i)s[o]=i[o];i.__esModule&&Object.defineProperty(s,"__esModule",{value:!0})})();