@clerk/shared 4.8.4-snapshot.v20260423044224 → 4.8.4

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 (70) hide show
  1. package/dist/runtime/apiUrlFromPublishableKey.js +1 -1
  2. package/dist/runtime/apiUrlFromPublishableKey.mjs +1 -1
  3. package/dist/runtime/color.d.mts.map +1 -1
  4. package/dist/runtime/globs.d.mts.map +1 -1
  5. package/dist/runtime/globs.d.ts.map +1 -1
  6. package/dist/runtime/index-B4_BYgBX.d.mts.map +1 -1
  7. package/dist/runtime/index-gwPUTb24.d.ts.map +1 -1
  8. package/dist/runtime/internal/clerk-js/completeSignUpFlow.js +3 -3
  9. package/dist/runtime/internal/clerk-js/completeSignUpFlow.mjs +3 -3
  10. package/dist/runtime/internal/clerk-js/queryParams.js +3 -3
  11. package/dist/runtime/internal/clerk-js/queryParams.mjs +3 -3
  12. package/dist/runtime/internal/clerk-js/queryStateParams.js +3 -3
  13. package/dist/runtime/internal/clerk-js/queryStateParams.mjs +3 -3
  14. package/dist/runtime/internal/clerk-js/redirectUrls.js +2 -2
  15. package/dist/runtime/internal/clerk-js/redirectUrls.mjs +2 -2
  16. package/dist/runtime/internal/clerk-js/sessionTasks.js +4 -4
  17. package/dist/runtime/internal/clerk-js/sessionTasks.mjs +4 -4
  18. package/dist/runtime/internal/clerk-js/url.js +2 -2
  19. package/dist/runtime/internal/clerk-js/url.mjs +2 -2
  20. package/dist/runtime/{keys-DuxzP8MU.mjs → keys-BeVKH43u.mjs} +32 -2
  21. package/dist/runtime/keys-BeVKH43u.mjs.map +1 -0
  22. package/dist/runtime/{keys-BI9hmfja.js → keys-D5ahg2Gn.js} +37 -1
  23. package/dist/runtime/keys-D5ahg2Gn.js.map +1 -0
  24. package/dist/runtime/keys.d.mts +26 -1
  25. package/dist/runtime/keys.d.mts.map +1 -1
  26. package/dist/runtime/keys.d.ts +26 -1
  27. package/dist/runtime/keys.d.ts.map +1 -1
  28. package/dist/runtime/keys.js +3 -2
  29. package/dist/runtime/keys.mjs +2 -2
  30. package/dist/runtime/loadClerkJsScript.js +3 -3
  31. package/dist/runtime/loadClerkJsScript.js.map +1 -1
  32. package/dist/runtime/loadClerkJsScript.mjs +3 -3
  33. package/dist/runtime/loadClerkJsScript.mjs.map +1 -1
  34. package/dist/runtime/{netlifyCacheHandler-Dkdkho_6.mjs → netlifyCacheHandler-Cpx2hZ9E.mjs} +2 -2
  35. package/dist/runtime/{netlifyCacheHandler-Dkdkho_6.mjs.map → netlifyCacheHandler-Cpx2hZ9E.mjs.map} +1 -1
  36. package/dist/runtime/{netlifyCacheHandler-DFm5qdPh.js → netlifyCacheHandler-DMlEakyq.js} +2 -2
  37. package/dist/runtime/{netlifyCacheHandler-DFm5qdPh.js.map → netlifyCacheHandler-DMlEakyq.js.map} +1 -1
  38. package/dist/runtime/netlifyCacheHandler.js +2 -2
  39. package/dist/runtime/netlifyCacheHandler.mjs +2 -2
  40. package/dist/runtime/{queryParams-Dlt0oVDg.mjs → queryParams-Bad5kF87.mjs} +2 -2
  41. package/dist/runtime/{queryParams-Dlt0oVDg.mjs.map → queryParams-Bad5kF87.mjs.map} +1 -1
  42. package/dist/runtime/{queryParams-DSUymAGT.js → queryParams-DFhrd86C.js} +2 -2
  43. package/dist/runtime/{queryParams-DSUymAGT.js.map → queryParams-DFhrd86C.js.map} +1 -1
  44. package/dist/runtime/react/index.d.mts +1 -1
  45. package/dist/runtime/react/index.d.ts +1 -1
  46. package/dist/runtime/react/index.js +3 -3
  47. package/dist/runtime/react/index.js.map +1 -1
  48. package/dist/runtime/react/index.mjs +3 -3
  49. package/dist/runtime/react/index.mjs.map +1 -1
  50. package/dist/runtime/router.d.mts.map +1 -1
  51. package/dist/runtime/router.d.ts.map +1 -1
  52. package/dist/runtime/{telemetry-DE2JFEBf.mjs → telemetry-DJrefnDc.mjs} +2 -2
  53. package/dist/runtime/{telemetry-DE2JFEBf.mjs.map → telemetry-DJrefnDc.mjs.map} +1 -1
  54. package/dist/runtime/{telemetry--P0a0tSk.js → telemetry-DMGwYVSd.js} +2 -2
  55. package/dist/runtime/{telemetry--P0a0tSk.js.map → telemetry-DMGwYVSd.js.map} +1 -1
  56. package/dist/runtime/telemetry.js +2 -2
  57. package/dist/runtime/telemetry.mjs +2 -2
  58. package/dist/runtime/{url-CoXV4i87.js → url-Cw4Wpvh3.js} +2 -2
  59. package/dist/runtime/{url-CoXV4i87.js.map → url-Cw4Wpvh3.js.map} +1 -1
  60. package/dist/runtime/{url-DaPDWryr.mjs → url-cNLJYbcB.mjs} +2 -2
  61. package/dist/runtime/{url-DaPDWryr.mjs.map → url-cNLJYbcB.mjs.map} +1 -1
  62. package/dist/runtime/{versionSelector-CY7koW8Z.js → versionSelector-C1hK82gB.js} +2 -2
  63. package/dist/runtime/{versionSelector-CY7koW8Z.js.map → versionSelector-C1hK82gB.js.map} +1 -1
  64. package/dist/runtime/{versionSelector-CR64ra7G.mjs → versionSelector-CNF9SLY3.mjs} +2 -2
  65. package/dist/runtime/{versionSelector-CR64ra7G.mjs.map → versionSelector-CNF9SLY3.mjs.map} +1 -1
  66. package/dist/runtime/versionSelector.js +1 -1
  67. package/dist/runtime/versionSelector.mjs +1 -1
  68. package/package.json +1 -1
  69. package/dist/runtime/keys-BI9hmfja.js.map +0 -1
  70. package/dist/runtime/keys-DuxzP8MU.mjs.map +0 -1
@@ -1,10 +1,10 @@
1
1
  require('../../constants-WYhx_umW.js');
2
2
  require('../../isomorphicAtob-Hkpnx2p8.js');
3
3
  require('../../isomorphicBtoa-_pSA92Q9.js');
4
- require('../../keys-BI9hmfja.js');
5
- require('../../netlifyCacheHandler-DFm5qdPh.js');
4
+ require('../../keys-D5ahg2Gn.js');
5
+ require('../../netlifyCacheHandler-DMlEakyq.js');
6
6
  require('../../constants-BUzkV8jh.js');
7
- const require_queryParams = require('../../queryParams-DSUymAGT.js');
7
+ const require_queryParams = require('../../queryParams-DFhrd86C.js');
8
8
 
9
9
  //#region src/internal/clerk-js/completeSignUpFlow.ts
10
10
  const completeSignUpFlow = ({ signUp, verifyEmailPath, verifyPhonePath, continuePath, navigate, handleComplete, redirectUrl = "", redirectUrlComplete = "", oidcPrompt }) => {
@@ -1,10 +1,10 @@
1
1
  import "../../constants-Bta24VLk.mjs";
2
2
  import "../../isomorphicAtob-CoF80qYz.mjs";
3
3
  import "../../isomorphicBtoa-DWmLcIHi.mjs";
4
- import "../../keys-DuxzP8MU.mjs";
5
- import "../../netlifyCacheHandler-Dkdkho_6.mjs";
4
+ import "../../keys-BeVKH43u.mjs";
5
+ import "../../netlifyCacheHandler-Cpx2hZ9E.mjs";
6
6
  import "../../constants-BulbbNR9.mjs";
7
- import { t as forwardClerkQueryParams } from "../../queryParams-Dlt0oVDg.mjs";
7
+ import { t as forwardClerkQueryParams } from "../../queryParams-Bad5kF87.mjs";
8
8
 
9
9
  //#region src/internal/clerk-js/completeSignUpFlow.ts
10
10
  const completeSignUpFlow = ({ signUp, verifyEmailPath, verifyPhonePath, continuePath, navigate, handleComplete, redirectUrl = "", redirectUrlComplete = "", oidcPrompt }) => {
@@ -1,10 +1,10 @@
1
1
  require('../../constants-WYhx_umW.js');
2
2
  require('../../isomorphicAtob-Hkpnx2p8.js');
3
3
  require('../../isomorphicBtoa-_pSA92Q9.js');
4
- require('../../keys-BI9hmfja.js');
5
- require('../../netlifyCacheHandler-DFm5qdPh.js');
4
+ require('../../keys-D5ahg2Gn.js');
5
+ require('../../netlifyCacheHandler-DMlEakyq.js');
6
6
  require('../../constants-BUzkV8jh.js');
7
- const require_queryParams = require('../../queryParams-DSUymAGT.js');
7
+ const require_queryParams = require('../../queryParams-DFhrd86C.js');
8
8
 
9
9
  exports.forwardClerkQueryParams = require_queryParams.forwardClerkQueryParams;
10
10
  exports.getClerkQueryParam = require_queryParams.getClerkQueryParam;
@@ -1,9 +1,9 @@
1
1
  import "../../constants-Bta24VLk.mjs";
2
2
  import "../../isomorphicAtob-CoF80qYz.mjs";
3
3
  import "../../isomorphicBtoa-DWmLcIHi.mjs";
4
- import "../../keys-DuxzP8MU.mjs";
5
- import "../../netlifyCacheHandler-Dkdkho_6.mjs";
4
+ import "../../keys-BeVKH43u.mjs";
5
+ import "../../netlifyCacheHandler-Cpx2hZ9E.mjs";
6
6
  import "../../constants-BulbbNR9.mjs";
7
- import { n as getClerkQueryParam, r as removeClerkQueryParam, t as forwardClerkQueryParams } from "../../queryParams-Dlt0oVDg.mjs";
7
+ import { n as getClerkQueryParam, r as removeClerkQueryParam, t as forwardClerkQueryParams } from "../../queryParams-Bad5kF87.mjs";
8
8
 
9
9
  export { forwardClerkQueryParams, getClerkQueryParam, removeClerkQueryParam };
@@ -1,10 +1,10 @@
1
1
  require('../../constants-WYhx_umW.js');
2
2
  require('../../isomorphicAtob-Hkpnx2p8.js');
3
3
  require('../../isomorphicBtoa-_pSA92Q9.js');
4
- require('../../keys-BI9hmfja.js');
5
- require('../../netlifyCacheHandler-DFm5qdPh.js');
4
+ require('../../keys-D5ahg2Gn.js');
5
+ require('../../netlifyCacheHandler-DMlEakyq.js');
6
6
  const require_constants$1 = require('../../constants-BUzkV8jh.js');
7
- const require_queryParams = require('../../queryParams-DSUymAGT.js');
7
+ const require_queryParams = require('../../queryParams-DFhrd86C.js');
8
8
  const require_encoders = require('../../encoders-C_EA3--l.js');
9
9
 
10
10
  //#region src/internal/clerk-js/queryStateParams.ts
@@ -1,10 +1,10 @@
1
1
  import "../../constants-Bta24VLk.mjs";
2
2
  import "../../isomorphicAtob-CoF80qYz.mjs";
3
3
  import "../../isomorphicBtoa-DWmLcIHi.mjs";
4
- import "../../keys-DuxzP8MU.mjs";
5
- import "../../netlifyCacheHandler-Dkdkho_6.mjs";
4
+ import "../../keys-BeVKH43u.mjs";
5
+ import "../../netlifyCacheHandler-Cpx2hZ9E.mjs";
6
6
  import { r as CLERK_MODAL_STATE } from "../../constants-BulbbNR9.mjs";
7
- import { n as getClerkQueryParam } from "../../queryParams-Dlt0oVDg.mjs";
7
+ import { n as getClerkQueryParam } from "../../queryParams-Bad5kF87.mjs";
8
8
  import { n as encodeB64 } from "../../encoders-CAjYroSe.mjs";
9
9
 
10
10
  //#region src/internal/clerk-js/queryStateParams.ts
@@ -1,7 +1,7 @@
1
1
  require('../../constants-WYhx_umW.js');
2
2
  require('../../isomorphicAtob-Hkpnx2p8.js');
3
3
  require('../../isomorphicBtoa-_pSA92Q9.js');
4
- require('../../keys-BI9hmfja.js');
4
+ require('../../keys-D5ahg2Gn.js');
5
5
  require('../../globs-D0Kpu4g1.js');
6
6
  require('../../instance-C1LlVxIp.js');
7
7
  require('../../url-sAcxbiir.js');
@@ -10,7 +10,7 @@ const require_object = require('../../object-DklYlVP-.js');
10
10
  const require_underscore = require('../../underscore-BX6Ucmg5.js');
11
11
  require('../../path-ci3QmWY8.js');
12
12
  require('../../querystring-BFj_iDi0.js');
13
- const require_url$1 = require('../../url-CoXV4i87.js');
13
+ const require_url$1 = require('../../url-Cw4Wpvh3.js');
14
14
 
15
15
  //#region src/internal/clerk-js/redirectUrls.ts
16
16
  var RedirectUrls = class RedirectUrls {
@@ -1,7 +1,7 @@
1
1
  import "../../constants-Bta24VLk.mjs";
2
2
  import "../../isomorphicAtob-CoF80qYz.mjs";
3
3
  import "../../isomorphicBtoa-DWmLcIHi.mjs";
4
- import "../../keys-DuxzP8MU.mjs";
4
+ import "../../keys-BeVKH43u.mjs";
5
5
  import "../../globs-u_gXJPLt.mjs";
6
6
  import "../../instance-BmZr0cdE.mjs";
7
7
  import "../../url-C6gPMFx5.mjs";
@@ -10,7 +10,7 @@ import { n as filterProps, r as removeUndefined, t as applyFunctionToObj } from
10
10
  import { t as camelToSnake } from "../../underscore-ClYSgvuy.mjs";
11
11
  import "../../path-BLD6zl1u.mjs";
12
12
  import "../../querystring-pXtwII0l.mjs";
13
- import { l as isAllowedRedirect, v as relativeToAbsoluteUrl } from "../../url-DaPDWryr.mjs";
13
+ import { l as isAllowedRedirect, v as relativeToAbsoluteUrl } from "../../url-cNLJYbcB.mjs";
14
14
 
15
15
  //#region src/internal/clerk-js/redirectUrls.ts
16
16
  var RedirectUrls = class RedirectUrls {
@@ -1,18 +1,18 @@
1
1
  require('../../constants-WYhx_umW.js');
2
2
  require('../../isomorphicAtob-Hkpnx2p8.js');
3
3
  require('../../isomorphicBtoa-_pSA92Q9.js');
4
- require('../../keys-BI9hmfja.js');
4
+ require('../../keys-D5ahg2Gn.js');
5
5
  require('../../globs-D0Kpu4g1.js');
6
6
  require('../../instance-C1LlVxIp.js');
7
7
  require('../../url-sAcxbiir.js');
8
8
  const require_logger = require('../../logger-BOte4sQb.js');
9
- require('../../netlifyCacheHandler-DFm5qdPh.js');
9
+ require('../../netlifyCacheHandler-DMlEakyq.js');
10
10
  require('../../underscore-BX6Ucmg5.js');
11
11
  require('../../constants-BUzkV8jh.js');
12
- const require_queryParams = require('../../queryParams-DSUymAGT.js');
12
+ const require_queryParams = require('../../queryParams-DFhrd86C.js');
13
13
  require('../../path-ci3QmWY8.js');
14
14
  require('../../querystring-BFj_iDi0.js');
15
- const require_url$1 = require('../../url-CoXV4i87.js');
15
+ const require_url$1 = require('../../url-Cw4Wpvh3.js');
16
16
 
17
17
  //#region src/internal/clerk-js/sessionTasks.ts
18
18
  /**
@@ -1,18 +1,18 @@
1
1
  import "../../constants-Bta24VLk.mjs";
2
2
  import "../../isomorphicAtob-CoF80qYz.mjs";
3
3
  import "../../isomorphicBtoa-DWmLcIHi.mjs";
4
- import "../../keys-DuxzP8MU.mjs";
4
+ import "../../keys-BeVKH43u.mjs";
5
5
  import "../../globs-u_gXJPLt.mjs";
6
6
  import "../../instance-BmZr0cdE.mjs";
7
7
  import "../../url-C6gPMFx5.mjs";
8
8
  import { t as logger } from "../../logger-DISzhF9M.mjs";
9
- import "../../netlifyCacheHandler-Dkdkho_6.mjs";
9
+ import "../../netlifyCacheHandler-Cpx2hZ9E.mjs";
10
10
  import "../../underscore-ClYSgvuy.mjs";
11
11
  import "../../constants-BulbbNR9.mjs";
12
- import { t as forwardClerkQueryParams } from "../../queryParams-Dlt0oVDg.mjs";
12
+ import { t as forwardClerkQueryParams } from "../../queryParams-Bad5kF87.mjs";
13
13
  import "../../path-BLD6zl1u.mjs";
14
14
  import "../../querystring-pXtwII0l.mjs";
15
- import { t as buildURL } from "../../url-DaPDWryr.mjs";
15
+ import { t as buildURL } from "../../url-cNLJYbcB.mjs";
16
16
 
17
17
  //#region src/internal/clerk-js/sessionTasks.ts
18
18
  /**
@@ -1,7 +1,7 @@
1
1
  require('../../constants-WYhx_umW.js');
2
2
  require('../../isomorphicAtob-Hkpnx2p8.js');
3
3
  require('../../isomorphicBtoa-_pSA92Q9.js');
4
- require('../../keys-BI9hmfja.js');
4
+ require('../../keys-D5ahg2Gn.js');
5
5
  require('../../globs-D0Kpu4g1.js');
6
6
  require('../../instance-C1LlVxIp.js');
7
7
  require('../../url-sAcxbiir.js');
@@ -9,7 +9,7 @@ require('../../logger-BOte4sQb.js');
9
9
  require('../../underscore-BX6Ucmg5.js');
10
10
  require('../../path-ci3QmWY8.js');
11
11
  require('../../querystring-BFj_iDi0.js');
12
- const require_url$1 = require('../../url-CoXV4i87.js');
12
+ const require_url$1 = require('../../url-Cw4Wpvh3.js');
13
13
 
14
14
  exports.buildURL = require_url$1.buildURL;
15
15
  exports.createAllowedRedirectOrigins = require_url$1.createAllowedRedirectOrigins;
@@ -1,7 +1,7 @@
1
1
  import "../../constants-Bta24VLk.mjs";
2
2
  import "../../isomorphicAtob-CoF80qYz.mjs";
3
3
  import "../../isomorphicBtoa-DWmLcIHi.mjs";
4
- import "../../keys-DuxzP8MU.mjs";
4
+ import "../../keys-BeVKH43u.mjs";
5
5
  import "../../globs-u_gXJPLt.mjs";
6
6
  import "../../instance-BmZr0cdE.mjs";
7
7
  import "../../url-C6gPMFx5.mjs";
@@ -9,6 +9,6 @@ import "../../logger-DISzhF9M.mjs";
9
9
  import "../../underscore-ClYSgvuy.mjs";
10
10
  import "../../path-BLD6zl1u.mjs";
11
11
  import "../../querystring-pXtwII0l.mjs";
12
- import { C as trimLeadingSlash, S as toURL, _ as pathFromFullPath, a as hasBannedHrefProtocol, b as sanitizeHref, c as hasUrlInFragment, d as isDevAccountPortalOrigin, f as isDevOrStagingUrl, g as mergeFragmentIntoUrl, h as isValidUrl, i as getSearchParameterFromHash, l as isAllowedRedirect, m as isRedirectForFAPIInitiatedFlow, n as createAllowedRedirectOrigins, o as hasBannedProtocol, p as isProblematicUrl, r as getETLDPlusOneFromFrontendApi, s as hasExternalAccountSignUpError, t as buildURL, u as isDataUri, v as relativeToAbsoluteUrl, w as trimTrailingSlash, x as stripOrigin, y as requiresUserInput } from "../../url-DaPDWryr.mjs";
12
+ import { C as trimLeadingSlash, S as toURL, _ as pathFromFullPath, a as hasBannedHrefProtocol, b as sanitizeHref, c as hasUrlInFragment, d as isDevAccountPortalOrigin, f as isDevOrStagingUrl, g as mergeFragmentIntoUrl, h as isValidUrl, i as getSearchParameterFromHash, l as isAllowedRedirect, m as isRedirectForFAPIInitiatedFlow, n as createAllowedRedirectOrigins, o as hasBannedProtocol, p as isProblematicUrl, r as getETLDPlusOneFromFrontendApi, s as hasExternalAccountSignUpError, t as buildURL, u as isDataUri, v as relativeToAbsoluteUrl, w as trimTrailingSlash, x as stripOrigin, y as requiresUserInput } from "../../url-cNLJYbcB.mjs";
13
13
 
14
14
  export { buildURL, createAllowedRedirectOrigins, getETLDPlusOneFromFrontendApi, getSearchParameterFromHash, hasBannedHrefProtocol, hasBannedProtocol, hasExternalAccountSignUpError, hasUrlInFragment, isAllowedRedirect, isDataUri, isDevAccountPortalOrigin, isDevOrStagingUrl, isProblematicUrl, isRedirectForFAPIInitiatedFlow, isValidUrl, mergeFragmentIntoUrl, pathFromFullPath, relativeToAbsoluteUrl, requiresUserInput, sanitizeHref, stripOrigin, toURL, trimLeadingSlash, trimTrailingSlash };
@@ -22,6 +22,36 @@ function buildPublishableKey(frontendApi) {
22
22
  return `${PUBLISHABLE_FRONTEND_API_DEV_REGEX.test(frontendApi) || frontendApi.startsWith("clerk.") && LEGACY_DEV_INSTANCE_SUFFIXES.some((s) => frontendApi.endsWith(s)) ? PUBLISHABLE_KEY_TEST_PREFIX : PUBLISHABLE_KEY_LIVE_PREFIX}${isomorphicBtoa(`${frontendApi}$`)}`;
23
23
  }
24
24
  /**
25
+ * Derives a publishable key from the current hostname. Intended for multi-domain
26
+ * setups (e.g. custom domains on top of a default domain) where the correct key
27
+ * must be resolved per request.
28
+ *
29
+ * Pass the configured publishable key as `fallbackKey` so that development
30
+ * instances (pk_test_) are returned as-is instead of being incorrectly derived
31
+ * from the host (e.g. localhost).
32
+ *
33
+ * @example
34
+ * // React (use window.location.hostname, not window.location.host, to avoid including the port)
35
+ * <ClerkProvider publishableKey={publishableKeyFromHost(window.location.hostname, import.meta.env.VITE_CLERK_PUBLISHABLE_KEY)}>
36
+ *
37
+ * @example
38
+ * // Express (inside clerkMiddleware callback)
39
+ * // Validate req.hostname against a known allowlist before passing it in.
40
+ * // When `trust proxy` is enabled, req.hostname reads from X-Forwarded-Host
41
+ * // and can be spoofed if your proxy is not properly configured.
42
+ * const ALLOWED_HOSTS = ['domain-a.com', 'domain-b.com'];
43
+ * clerkMiddleware((req) => {
44
+ * if (!ALLOWED_HOSTS.includes(req.hostname)) throw new Error('Unknown host');
45
+ * return { publishableKey: publishableKeyFromHost(req.hostname, process.env.CLERK_PUBLISHABLE_KEY) };
46
+ * })
47
+ */
48
+ function publishableKeyFromHost(host, fallbackKey) {
49
+ if (fallbackKey && isDevelopmentFromPublishableKey(fallbackKey)) return fallbackKey;
50
+ const hostname = host.toLowerCase().replace(/:\d+$/, "");
51
+ if (!hostname) throw new Error("Host must not be empty.");
52
+ return buildPublishableKey(`clerk.${hostname}`);
53
+ }
54
+ /**
25
55
  * Validates that a decoded publishable key has the correct format.
26
56
  * The decoded value should be a frontend API followed by exactly one '$' at the end.
27
57
  *
@@ -177,5 +207,5 @@ const getSuffixedCookieName = (cookieName, cookieSuffix) => {
177
207
  };
178
208
 
179
209
  //#endregion
180
- export { isDevelopmentFromPublishableKey as a, isProductionFromSecretKey as c, getSuffixedCookieName as i, isPublishableKey as l, createDevOrStagingUrlCache as n, isDevelopmentFromSecretKey as o, getCookieSuffix as r, isProductionFromPublishableKey as s, buildPublishableKey as t, parsePublishableKey as u };
181
- //# sourceMappingURL=keys-DuxzP8MU.mjs.map
210
+ export { isDevelopmentFromPublishableKey as a, isProductionFromSecretKey as c, publishableKeyFromHost as d, getSuffixedCookieName as i, isPublishableKey as l, createDevOrStagingUrlCache as n, isDevelopmentFromSecretKey as o, getCookieSuffix as r, isProductionFromPublishableKey as s, buildPublishableKey as t, parsePublishableKey as u };
211
+ //# sourceMappingURL=keys-BeVKH43u.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys-BeVKH43u.mjs","names":["decodedFrontendApi: string"],"sources":["../../src/keys.ts"],"sourcesContent":["import { DEV_OR_STAGING_SUFFIXES, LEGACY_DEV_INSTANCE_SUFFIXES } from './constants';\nimport { isomorphicAtob } from './isomorphicAtob';\nimport { isomorphicBtoa } from './isomorphicBtoa';\nimport type { PublishableKey } from './types';\n\n/**\n * Configuration options for parsing publishable keys.\n */\ntype ParsePublishableKeyOptions = {\n /** Whether to throw an error if parsing fails */\n fatal?: boolean;\n /** Custom domain to use for satellite instances */\n domain?: string;\n /** Proxy URL to use instead of the decoded frontend API */\n proxyUrl?: string;\n /** Whether this is a satellite instance */\n isSatellite?: boolean;\n};\n\n/** Prefix used for production publishable keys */\nconst PUBLISHABLE_KEY_LIVE_PREFIX = 'pk_live_';\n\n/** Prefix used for development publishable keys */\nconst PUBLISHABLE_KEY_TEST_PREFIX = 'pk_test_';\n\n/**\n * Regular expression that matches development frontend API keys.\n * Matches patterns like: foo-bar-13.clerk.accounts.dev.\n */\nconst PUBLISHABLE_FRONTEND_API_DEV_REGEX = /^(([a-z]+)-){2}([0-9]{1,2})\\.clerk\\.accounts([a-z.]*)(dev|com)$/i;\n\n/**\n * Converts a frontend API URL into a base64-encoded publishable key.\n *\n * @param frontendApi - The frontend API URL (e.g., 'clerk.example.com').\n * @returns A base64-encoded publishable key with appropriate prefix (pk_live_ or pk_test_).\n */\nexport function buildPublishableKey(frontendApi: string): string {\n const isDevKey =\n PUBLISHABLE_FRONTEND_API_DEV_REGEX.test(frontendApi) ||\n (frontendApi.startsWith('clerk.') && LEGACY_DEV_INSTANCE_SUFFIXES.some(s => frontendApi.endsWith(s)));\n const keyPrefix = isDevKey ? PUBLISHABLE_KEY_TEST_PREFIX : PUBLISHABLE_KEY_LIVE_PREFIX;\n return `${keyPrefix}${isomorphicBtoa(`${frontendApi}$`)}`;\n}\n\n/**\n * Derives a publishable key from the current hostname. Intended for multi-domain\n * setups (e.g. custom domains on top of a default domain) where the correct key\n * must be resolved per request.\n *\n * Pass the configured publishable key as `fallbackKey` so that development\n * instances (pk_test_) are returned as-is instead of being incorrectly derived\n * from the host (e.g. localhost).\n *\n * @example\n * // React (use window.location.hostname, not window.location.host, to avoid including the port)\n * <ClerkProvider publishableKey={publishableKeyFromHost(window.location.hostname, import.meta.env.VITE_CLERK_PUBLISHABLE_KEY)}>\n *\n * @example\n * // Express (inside clerkMiddleware callback)\n * // Validate req.hostname against a known allowlist before passing it in.\n * // When `trust proxy` is enabled, req.hostname reads from X-Forwarded-Host\n * // and can be spoofed if your proxy is not properly configured.\n * const ALLOWED_HOSTS = ['domain-a.com', 'domain-b.com'];\n * clerkMiddleware((req) => {\n * if (!ALLOWED_HOSTS.includes(req.hostname)) throw new Error('Unknown host');\n * return { publishableKey: publishableKeyFromHost(req.hostname, process.env.CLERK_PUBLISHABLE_KEY) };\n * })\n */\nexport function publishableKeyFromHost(host: string, fallbackKey?: string): string {\n if (fallbackKey && isDevelopmentFromPublishableKey(fallbackKey)) {\n return fallbackKey;\n }\n const hostname = host.toLowerCase().replace(/:\\d+$/, '');\n if (!hostname) {\n throw new Error('Host must not be empty.');\n }\n return buildPublishableKey(`clerk.${hostname}`);\n}\n\n/**\n * Validates that a decoded publishable key has the correct format.\n * The decoded value should be a frontend API followed by exactly one '$' at the end.\n *\n * @param decoded - The decoded publishable key string to validate.\n * @returns `true` if the decoded key has valid format, `false` otherwise.\n */\nfunction isValidDecodedPublishableKey(decoded: string): boolean {\n if (!decoded.endsWith('$')) {\n return false;\n }\n\n const withoutTrailing = decoded.slice(0, -1);\n if (withoutTrailing.includes('$')) {\n return false;\n }\n\n return withoutTrailing.includes('.');\n}\n\nexport function parsePublishableKey(\n key: string | undefined,\n options: ParsePublishableKeyOptions & { fatal: true },\n): PublishableKey;\nexport function parsePublishableKey(\n key: string | undefined,\n options?: ParsePublishableKeyOptions,\n): PublishableKey | null;\n/**\n * Parses and validates a publishable key, extracting the frontend API and instance type.\n *\n * @param key - The publishable key to parse.\n * @param options - Configuration options for parsing.\n * @param options.fatal\n * @param options.domain\n * @param options.proxyUrl\n * @param options.isSatellite\n * @returns Parsed publishable key object with instanceType and frontendApi, or null if invalid.\n *\n * @throws {Error} When options.fatal is true and key is missing or invalid.\n */\nexport function parsePublishableKey(\n key: string | undefined,\n options: { fatal?: boolean; domain?: string; proxyUrl?: string; isSatellite?: boolean } = {},\n): PublishableKey | null {\n key = key || '';\n\n if (!key || !isPublishableKey(key)) {\n if (options.fatal && !key) {\n throw new Error(\n 'Publishable key is missing. Ensure that your publishable key is correctly configured. Double-check your environment configuration for your keys, or access them here: https://dashboard.clerk.com/last-active?path=api-keys',\n );\n }\n if (options.fatal && !isPublishableKey(key)) {\n throw new Error('Publishable key not valid.');\n }\n return null;\n }\n\n const instanceType = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) ? 'production' : 'development';\n\n let decodedFrontendApi: string;\n try {\n decodedFrontendApi = isomorphicAtob(key.split('_')[2]);\n } catch {\n if (options.fatal) {\n throw new Error('Publishable key not valid: Failed to decode key.');\n }\n return null;\n }\n\n if (!isValidDecodedPublishableKey(decodedFrontendApi)) {\n if (options.fatal) {\n throw new Error('Publishable key not valid: Decoded key has invalid format.');\n }\n return null;\n }\n\n let frontendApi = decodedFrontendApi.slice(0, -1);\n\n if (options.proxyUrl) {\n frontendApi = options.proxyUrl;\n } else if (instanceType !== 'development' && options.domain && options.isSatellite) {\n frontendApi = `clerk.${options.domain}`;\n }\n\n return {\n instanceType,\n frontendApi,\n };\n}\n\n/**\n * Checks if the provided key is a valid publishable key.\n *\n * @param key - The key to be checked. Defaults to an empty string if not provided.\n * @returns `true` if 'key' is a valid publishable key, `false` otherwise.\n */\nexport function isPublishableKey(key: string = '') {\n try {\n const hasValidPrefix = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) || key.startsWith(PUBLISHABLE_KEY_TEST_PREFIX);\n\n if (!hasValidPrefix) {\n return false;\n }\n\n const parts = key.split('_');\n if (parts.length !== 3) {\n return false;\n }\n\n const encodedPart = parts[2];\n if (!encodedPart) {\n return false;\n }\n\n const decoded = isomorphicAtob(encodedPart);\n return isValidDecodedPublishableKey(decoded);\n } catch {\n return false;\n }\n}\n\n/**\n * Creates a memoized cache for checking if URLs are development or staging environments.\n * Uses a Map to cache results for better performance on repeated checks.\n *\n * @returns An object with an isDevOrStagingUrl method that checks if a URL is dev/staging.\n */\nexport function createDevOrStagingUrlCache() {\n const devOrStagingUrlCache = new Map<string, boolean>();\n\n return {\n /**\n * Checks if a URL is a development or staging environment.\n *\n * @param url - The URL to check (string or URL object).\n * @returns `true` if the URL is a development or staging environment, `false` otherwise.\n */\n isDevOrStagingUrl: (url: string | URL): boolean => {\n if (!url) {\n return false;\n }\n\n const hostname = typeof url === 'string' ? url : url.hostname;\n let res = devOrStagingUrlCache.get(hostname);\n if (res === undefined) {\n res = DEV_OR_STAGING_SUFFIXES.some(s => hostname.endsWith(s));\n devOrStagingUrlCache.set(hostname, res);\n }\n return res;\n },\n };\n}\n\n/**\n * Checks if a publishable key is for a development environment.\n * Supports both legacy format (test_) and new format (pk_test_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('pk_test_');\n}\n\n/**\n * Checks if a publishable key is for a production environment.\n * Supports both legacy format (live_) and new format (pk_live_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('pk_live_');\n}\n\n/**\n * Checks if a secret key is for a development environment.\n * Supports both legacy format (test_) and new format (sk_test_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('sk_test_');\n}\n\n/**\n * Checks if a secret key is for a production environment.\n * Supports both legacy format (live_) and new format (sk_live_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('sk_live_');\n}\n\n/**\n * Generates a unique cookie suffix based on the publishable key using SHA-1 hashing.\n * The suffix is base64-encoded and URL-safe (+ and / characters are replaced).\n *\n * @param publishableKey - The publishable key to generate suffix from.\n * @param subtle - The SubtleCrypto interface to use for hashing (defaults to globalThis.crypto.subtle).\n * @returns A promise that resolves to an 8-character URL-safe base64 string.\n */\nexport async function getCookieSuffix(\n publishableKey: string,\n subtle: SubtleCrypto = globalThis.crypto.subtle,\n): Promise<string> {\n const data = new TextEncoder().encode(publishableKey);\n const digest = await subtle.digest('sha-1', data);\n const stringDigest = String.fromCharCode(...new Uint8Array(digest));\n // Base 64 Encoding with URL and Filename Safe Alphabet: https://datatracker.ietf.org/doc/html/rfc4648#section-5\n return isomorphicBtoa(stringDigest).replace(/\\+/gi, '-').replace(/\\//gi, '_').substring(0, 8);\n}\n\n/**\n * Creates a suffixed cookie name by appending the cookie suffix to the base name.\n * Used to create unique cookie names based on the publishable key.\n *\n * @param cookieName - The base cookie name.\n * @param cookieSuffix - The suffix to append (typically generated by getCookieSuffix).\n * @returns The suffixed cookie name in format: `${cookieName}_${cookieSuffix}`.\n */\nexport const getSuffixedCookieName = (cookieName: string, cookieSuffix: string): string => {\n return `${cookieName}_${cookieSuffix}`;\n};\n"],"mappings":";;;;;;AAoBA,MAAM,8BAA8B;;AAGpC,MAAM,8BAA8B;;;;;AAMpC,MAAM,qCAAqC;;;;;;;AAQ3C,SAAgB,oBAAoB,aAA6B;AAK/D,QAAO,GAHL,mCAAmC,KAAK,YAAY,IACnD,YAAY,WAAW,SAAS,IAAI,6BAA6B,MAAK,MAAK,YAAY,SAAS,EAAE,CAAC,GACzE,8BAA8B,8BACrC,eAAe,GAAG,YAAY,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BzD,SAAgB,uBAAuB,MAAc,aAA8B;AACjF,KAAI,eAAe,gCAAgC,YAAY,CAC7D,QAAO;CAET,MAAM,WAAW,KAAK,aAAa,CAAC,QAAQ,SAAS,GAAG;AACxD,KAAI,CAAC,SACH,OAAM,IAAI,MAAM,0BAA0B;AAE5C,QAAO,oBAAoB,SAAS,WAAW;;;;;;;;;AAUjD,SAAS,6BAA6B,SAA0B;AAC9D,KAAI,CAAC,QAAQ,SAAS,IAAI,CACxB,QAAO;CAGT,MAAM,kBAAkB,QAAQ,MAAM,GAAG,GAAG;AAC5C,KAAI,gBAAgB,SAAS,IAAI,CAC/B,QAAO;AAGT,QAAO,gBAAgB,SAAS,IAAI;;;;;;;;;;;;;;;AAwBtC,SAAgB,oBACd,KACA,UAA0F,EAAE,EACrE;AACvB,OAAM,OAAO;AAEb,KAAI,CAAC,OAAO,CAAC,iBAAiB,IAAI,EAAE;AAClC,MAAI,QAAQ,SAAS,CAAC,IACpB,OAAM,IAAI,MACR,8NACD;AAEH,MAAI,QAAQ,SAAS,CAAC,iBAAiB,IAAI,CACzC,OAAM,IAAI,MAAM,6BAA6B;AAE/C,SAAO;;CAGT,MAAM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;;;;;AAUpE,SAAgB,+BAA+B,QAAyB;AACtE,QAAO,OAAO,WAAW,QAAQ,IAAI,OAAO,WAAW,WAAW;;;;;;;;;AAUpE,SAAgB,2BAA2B,QAAyB;AAClE,QAAO,OAAO,WAAW,QAAQ,IAAI,OAAO,WAAW,WAAW;;;;;;;;;AAUpE,SAAgB,0BAA0B,QAAyB;AACjE,QAAO,OAAO,WAAW,QAAQ,IAAI,OAAO,WAAW,WAAW;;;;;;;;;;AAWpE,eAAsB,gBACpB,gBACA,SAAuB,WAAW,OAAO,QACxB;CACjB,MAAM,OAAO,IAAI,aAAa,CAAC,OAAO,eAAe;CACrD,MAAM,SAAS,MAAM,OAAO,OAAO,SAAS,KAAK;AAGjD,QAAO,eAFc,OAAO,aAAa,GAAG,IAAI,WAAW,OAAO,CAAC,CAEhC,CAAC,QAAQ,QAAQ,IAAI,CAAC,QAAQ,QAAQ,IAAI,CAAC,UAAU,GAAG,EAAE;;;;;;;;;;AAW/F,MAAa,yBAAyB,YAAoB,iBAAiC;AACzF,QAAO,GAAG,WAAW,GAAG"}
@@ -22,6 +22,36 @@ function buildPublishableKey(frontendApi) {
22
22
  return `${PUBLISHABLE_FRONTEND_API_DEV_REGEX.test(frontendApi) || frontendApi.startsWith("clerk.") && require_constants.LEGACY_DEV_INSTANCE_SUFFIXES.some((s) => frontendApi.endsWith(s)) ? PUBLISHABLE_KEY_TEST_PREFIX : PUBLISHABLE_KEY_LIVE_PREFIX}${require_isomorphicBtoa.isomorphicBtoa(`${frontendApi}$`)}`;
23
23
  }
24
24
  /**
25
+ * Derives a publishable key from the current hostname. Intended for multi-domain
26
+ * setups (e.g. custom domains on top of a default domain) where the correct key
27
+ * must be resolved per request.
28
+ *
29
+ * Pass the configured publishable key as `fallbackKey` so that development
30
+ * instances (pk_test_) are returned as-is instead of being incorrectly derived
31
+ * from the host (e.g. localhost).
32
+ *
33
+ * @example
34
+ * // React (use window.location.hostname, not window.location.host, to avoid including the port)
35
+ * <ClerkProvider publishableKey={publishableKeyFromHost(window.location.hostname, import.meta.env.VITE_CLERK_PUBLISHABLE_KEY)}>
36
+ *
37
+ * @example
38
+ * // Express (inside clerkMiddleware callback)
39
+ * // Validate req.hostname against a known allowlist before passing it in.
40
+ * // When `trust proxy` is enabled, req.hostname reads from X-Forwarded-Host
41
+ * // and can be spoofed if your proxy is not properly configured.
42
+ * const ALLOWED_HOSTS = ['domain-a.com', 'domain-b.com'];
43
+ * clerkMiddleware((req) => {
44
+ * if (!ALLOWED_HOSTS.includes(req.hostname)) throw new Error('Unknown host');
45
+ * return { publishableKey: publishableKeyFromHost(req.hostname, process.env.CLERK_PUBLISHABLE_KEY) };
46
+ * })
47
+ */
48
+ function publishableKeyFromHost(host, fallbackKey) {
49
+ if (fallbackKey && isDevelopmentFromPublishableKey(fallbackKey)) return fallbackKey;
50
+ const hostname = host.toLowerCase().replace(/:\d+$/, "");
51
+ if (!hostname) throw new Error("Host must not be empty.");
52
+ return buildPublishableKey(`clerk.${hostname}`);
53
+ }
54
+ /**
25
55
  * Validates that a decoded publishable key has the correct format.
26
56
  * The decoded value should be a frontend API followed by exactly one '$' at the end.
27
57
  *
@@ -237,4 +267,10 @@ Object.defineProperty(exports, 'parsePublishableKey', {
237
267
  return parsePublishableKey;
238
268
  }
239
269
  });
240
- //# sourceMappingURL=keys-BI9hmfja.js.map
270
+ Object.defineProperty(exports, 'publishableKeyFromHost', {
271
+ enumerable: true,
272
+ get: function () {
273
+ return publishableKeyFromHost;
274
+ }
275
+ });
276
+ //# sourceMappingURL=keys-D5ahg2Gn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys-D5ahg2Gn.js","names":["LEGACY_DEV_INSTANCE_SUFFIXES","isomorphicBtoa","decodedFrontendApi: string","isomorphicAtob","DEV_OR_STAGING_SUFFIXES"],"sources":["../../src/keys.ts"],"sourcesContent":["import { DEV_OR_STAGING_SUFFIXES, LEGACY_DEV_INSTANCE_SUFFIXES } from './constants';\nimport { isomorphicAtob } from './isomorphicAtob';\nimport { isomorphicBtoa } from './isomorphicBtoa';\nimport type { PublishableKey } from './types';\n\n/**\n * Configuration options for parsing publishable keys.\n */\ntype ParsePublishableKeyOptions = {\n /** Whether to throw an error if parsing fails */\n fatal?: boolean;\n /** Custom domain to use for satellite instances */\n domain?: string;\n /** Proxy URL to use instead of the decoded frontend API */\n proxyUrl?: string;\n /** Whether this is a satellite instance */\n isSatellite?: boolean;\n};\n\n/** Prefix used for production publishable keys */\nconst PUBLISHABLE_KEY_LIVE_PREFIX = 'pk_live_';\n\n/** Prefix used for development publishable keys */\nconst PUBLISHABLE_KEY_TEST_PREFIX = 'pk_test_';\n\n/**\n * Regular expression that matches development frontend API keys.\n * Matches patterns like: foo-bar-13.clerk.accounts.dev.\n */\nconst PUBLISHABLE_FRONTEND_API_DEV_REGEX = /^(([a-z]+)-){2}([0-9]{1,2})\\.clerk\\.accounts([a-z.]*)(dev|com)$/i;\n\n/**\n * Converts a frontend API URL into a base64-encoded publishable key.\n *\n * @param frontendApi - The frontend API URL (e.g., 'clerk.example.com').\n * @returns A base64-encoded publishable key with appropriate prefix (pk_live_ or pk_test_).\n */\nexport function buildPublishableKey(frontendApi: string): string {\n const isDevKey =\n PUBLISHABLE_FRONTEND_API_DEV_REGEX.test(frontendApi) ||\n (frontendApi.startsWith('clerk.') && LEGACY_DEV_INSTANCE_SUFFIXES.some(s => frontendApi.endsWith(s)));\n const keyPrefix = isDevKey ? PUBLISHABLE_KEY_TEST_PREFIX : PUBLISHABLE_KEY_LIVE_PREFIX;\n return `${keyPrefix}${isomorphicBtoa(`${frontendApi}$`)}`;\n}\n\n/**\n * Derives a publishable key from the current hostname. Intended for multi-domain\n * setups (e.g. custom domains on top of a default domain) where the correct key\n * must be resolved per request.\n *\n * Pass the configured publishable key as `fallbackKey` so that development\n * instances (pk_test_) are returned as-is instead of being incorrectly derived\n * from the host (e.g. localhost).\n *\n * @example\n * // React (use window.location.hostname, not window.location.host, to avoid including the port)\n * <ClerkProvider publishableKey={publishableKeyFromHost(window.location.hostname, import.meta.env.VITE_CLERK_PUBLISHABLE_KEY)}>\n *\n * @example\n * // Express (inside clerkMiddleware callback)\n * // Validate req.hostname against a known allowlist before passing it in.\n * // When `trust proxy` is enabled, req.hostname reads from X-Forwarded-Host\n * // and can be spoofed if your proxy is not properly configured.\n * const ALLOWED_HOSTS = ['domain-a.com', 'domain-b.com'];\n * clerkMiddleware((req) => {\n * if (!ALLOWED_HOSTS.includes(req.hostname)) throw new Error('Unknown host');\n * return { publishableKey: publishableKeyFromHost(req.hostname, process.env.CLERK_PUBLISHABLE_KEY) };\n * })\n */\nexport function publishableKeyFromHost(host: string, fallbackKey?: string): string {\n if (fallbackKey && isDevelopmentFromPublishableKey(fallbackKey)) {\n return fallbackKey;\n }\n const hostname = host.toLowerCase().replace(/:\\d+$/, '');\n if (!hostname) {\n throw new Error('Host must not be empty.');\n }\n return buildPublishableKey(`clerk.${hostname}`);\n}\n\n/**\n * Validates that a decoded publishable key has the correct format.\n * The decoded value should be a frontend API followed by exactly one '$' at the end.\n *\n * @param decoded - The decoded publishable key string to validate.\n * @returns `true` if the decoded key has valid format, `false` otherwise.\n */\nfunction isValidDecodedPublishableKey(decoded: string): boolean {\n if (!decoded.endsWith('$')) {\n return false;\n }\n\n const withoutTrailing = decoded.slice(0, -1);\n if (withoutTrailing.includes('$')) {\n return false;\n }\n\n return withoutTrailing.includes('.');\n}\n\nexport function parsePublishableKey(\n key: string | undefined,\n options: ParsePublishableKeyOptions & { fatal: true },\n): PublishableKey;\nexport function parsePublishableKey(\n key: string | undefined,\n options?: ParsePublishableKeyOptions,\n): PublishableKey | null;\n/**\n * Parses and validates a publishable key, extracting the frontend API and instance type.\n *\n * @param key - The publishable key to parse.\n * @param options - Configuration options for parsing.\n * @param options.fatal\n * @param options.domain\n * @param options.proxyUrl\n * @param options.isSatellite\n * @returns Parsed publishable key object with instanceType and frontendApi, or null if invalid.\n *\n * @throws {Error} When options.fatal is true and key is missing or invalid.\n */\nexport function parsePublishableKey(\n key: string | undefined,\n options: { fatal?: boolean; domain?: string; proxyUrl?: string; isSatellite?: boolean } = {},\n): PublishableKey | null {\n key = key || '';\n\n if (!key || !isPublishableKey(key)) {\n if (options.fatal && !key) {\n throw new Error(\n 'Publishable key is missing. Ensure that your publishable key is correctly configured. Double-check your environment configuration for your keys, or access them here: https://dashboard.clerk.com/last-active?path=api-keys',\n );\n }\n if (options.fatal && !isPublishableKey(key)) {\n throw new Error('Publishable key not valid.');\n }\n return null;\n }\n\n const instanceType = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) ? 'production' : 'development';\n\n let decodedFrontendApi: string;\n try {\n decodedFrontendApi = isomorphicAtob(key.split('_')[2]);\n } catch {\n if (options.fatal) {\n throw new Error('Publishable key not valid: Failed to decode key.');\n }\n return null;\n }\n\n if (!isValidDecodedPublishableKey(decodedFrontendApi)) {\n if (options.fatal) {\n throw new Error('Publishable key not valid: Decoded key has invalid format.');\n }\n return null;\n }\n\n let frontendApi = decodedFrontendApi.slice(0, -1);\n\n if (options.proxyUrl) {\n frontendApi = options.proxyUrl;\n } else if (instanceType !== 'development' && options.domain && options.isSatellite) {\n frontendApi = `clerk.${options.domain}`;\n }\n\n return {\n instanceType,\n frontendApi,\n };\n}\n\n/**\n * Checks if the provided key is a valid publishable key.\n *\n * @param key - The key to be checked. Defaults to an empty string if not provided.\n * @returns `true` if 'key' is a valid publishable key, `false` otherwise.\n */\nexport function isPublishableKey(key: string = '') {\n try {\n const hasValidPrefix = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) || key.startsWith(PUBLISHABLE_KEY_TEST_PREFIX);\n\n if (!hasValidPrefix) {\n return false;\n }\n\n const parts = key.split('_');\n if (parts.length !== 3) {\n return false;\n }\n\n const encodedPart = parts[2];\n if (!encodedPart) {\n return false;\n }\n\n const decoded = isomorphicAtob(encodedPart);\n return isValidDecodedPublishableKey(decoded);\n } catch {\n return false;\n }\n}\n\n/**\n * Creates a memoized cache for checking if URLs are development or staging environments.\n * Uses a Map to cache results for better performance on repeated checks.\n *\n * @returns An object with an isDevOrStagingUrl method that checks if a URL is dev/staging.\n */\nexport function createDevOrStagingUrlCache() {\n const devOrStagingUrlCache = new Map<string, boolean>();\n\n return {\n /**\n * Checks if a URL is a development or staging environment.\n *\n * @param url - The URL to check (string or URL object).\n * @returns `true` if the URL is a development or staging environment, `false` otherwise.\n */\n isDevOrStagingUrl: (url: string | URL): boolean => {\n if (!url) {\n return false;\n }\n\n const hostname = typeof url === 'string' ? url : url.hostname;\n let res = devOrStagingUrlCache.get(hostname);\n if (res === undefined) {\n res = DEV_OR_STAGING_SUFFIXES.some(s => hostname.endsWith(s));\n devOrStagingUrlCache.set(hostname, res);\n }\n return res;\n },\n };\n}\n\n/**\n * Checks if a publishable key is for a development environment.\n * Supports both legacy format (test_) and new format (pk_test_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('pk_test_');\n}\n\n/**\n * Checks if a publishable key is for a production environment.\n * Supports both legacy format (live_) and new format (pk_live_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('pk_live_');\n}\n\n/**\n * Checks if a secret key is for a development environment.\n * Supports both legacy format (test_) and new format (sk_test_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('sk_test_');\n}\n\n/**\n * Checks if a secret key is for a production environment.\n * Supports both legacy format (live_) and new format (sk_live_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('sk_live_');\n}\n\n/**\n * Generates a unique cookie suffix based on the publishable key using SHA-1 hashing.\n * The suffix is base64-encoded and URL-safe (+ and / characters are replaced).\n *\n * @param publishableKey - The publishable key to generate suffix from.\n * @param subtle - The SubtleCrypto interface to use for hashing (defaults to globalThis.crypto.subtle).\n * @returns A promise that resolves to an 8-character URL-safe base64 string.\n */\nexport async function getCookieSuffix(\n publishableKey: string,\n subtle: SubtleCrypto = globalThis.crypto.subtle,\n): Promise<string> {\n const data = new TextEncoder().encode(publishableKey);\n const digest = await subtle.digest('sha-1', data);\n const stringDigest = String.fromCharCode(...new Uint8Array(digest));\n // Base 64 Encoding with URL and Filename Safe Alphabet: https://datatracker.ietf.org/doc/html/rfc4648#section-5\n return isomorphicBtoa(stringDigest).replace(/\\+/gi, '-').replace(/\\//gi, '_').substring(0, 8);\n}\n\n/**\n * Creates a suffixed cookie name by appending the cookie suffix to the base name.\n * Used to create unique cookie names based on the publishable key.\n *\n * @param cookieName - The base cookie name.\n * @param cookieSuffix - The suffix to append (typically generated by getCookieSuffix).\n * @returns The suffixed cookie name in format: `${cookieName}_${cookieSuffix}`.\n */\nexport const getSuffixedCookieName = (cookieName: string, cookieSuffix: string): string => {\n return `${cookieName}_${cookieSuffix}`;\n};\n"],"mappings":";;;;;;AAoBA,MAAM,8BAA8B;;AAGpC,MAAM,8BAA8B;;;;;AAMpC,MAAM,qCAAqC;;;;;;;AAQ3C,SAAgB,oBAAoB,aAA6B;AAK/D,QAAO,GAHL,mCAAmC,KAAK,YAAY,IACnD,YAAY,WAAW,SAAS,IAAIA,+CAA6B,MAAK,MAAK,YAAY,SAAS,EAAE,CAAC,GACzE,8BAA8B,8BACrCC,sCAAe,GAAG,YAAY,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BzD,SAAgB,uBAAuB,MAAc,aAA8B;AACjF,KAAI,eAAe,gCAAgC,YAAY,CAC7D,QAAO;CAET,MAAM,WAAW,KAAK,aAAa,CAAC,QAAQ,SAAS,GAAG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AiC;AACzF,QAAO,GAAG,WAAW,GAAG"}
@@ -22,6 +22,31 @@ type ParsePublishableKeyOptions = {
22
22
  * @returns A base64-encoded publishable key with appropriate prefix (pk_live_ or pk_test_).
23
23
  */
24
24
  declare function buildPublishableKey(frontendApi: string): string;
25
+ /**
26
+ * Derives a publishable key from the current hostname. Intended for multi-domain
27
+ * setups (e.g. custom domains on top of a default domain) where the correct key
28
+ * must be resolved per request.
29
+ *
30
+ * Pass the configured publishable key as `fallbackKey` so that development
31
+ * instances (pk_test_) are returned as-is instead of being incorrectly derived
32
+ * from the host (e.g. localhost).
33
+ *
34
+ * @example
35
+ * // React (use window.location.hostname, not window.location.host, to avoid including the port)
36
+ * <ClerkProvider publishableKey={publishableKeyFromHost(window.location.hostname, import.meta.env.VITE_CLERK_PUBLISHABLE_KEY)}>
37
+ *
38
+ * @example
39
+ * // Express (inside clerkMiddleware callback)
40
+ * // Validate req.hostname against a known allowlist before passing it in.
41
+ * // When `trust proxy` is enabled, req.hostname reads from X-Forwarded-Host
42
+ * // and can be spoofed if your proxy is not properly configured.
43
+ * const ALLOWED_HOSTS = ['domain-a.com', 'domain-b.com'];
44
+ * clerkMiddleware((req) => {
45
+ * if (!ALLOWED_HOSTS.includes(req.hostname)) throw new Error('Unknown host');
46
+ * return { publishableKey: publishableKeyFromHost(req.hostname, process.env.CLERK_PUBLISHABLE_KEY) };
47
+ * })
48
+ */
49
+ declare function publishableKeyFromHost(host: string, fallbackKey?: string): string;
25
50
  declare function parsePublishableKey(key: string | undefined, options: ParsePublishableKeyOptions & {
26
51
  fatal: true;
27
52
  }): PublishableKey;
@@ -99,5 +124,5 @@ declare function getCookieSuffix(publishableKey: string, subtle?: SubtleCrypto):
99
124
  */
100
125
  declare const getSuffixedCookieName: (cookieName: string, cookieSuffix: string) => string;
101
126
  //#endregion
102
- export { buildPublishableKey, createDevOrStagingUrlCache, getCookieSuffix, getSuffixedCookieName, isDevelopmentFromPublishableKey, isDevelopmentFromSecretKey, isProductionFromPublishableKey, isProductionFromSecretKey, isPublishableKey, parsePublishableKey };
127
+ export { buildPublishableKey, createDevOrStagingUrlCache, getCookieSuffix, getSuffixedCookieName, isDevelopmentFromPublishableKey, isDevelopmentFromSecretKey, isProductionFromPublishableKey, isProductionFromSecretKey, isPublishableKey, parsePublishableKey, publishableKeyFromHost };
103
128
  //# sourceMappingURL=keys.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"keys.d.mts","names":[],"sources":["../../src/keys.ts"],"sourcesContent":[],"mappings":";;;;;;;AAG8C,KAKzC,0BAAA,GAA0B;EA6Bf;EA4BA,KAAA,CAAA,EAAA,OAAA;EAIA;EA0EA,MAAA,CAAA,EAAA,MAAA;EA+BA;EAiCA,QAAA,CAAA,EAAA,MAAA;EAWA;EAWA,WAAA,CAAA,EAAA,OAAA;AAWhB,CAAA;AAYA;AAmBA;;;;;iBA1OgB,mBAAA;iBA4BA,mBAAA,mCAEL;;IACR;iBACa,mBAAA,oCAEJ,6BACT;;;;;;;iBAuEa,gBAAA;;;;;;;iBA+BA,0BAAA,CAAA;;;;;;;oCAUsB;;;;;;;;;iBAuBtB,+BAAA;;;;;;;;iBAWA,8BAAA;;;;;;;;iBAWA,0BAAA;;;;;;;;iBAWA,yBAAA;;;;;;;;;iBAYM,eAAA,kCAEZ,eACP;;;;;;;;;cAgBU"}
1
+ {"version":3,"file":"keys.d.mts","names":[],"sources":["../../src/keys.ts"],"sourcesContent":[],"mappings":";;;;;;;AAG8C,KAKzC,0BAAA,GAA0B;EA6Bf;EAgCA,KAAA,CAAA,EAAA,OAAA;EA+BA;EAIA,MAAA,CAAA,EAAA,MAAA;EA0EA;EA+BA,QAAA,CAAA,EAAA,MAAA;EAiCA;EAWA,WAAA,CAAA,EAAA,OAAA;AAWhB,CAAA;AAWA;AAYA;AAmBA;;;;iBA7QgB,mBAAA;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCA,sBAAA;iBA+BA,mBAAA,mCAEL;;IACR;iBACa,mBAAA,oCAEJ,6BACT;;;;;;;iBAuEa,gBAAA;;;;;;;iBA+BA,0BAAA,CAAA;;;;;;;oCAUsB;;;;;;;;;iBAuBtB,+BAAA;;;;;;;;iBAWA,8BAAA;;;;;;;;iBAWA,0BAAA;;;;;;;;iBAWA,yBAAA;;;;;;;;;iBAYM,eAAA,kCAEZ,eACP;;;;;;;;;cAgBU"}
@@ -22,6 +22,31 @@ type ParsePublishableKeyOptions = {
22
22
  * @returns A base64-encoded publishable key with appropriate prefix (pk_live_ or pk_test_).
23
23
  */
24
24
  declare function buildPublishableKey(frontendApi: string): string;
25
+ /**
26
+ * Derives a publishable key from the current hostname. Intended for multi-domain
27
+ * setups (e.g. custom domains on top of a default domain) where the correct key
28
+ * must be resolved per request.
29
+ *
30
+ * Pass the configured publishable key as `fallbackKey` so that development
31
+ * instances (pk_test_) are returned as-is instead of being incorrectly derived
32
+ * from the host (e.g. localhost).
33
+ *
34
+ * @example
35
+ * // React (use window.location.hostname, not window.location.host, to avoid including the port)
36
+ * <ClerkProvider publishableKey={publishableKeyFromHost(window.location.hostname, import.meta.env.VITE_CLERK_PUBLISHABLE_KEY)}>
37
+ *
38
+ * @example
39
+ * // Express (inside clerkMiddleware callback)
40
+ * // Validate req.hostname against a known allowlist before passing it in.
41
+ * // When `trust proxy` is enabled, req.hostname reads from X-Forwarded-Host
42
+ * // and can be spoofed if your proxy is not properly configured.
43
+ * const ALLOWED_HOSTS = ['domain-a.com', 'domain-b.com'];
44
+ * clerkMiddleware((req) => {
45
+ * if (!ALLOWED_HOSTS.includes(req.hostname)) throw new Error('Unknown host');
46
+ * return { publishableKey: publishableKeyFromHost(req.hostname, process.env.CLERK_PUBLISHABLE_KEY) };
47
+ * })
48
+ */
49
+ declare function publishableKeyFromHost(host: string, fallbackKey?: string): string;
25
50
  declare function parsePublishableKey(key: string | undefined, options: ParsePublishableKeyOptions & {
26
51
  fatal: true;
27
52
  }): PublishableKey;
@@ -99,5 +124,5 @@ declare function getCookieSuffix(publishableKey: string, subtle?: SubtleCrypto):
99
124
  */
100
125
  declare const getSuffixedCookieName: (cookieName: string, cookieSuffix: string) => string;
101
126
  //#endregion
102
- export { buildPublishableKey, createDevOrStagingUrlCache, getCookieSuffix, getSuffixedCookieName, isDevelopmentFromPublishableKey, isDevelopmentFromSecretKey, isProductionFromPublishableKey, isProductionFromSecretKey, isPublishableKey, parsePublishableKey };
127
+ export { buildPublishableKey, createDevOrStagingUrlCache, getCookieSuffix, getSuffixedCookieName, isDevelopmentFromPublishableKey, isDevelopmentFromSecretKey, isProductionFromPublishableKey, isProductionFromSecretKey, isPublishableKey, parsePublishableKey, publishableKeyFromHost };
103
128
  //# sourceMappingURL=keys.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"keys.d.ts","names":[],"sources":["../../src/keys.ts"],"sourcesContent":[],"mappings":";;;;;;;AAG8C,KAKzC,0BAAA,GAA0B;EA6Bf;EA4BA,KAAA,CAAA,EAAA,OAAA;EAIA;EA0EA,MAAA,CAAA,EAAA,MAAA;EA+BA;EAiCA,QAAA,CAAA,EAAA,MAAA;EAWA;EAWA,WAAA,CAAA,EAAA,OAAA;AAWhB,CAAA;AAYA;AAmBA;;;;;iBA1OgB,mBAAA;iBA4BA,mBAAA,mCAEL;;IACR;iBACa,mBAAA,oCAEJ,6BACT;;;;;;;iBAuEa,gBAAA;;;;;;;iBA+BA,0BAAA,CAAA;;;;;;;oCAUsB;;;;;;;;;iBAuBtB,+BAAA;;;;;;;;iBAWA,8BAAA;;;;;;;;iBAWA,0BAAA;;;;;;;;iBAWA,yBAAA;;;;;;;;;iBAYM,eAAA,kCAEZ,eACP;;;;;;;;;cAgBU"}
1
+ {"version":3,"file":"keys.d.ts","names":[],"sources":["../../src/keys.ts"],"sourcesContent":[],"mappings":";;;;;;;AAG8C,KAKzC,0BAAA,GAA0B;EA6Bf;EAgCA,KAAA,CAAA,EAAA,OAAA;EA+BA;EAIA,MAAA,CAAA,EAAA,MAAA;EA0EA;EA+BA,QAAA,CAAA,EAAA,MAAA;EAiCA;EAWA,WAAA,CAAA,EAAA,OAAA;AAWhB,CAAA;AAWA;AAYA;AAmBA;;;;iBA7QgB,mBAAA;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCA,sBAAA;iBA+BA,mBAAA,mCAEL;;IACR;iBACa,mBAAA,oCAEJ,6BACT;;;;;;;iBAuEa,gBAAA;;;;;;;iBA+BA,0BAAA,CAAA;;;;;;;oCAUsB;;;;;;;;;iBAuBtB,+BAAA;;;;;;;;iBAWA,8BAAA;;;;;;;;iBAWA,0BAAA;;;;;;;;iBAWA,yBAAA;;;;;;;;;iBAYM,eAAA,kCAEZ,eACP;;;;;;;;;cAgBU"}
@@ -1,7 +1,7 @@
1
1
  require('./constants-WYhx_umW.js');
2
2
  require('./isomorphicAtob-Hkpnx2p8.js');
3
3
  require('./isomorphicBtoa-_pSA92Q9.js');
4
- const require_keys = require('./keys-BI9hmfja.js');
4
+ const require_keys = require('./keys-D5ahg2Gn.js');
5
5
 
6
6
  exports.buildPublishableKey = require_keys.buildPublishableKey;
7
7
  exports.createDevOrStagingUrlCache = require_keys.createDevOrStagingUrlCache;
@@ -12,4 +12,5 @@ exports.isDevelopmentFromSecretKey = require_keys.isDevelopmentFromSecretKey;
12
12
  exports.isProductionFromPublishableKey = require_keys.isProductionFromPublishableKey;
13
13
  exports.isProductionFromSecretKey = require_keys.isProductionFromSecretKey;
14
14
  exports.isPublishableKey = require_keys.isPublishableKey;
15
- exports.parsePublishableKey = require_keys.parsePublishableKey;
15
+ exports.parsePublishableKey = require_keys.parsePublishableKey;
16
+ exports.publishableKeyFromHost = require_keys.publishableKeyFromHost;
@@ -1,6 +1,6 @@
1
1
  import "./constants-Bta24VLk.mjs";
2
2
  import "./isomorphicAtob-CoF80qYz.mjs";
3
3
  import "./isomorphicBtoa-DWmLcIHi.mjs";
4
- import { a as isDevelopmentFromPublishableKey, c as isProductionFromSecretKey, i as getSuffixedCookieName, l as isPublishableKey, n as createDevOrStagingUrlCache, o as isDevelopmentFromSecretKey, r as getCookieSuffix, s as isProductionFromPublishableKey, t as buildPublishableKey, u as parsePublishableKey } from "./keys-DuxzP8MU.mjs";
4
+ import { a as isDevelopmentFromPublishableKey, c as isProductionFromSecretKey, d as publishableKeyFromHost, i as getSuffixedCookieName, l as isPublishableKey, n as createDevOrStagingUrlCache, o as isDevelopmentFromSecretKey, r as getCookieSuffix, s as isProductionFromPublishableKey, t as buildPublishableKey, u as parsePublishableKey } from "./keys-BeVKH43u.mjs";
5
5
 
6
- export { buildPublishableKey, createDevOrStagingUrlCache, getCookieSuffix, getSuffixedCookieName, isDevelopmentFromPublishableKey, isDevelopmentFromSecretKey, isProductionFromPublishableKey, isProductionFromSecretKey, isPublishableKey, parsePublishableKey };
6
+ export { buildPublishableKey, createDevOrStagingUrlCache, getCookieSuffix, getSuffixedCookieName, isDevelopmentFromPublishableKey, isDevelopmentFromSecretKey, isProductionFromPublishableKey, isProductionFromSecretKey, isPublishableKey, parsePublishableKey, publishableKeyFromHost };
@@ -1,7 +1,7 @@
1
1
  require('./constants-WYhx_umW.js');
2
2
  require('./isomorphicAtob-Hkpnx2p8.js');
3
3
  require('./isomorphicBtoa-_pSA92Q9.js');
4
- const require_keys = require('./keys-BI9hmfja.js');
4
+ const require_keys = require('./keys-D5ahg2Gn.js');
5
5
  const require_clerkRuntimeError = require('./clerkRuntimeError-CaS4sM5w.js');
6
6
  const require_error = require('./error-BkPoOeMv.js');
7
7
  require('./retry-DGCmqlcR.js');
@@ -9,7 +9,7 @@ const require_loadScript = require('./loadScript-BnB9d_IW.js');
9
9
  const require_proxy = require('./proxy-DahrnOq8.js');
10
10
  require('./instance-C1LlVxIp.js');
11
11
  const require_url = require('./url-sAcxbiir.js');
12
- const require_versionSelector = require('./versionSelector-CY7koW8Z.js');
12
+ const require_versionSelector = require('./versionSelector-C1hK82gB.js');
13
13
 
14
14
  //#region src/loadClerkJsScript.ts
15
15
  const { isDevOrStagingUrl } = require_keys.createDevOrStagingUrlCache();
@@ -146,7 +146,7 @@ const clerkUIScriptUrl = (opts) => {
146
146
  publishableKey,
147
147
  proxyUrl,
148
148
  domain
149
- })}/npm/@clerk/ui@${require_versionSelector.versionSelector(__internal_clerkUIVersion, "1.6.5-snapshot.v20260423044224")}/dist/ui.browser.js`;
149
+ })}/npm/@clerk/ui@${require_versionSelector.versionSelector(__internal_clerkUIVersion, "1.6.6")}/dist/ui.browser.js`;
150
150
  };
151
151
  const buildClerkJSScriptAttributes = (options) => {
152
152
  const obj = {};
@@ -1 +1 @@
1
- {"version":3,"file":"loadClerkJsScript.js","names":["createDevOrStagingUrlCache","buildErrorThrower","ClerkRuntimeError","versionSelector","obj: Record<string, string>","isValidProxyUrl","proxyUrlToAbsoluteURL","parsePublishableKey","addClerkPrefix","timeoutId","pollInterval"],"sources":["../../src/loadClerkJsScript.ts"],"sourcesContent":["import { buildErrorThrower, ClerkRuntimeError } from './error';\nimport { createDevOrStagingUrlCache, parsePublishableKey } from './keys';\nimport { loadScript } from './loadScript';\nimport { isValidProxyUrl, proxyUrlToAbsoluteURL } from './proxy';\nimport type { SDKMetadata } from './types';\nimport { addClerkPrefix } from './url';\nimport { versionSelector } from './versionSelector';\n\nconst { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n\nconst errorThrower = buildErrorThrower({ packageName: '@clerk/shared' });\n\nexport type LoadClerkJSScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkJSUrl?: string;\n /** @internal */\n __internal_clerkJSVersion?: string;\n sdkMetadata?: SDKMetadata;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n /**\n * Timeout in milliseconds to wait for clerk-js to load before considering it failed.\n *\n * @default 15000 (15 seconds)\n */\n scriptLoadTimeout?: number;\n};\n\n/**\n * @deprecated Use `LoadClerkJSScriptOptions` instead. This alias will be removed in a future major version.\n */\nexport type LoadClerkJsScriptOptions = LoadClerkJSScriptOptions;\n\nexport type LoadClerkUIScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkUIUrl?: string;\n /** @internal */\n __internal_clerkUIVersion?: string;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n scriptLoadTimeout?: number;\n};\n\n/**\n * Validates that window.Clerk exists and is properly initialized.\n * This ensures we don't have false positives where the script loads but Clerk is malformed.\n *\n * @returns `true` if window.Clerk exists and has the expected structure with a load method.\n */\nfunction isClerkGlobalProperlyLoaded(prop: 'Clerk' | '__internal_ClerkUICtor'): boolean {\n if (typeof window === 'undefined' || !(window as any)[prop]) {\n return false;\n }\n\n // Basic validation that window.Clerk has the expected structure\n const val = (window as any)[prop];\n return !!val;\n}\nconst isClerkProperlyLoaded = () => isClerkGlobalProperlyLoaded('Clerk');\nconst isClerkUIProperlyLoaded = () => isClerkGlobalProperlyLoaded('__internal_ClerkUICtor');\n\n/**\n * Checks if an existing script has a request error using Performance API.\n *\n * @param scriptUrl - The URL of the script to check.\n * @returns True if the script has failed to load due to a network/HTTP error.\n */\nfunction hasScriptRequestError(scriptUrl: string): boolean {\n if (typeof window === 'undefined' || !window.performance) {\n return false;\n }\n\n const entries = performance.getEntriesByName(scriptUrl, 'resource') as PerformanceResourceTiming[];\n\n if (entries.length === 0) {\n return false;\n }\n\n const scriptEntry = entries[entries.length - 1];\n\n // transferSize === 0 with responseEnd === 0 indicates network failure\n // transferSize === 0 with responseEnd > 0 might be a 4xx/5xx error or blocked request\n if (scriptEntry.transferSize === 0 && scriptEntry.decodedBodySize === 0) {\n // If there was no response at all, it's definitely an error\n if (scriptEntry.responseEnd === 0) {\n return true;\n }\n // If we got a response but no content, likely an HTTP error (4xx/5xx)\n if (scriptEntry.responseEnd > 0 && scriptEntry.responseStart > 0) {\n return true;\n }\n\n if ('responseStatus' in scriptEntry) {\n const status = (scriptEntry as any).responseStatus;\n if (status >= 400) {\n return true;\n }\n if (scriptEntry.responseStatus === 0) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Hotloads the Clerk JS script with robust failure detection.\n *\n * Uses a timeout-based approach to ensure absolute certainty about load success/failure.\n * If the script fails to load within the timeout period, or loads but doesn't create\n * a proper Clerk instance, the promise rejects with an error.\n *\n * @param opts - The options used to build the Clerk JS script URL and load the script.\n * Must include a `publishableKey` if no existing script is found.\n * @returns Promise that resolves with null if Clerk loads successfully, or rejects with an error.\n *\n * @example\n * ```typescript\n * try {\n * await loadClerkJsScript({ publishableKey: 'pk_test_...' });\n * console.log('Clerk loaded successfully');\n * } catch (error) {\n * console.error('Failed to load Clerk:', error.message);\n * }\n * ```\n */\nexport const loadClerkJSScript = async (opts?: LoadClerkJSScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk JS' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_js',\n cause: error,\n });\n\n if (isClerkProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkJSScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-js-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkJSScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const loadClerkUIScript = async (opts?: LoadClerkUIScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk UI' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_ui',\n cause: error,\n });\n\n if (isClerkUIProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkUIScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-ui-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkUIScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const clerkJSScriptUrl = (opts: LoadClerkJSScriptOptions) => {\n const { __internal_clerkJSUrl, __internal_clerkJSVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkJSUrl) {\n return __internal_clerkJSUrl;\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n const version = versionSelector(__internal_clerkJSVersion);\n return `https://${scriptHost}/npm/@clerk/clerk-js@${version}/dist/clerk.browser.js`;\n};\n\nexport const clerkUIScriptUrl = (opts: LoadClerkUIScriptOptions) => {\n const { __internal_clerkUIUrl, __internal_clerkUIVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkUIUrl) {\n return __internal_clerkUIUrl;\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n const version = versionSelector(__internal_clerkUIVersion, UI_PACKAGE_VERSION);\n return `https://${scriptHost}/npm/@clerk/ui@${version}/dist/ui.browser.js`;\n};\n\nexport const buildClerkJSScriptAttributes = (options: LoadClerkJSScriptOptions) => {\n const obj: Record<string, string> = {};\n\n if (options.publishableKey) {\n obj['data-clerk-publishable-key'] = options.publishableKey;\n }\n\n if (options.proxyUrl) {\n obj['data-clerk-proxy-url'] = options.proxyUrl;\n }\n\n if (options.domain) {\n obj['data-clerk-domain'] = options.domain;\n }\n\n if (options.nonce) {\n obj.nonce = options.nonce;\n }\n\n return obj;\n};\n\nexport const buildClerkUIScriptAttributes = (options: LoadClerkUIScriptOptions) => {\n // TODO @nikos do we need this?\n return buildClerkJSScriptAttributes(options);\n};\n\nconst applyAttributesToScript = (attributes: Record<string, string>) => (script: HTMLScriptElement) => {\n for (const attribute in attributes) {\n script.setAttribute(attribute, attributes[attribute]);\n }\n};\n\nexport const buildScriptHost = (opts: { publishableKey: string; proxyUrl?: string; domain?: string }) => {\n const { proxyUrl, domain, publishableKey } = opts;\n\n if (!!proxyUrl && isValidProxyUrl(proxyUrl)) {\n return proxyUrlToAbsoluteURL(proxyUrl).replace(/http(s)?:\\/\\//, '');\n } else if (domain && !isDevOrStagingUrl(parsePublishableKey(publishableKey)?.frontendApi || '')) {\n return addClerkPrefix(domain);\n } else {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n};\n\nfunction waitForPredicateWithTimeout(\n timeoutMs: number,\n predicate: () => boolean,\n rejectWith: Error,\n existingScript?: HTMLScriptElement,\n): Promise<HTMLScriptElement | null> {\n return new Promise((resolve, reject) => {\n let resolved = false;\n\n const cleanup = (timeoutId: ReturnType<typeof setTimeout>, pollInterval: ReturnType<typeof setInterval>) => {\n clearTimeout(timeoutId);\n clearInterval(pollInterval);\n };\n\n // Bail out early if the script fails to load, instead of waiting for the entire timeout\n existingScript?.addEventListener('error', () => {\n cleanup(timeoutId, pollInterval);\n reject(rejectWith);\n });\n\n const checkAndResolve = () => {\n if (resolved) {\n return;\n }\n\n if (predicate()) {\n resolved = true;\n cleanup(timeoutId, pollInterval);\n resolve(null);\n }\n };\n\n const handleTimeout = () => {\n if (resolved) {\n return;\n }\n\n resolved = true;\n cleanup(timeoutId, pollInterval);\n\n if (!predicate()) {\n reject(rejectWith);\n } else {\n resolve(null);\n }\n };\n\n const timeoutId = setTimeout(handleTimeout, timeoutMs);\n\n checkAndResolve();\n\n const pollInterval = setInterval(() => {\n if (resolved) {\n clearInterval(pollInterval);\n return;\n }\n checkAndResolve();\n }, 100);\n });\n}\n\nexport function setClerkJSLoadingErrorPackageName(packageName: string) {\n errorThrower.setPackageName({ packageName });\n}\n\n/**\n * @deprecated Use `loadClerkJSScript` instead. This alias will be removed in a future major version.\n */\nexport const loadClerkJsScript = loadClerkJSScript;\n\n/**\n * @deprecated Use `clerkJSScriptUrl` instead. This alias will be removed in a future major version.\n */\nexport const clerkJsScriptUrl = clerkJSScriptUrl;\n\n/**\n * @deprecated Use `buildClerkJSScriptAttributes` instead. This alias will be removed in a future major version.\n */\nexport const buildClerkJsScriptAttributes = buildClerkJSScriptAttributes;\n\n/**\n * @deprecated Use `setClerkJSLoadingErrorPackageName` instead. This alias will be removed in a future major version.\n */\nexport const setClerkJsLoadingErrorPackageName = setClerkJSLoadingErrorPackageName;\n"],"mappings":";;;;;;;;;;;;;;AAQA,MAAM,EAAE,sBAAsBA,yCAA4B;AAE1D,MAAM,eAAeC,gCAAkB,EAAE,aAAa,iBAAiB,CAAC;;;;;;;AA2CxE,SAAS,4BAA4B,MAAmD;AACtF,KAAI,OAAO,WAAW,eAAe,CAAE,OAAe,MACpD,QAAO;AAKT,QAAO,CAAC,CADK,OAAe;;AAG9B,MAAM,8BAA8B,4BAA4B,QAAQ;AACxE,MAAM,gCAAgC,4BAA4B,yBAAyB;;;;;;;AAQ3F,SAAS,sBAAsB,WAA4B;AACzD,KAAI,OAAO,WAAW,eAAe,CAAC,OAAO,YAC3C,QAAO;CAGT,MAAM,UAAU,YAAY,iBAAiB,WAAW,WAAW;AAEnE,KAAI,QAAQ,WAAW,EACrB,QAAO;CAGT,MAAM,cAAc,QAAQ,QAAQ,SAAS;AAI7C,KAAI,YAAY,iBAAiB,KAAK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KhC,MAAa,+BAA+B;;;;AAK5C,MAAa,oCAAoC"}
1
+ {"version":3,"file":"loadClerkJsScript.js","names":["createDevOrStagingUrlCache","buildErrorThrower","ClerkRuntimeError","versionSelector","obj: Record<string, string>","isValidProxyUrl","proxyUrlToAbsoluteURL","parsePublishableKey","addClerkPrefix","timeoutId","pollInterval"],"sources":["../../src/loadClerkJsScript.ts"],"sourcesContent":["import { buildErrorThrower, ClerkRuntimeError } from './error';\nimport { createDevOrStagingUrlCache, parsePublishableKey } from './keys';\nimport { loadScript } from './loadScript';\nimport { isValidProxyUrl, proxyUrlToAbsoluteURL } from './proxy';\nimport type { SDKMetadata } from './types';\nimport { addClerkPrefix } from './url';\nimport { versionSelector } from './versionSelector';\n\nconst { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n\nconst errorThrower = buildErrorThrower({ packageName: '@clerk/shared' });\n\nexport type LoadClerkJSScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkJSUrl?: string;\n /** @internal */\n __internal_clerkJSVersion?: string;\n sdkMetadata?: SDKMetadata;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n /**\n * Timeout in milliseconds to wait for clerk-js to load before considering it failed.\n *\n * @default 15000 (15 seconds)\n */\n scriptLoadTimeout?: number;\n};\n\n/**\n * @deprecated Use `LoadClerkJSScriptOptions` instead. This alias will be removed in a future major version.\n */\nexport type LoadClerkJsScriptOptions = LoadClerkJSScriptOptions;\n\nexport type LoadClerkUIScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkUIUrl?: string;\n /** @internal */\n __internal_clerkUIVersion?: string;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n scriptLoadTimeout?: number;\n};\n\n/**\n * Validates that window.Clerk exists and is properly initialized.\n * This ensures we don't have false positives where the script loads but Clerk is malformed.\n *\n * @returns `true` if window.Clerk exists and has the expected structure with a load method.\n */\nfunction isClerkGlobalProperlyLoaded(prop: 'Clerk' | '__internal_ClerkUICtor'): boolean {\n if (typeof window === 'undefined' || !(window as any)[prop]) {\n return false;\n }\n\n // Basic validation that window.Clerk has the expected structure\n const val = (window as any)[prop];\n return !!val;\n}\nconst isClerkProperlyLoaded = () => isClerkGlobalProperlyLoaded('Clerk');\nconst isClerkUIProperlyLoaded = () => isClerkGlobalProperlyLoaded('__internal_ClerkUICtor');\n\n/**\n * Checks if an existing script has a request error using Performance API.\n *\n * @param scriptUrl - The URL of the script to check.\n * @returns True if the script has failed to load due to a network/HTTP error.\n */\nfunction hasScriptRequestError(scriptUrl: string): boolean {\n if (typeof window === 'undefined' || !window.performance) {\n return false;\n }\n\n const entries = performance.getEntriesByName(scriptUrl, 'resource') as PerformanceResourceTiming[];\n\n if (entries.length === 0) {\n return false;\n }\n\n const scriptEntry = entries[entries.length - 1];\n\n // transferSize === 0 with responseEnd === 0 indicates network failure\n // transferSize === 0 with responseEnd > 0 might be a 4xx/5xx error or blocked request\n if (scriptEntry.transferSize === 0 && scriptEntry.decodedBodySize === 0) {\n // If there was no response at all, it's definitely an error\n if (scriptEntry.responseEnd === 0) {\n return true;\n }\n // If we got a response but no content, likely an HTTP error (4xx/5xx)\n if (scriptEntry.responseEnd > 0 && scriptEntry.responseStart > 0) {\n return true;\n }\n\n if ('responseStatus' in scriptEntry) {\n const status = (scriptEntry as any).responseStatus;\n if (status >= 400) {\n return true;\n }\n if (scriptEntry.responseStatus === 0) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Hotloads the Clerk JS script with robust failure detection.\n *\n * Uses a timeout-based approach to ensure absolute certainty about load success/failure.\n * If the script fails to load within the timeout period, or loads but doesn't create\n * a proper Clerk instance, the promise rejects with an error.\n *\n * @param opts - The options used to build the Clerk JS script URL and load the script.\n * Must include a `publishableKey` if no existing script is found.\n * @returns Promise that resolves with null if Clerk loads successfully, or rejects with an error.\n *\n * @example\n * ```typescript\n * try {\n * await loadClerkJsScript({ publishableKey: 'pk_test_...' });\n * console.log('Clerk loaded successfully');\n * } catch (error) {\n * console.error('Failed to load Clerk:', error.message);\n * }\n * ```\n */\nexport const loadClerkJSScript = async (opts?: LoadClerkJSScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk JS' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_js',\n cause: error,\n });\n\n if (isClerkProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkJSScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-js-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkJSScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const loadClerkUIScript = async (opts?: LoadClerkUIScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk UI' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_ui',\n cause: error,\n });\n\n if (isClerkUIProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkUIScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-ui-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkUIScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const clerkJSScriptUrl = (opts: LoadClerkJSScriptOptions) => {\n const { __internal_clerkJSUrl, __internal_clerkJSVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkJSUrl) {\n return __internal_clerkJSUrl;\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n const version = versionSelector(__internal_clerkJSVersion);\n return `https://${scriptHost}/npm/@clerk/clerk-js@${version}/dist/clerk.browser.js`;\n};\n\nexport const clerkUIScriptUrl = (opts: LoadClerkUIScriptOptions) => {\n const { __internal_clerkUIUrl, __internal_clerkUIVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkUIUrl) {\n return __internal_clerkUIUrl;\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n const version = versionSelector(__internal_clerkUIVersion, UI_PACKAGE_VERSION);\n return `https://${scriptHost}/npm/@clerk/ui@${version}/dist/ui.browser.js`;\n};\n\nexport const buildClerkJSScriptAttributes = (options: LoadClerkJSScriptOptions) => {\n const obj: Record<string, string> = {};\n\n if (options.publishableKey) {\n obj['data-clerk-publishable-key'] = options.publishableKey;\n }\n\n if (options.proxyUrl) {\n obj['data-clerk-proxy-url'] = options.proxyUrl;\n }\n\n if (options.domain) {\n obj['data-clerk-domain'] = options.domain;\n }\n\n if (options.nonce) {\n obj.nonce = options.nonce;\n }\n\n return obj;\n};\n\nexport const buildClerkUIScriptAttributes = (options: LoadClerkUIScriptOptions) => {\n // TODO @nikos do we need this?\n return buildClerkJSScriptAttributes(options);\n};\n\nconst applyAttributesToScript = (attributes: Record<string, string>) => (script: HTMLScriptElement) => {\n for (const attribute in attributes) {\n script.setAttribute(attribute, attributes[attribute]);\n }\n};\n\nexport const buildScriptHost = (opts: { publishableKey: string; proxyUrl?: string; domain?: string }) => {\n const { proxyUrl, domain, publishableKey } = opts;\n\n if (!!proxyUrl && isValidProxyUrl(proxyUrl)) {\n return proxyUrlToAbsoluteURL(proxyUrl).replace(/http(s)?:\\/\\//, '');\n } else if (domain && !isDevOrStagingUrl(parsePublishableKey(publishableKey)?.frontendApi || '')) {\n return addClerkPrefix(domain);\n } else {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n};\n\nfunction waitForPredicateWithTimeout(\n timeoutMs: number,\n predicate: () => boolean,\n rejectWith: Error,\n existingScript?: HTMLScriptElement,\n): Promise<HTMLScriptElement | null> {\n return new Promise((resolve, reject) => {\n let resolved = false;\n\n const cleanup = (timeoutId: ReturnType<typeof setTimeout>, pollInterval: ReturnType<typeof setInterval>) => {\n clearTimeout(timeoutId);\n clearInterval(pollInterval);\n };\n\n // Bail out early if the script fails to load, instead of waiting for the entire timeout\n existingScript?.addEventListener('error', () => {\n cleanup(timeoutId, pollInterval);\n reject(rejectWith);\n });\n\n const checkAndResolve = () => {\n if (resolved) {\n return;\n }\n\n if (predicate()) {\n resolved = true;\n cleanup(timeoutId, pollInterval);\n resolve(null);\n }\n };\n\n const handleTimeout = () => {\n if (resolved) {\n return;\n }\n\n resolved = true;\n cleanup(timeoutId, pollInterval);\n\n if (!predicate()) {\n reject(rejectWith);\n } else {\n resolve(null);\n }\n };\n\n const timeoutId = setTimeout(handleTimeout, timeoutMs);\n\n checkAndResolve();\n\n const pollInterval = setInterval(() => {\n if (resolved) {\n clearInterval(pollInterval);\n return;\n }\n checkAndResolve();\n }, 100);\n });\n}\n\nexport function setClerkJSLoadingErrorPackageName(packageName: string) {\n errorThrower.setPackageName({ packageName });\n}\n\n/**\n * @deprecated Use `loadClerkJSScript` instead. This alias will be removed in a future major version.\n */\nexport const loadClerkJsScript = loadClerkJSScript;\n\n/**\n * @deprecated Use `clerkJSScriptUrl` instead. This alias will be removed in a future major version.\n */\nexport const clerkJsScriptUrl = clerkJSScriptUrl;\n\n/**\n * @deprecated Use `buildClerkJSScriptAttributes` instead. This alias will be removed in a future major version.\n */\nexport const buildClerkJsScriptAttributes = buildClerkJSScriptAttributes;\n\n/**\n * @deprecated Use `setClerkJSLoadingErrorPackageName` instead. This alias will be removed in a future major version.\n */\nexport const setClerkJsLoadingErrorPackageName = setClerkJSLoadingErrorPackageName;\n"],"mappings":";;;;;;;;;;;;;;AAQA,MAAM,EAAE,sBAAsBA,yCAA4B;AAE1D,MAAM,eAAeC,gCAAkB,EAAE,aAAa,iBAAiB,CAAC;;;;;;;AA2CxE,SAAS,4BAA4B,MAAmD;AACtF,KAAI,OAAO,WAAW,eAAe,CAAE,OAAe,MACpD,QAAO;AAKT,QAAO,CAAC,CADK,OAAe;;AAG9B,MAAM,8BAA8B,4BAA4B,QAAQ;AACxE,MAAM,gCAAgC,4BAA4B,yBAAyB;;;;;;;AAQ3F,SAAS,sBAAsB,WAA4B;AACzD,KAAI,OAAO,WAAW,eAAe,CAAC,OAAO,YAC3C,QAAO;CAGT,MAAM,UAAU,YAAY,iBAAiB,WAAW,WAAW;AAEnE,KAAI,QAAQ,WAAW,EACrB,QAAO;CAGT,MAAM,cAAc,QAAQ,QAAQ,SAAS;AAI7C,KAAI,YAAY,iBAAiB,KAAK,YAAY,oBAAoB,GAAG;AAEvE,MAAI,YAAY,gBAAgB,EAC9B,QAAO;AAGT,MAAI,YAAY,cAAc,KAAK,YAAY,gBAAgB,EAC7D,QAAO;AAGT,MAAI,oBAAoB,aAAa;AAEnC,OADgB,YAAoB,kBACtB,IACZ,QAAO;AAET,OAAI,YAAY,mBAAmB,EACjC,QAAO;;;AAKb,QAAO;;;;;;;;;;;;;;;;;;;;;;;AAwBT,MAAa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