@clerk/shared 4.25.1-canary.v20260708195640 → 4.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/loadClerkJsScript.js +1 -1
- package/dist/loadClerkJsScript.js.map +1 -1
- package/dist/loadClerkJsScript.mjs +1 -1
- package/dist/loadClerkJsScript.mjs.map +1 -1
- package/dist/pathMatcher.d.mts +12 -0
- package/dist/pathMatcher.d.ts +12 -0
- package/dist/pathMatcher.js +4 -0
- package/dist/pathMatcher.js.map +1 -1
- package/dist/pathMatcher.mjs +4 -0
- package/dist/pathMatcher.mjs.map +1 -1
- package/dist/types/signUpCommon.d.mts +10 -1
- package/dist/types/signUpCommon.d.ts +10 -1
- package/dist/versionSelector.js +1 -1
- package/dist/versionSelector.js.map +1 -1
- package/dist/versionSelector.mjs +1 -1
- package/dist/versionSelector.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -140,7 +140,7 @@ const clerkJSScriptUrl = (opts) => {
|
|
|
140
140
|
const clerkUIScriptUrl = (opts) => {
|
|
141
141
|
const { __internal_clerkUIUrl, __internal_clerkUIVersion, proxyUrl, domain, publishableKey } = opts;
|
|
142
142
|
if (__internal_clerkUIUrl) return __internal_clerkUIUrl;
|
|
143
|
-
const version = require_versionSelector.versionSelector(__internal_clerkUIVersion, "1.25.1
|
|
143
|
+
const version = require_versionSelector.versionSelector(__internal_clerkUIVersion, "1.25.1");
|
|
144
144
|
if (proxyUrl && require_proxy.isProxyUrlRelative(proxyUrl)) return buildRelativeProxyScriptUrl(proxyUrl, "ui", version, "ui.browser.js");
|
|
145
145
|
return `https://${buildScriptHost({
|
|
146
146
|
publishableKey,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadClerkJsScript.js","names":["createDevOrStagingUrlCache","buildErrorThrower","ClerkRuntimeError","versionSelector","isProxyUrlRelative","isValidProxyUrl","proxyUrlToAbsoluteURL","parsePublishableKey","addClerkPrefix"],"sources":["../src/loadClerkJsScript.ts"],"sourcesContent":["import { buildErrorThrower, ClerkRuntimeError } from './error';\nimport { createDevOrStagingUrlCache, parsePublishableKey } from './keys';\nimport { loadScript } from './loadScript';\nimport { isProxyUrlRelative, 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 version = versionSelector(__internal_clerkJSVersion);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'clerk-js', version, 'clerk.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\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 version = versionSelector(__internal_clerkUIVersion, UI_PACKAGE_VERSION);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'ui', version, 'ui.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\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\nconst stripTrailingSlashes = (value: string) => {\n while (value.endsWith('/')) {\n value = value.slice(0, -1);\n }\n\n return value;\n};\n\nconst buildRelativeProxyScriptUrl = (proxyUrl: string, packageName: string, version: string, fileName: string) => {\n return `${stripTrailingSlashes(proxyUrl)}/npm/@clerk/${packageName}@${version}/dist/${fileName}`;\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 const resolvedProxyUrl = proxyUrlToAbsoluteURL(proxyUrl);\n\n if (isProxyUrlRelative(resolvedProxyUrl)) {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n\n return resolvedProxyUrl.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,wCAA2B;AAEzD,MAAM,eAAeC,gCAAkB,EAAE,aAAa,gBAAgB,CAAC;;;;;;;AA2CvE,SAAS,4BAA4B,MAAmD;CACtF,IAAI,OAAO,WAAW,eAAe,CAAE,OAAe,OACpD,OAAO;CAKT,OAAO,CAAC,CADK,OAAe;AAE9B;AACA,MAAM,8BAA8B,4BAA4B,OAAO;AACvE,MAAM,gCAAgC,4BAA4B,wBAAwB;;;;;;;AAQ1F,SAAS,sBAAsB,WAA4B;CACzD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,aAC3C,OAAO;CAGT,MAAM,UAAU,YAAY,iBAAiB,WAAW,UAAU;CAElE,IAAI,QAAQ,WAAW,GACrB,OAAO;CAGT,MAAM,cAAc,QAAQ,QAAQ,SAAS;CAI7C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MAAM,WAAW,WAA0C,iBAAiD;GAC1G,aAAa,SAAS;GACtB,cAAc,YAAY;EAC5B;EAGA,gBAAgB,iBAAiB,eAAe;GAC9C,QAAQ,WAAW,YAAY;GAC/B,OAAO,UAAU;EACnB,CAAC;EAED,MAAM,wBAAwB;GAC5B,IAAI,UACF;GAGF,IAAI,UAAU,GAAG;IACf,WAAW;IACX,QAAQ,WAAW,YAAY;IAC/B,QAAQ,IAAI;GACd;EACF;EAEA,MAAM,sBAAsB;GAC1B,IAAI,UACF;GAGF,WAAW;GACX,QAAQ,WAAW,YAAY;GAE/B,IAAI,CAAC,UAAU,GACb,OAAO,UAAU;QAEjB,QAAQ,IAAI;EAEhB;EAEA,MAAM,YAAY,WAAW,eAAe,SAAS;EAErD,gBAAgB;EAEhB,MAAM,eAAe,kBAAkB;GACrC,IAAI,UAAU;IACZ,cAAc,YAAY;IAC1B;GACF;GACA,gBAAgB;EAClB,GAAG,GAAG;CACR,CAAC;AACH;AAEA,SAAgB,kCAAkC,aAAqB;CACrE,aAAa,eAAe,EAAE,YAAY,CAAC;AAC7C;;;;AAKA,MAAa,oBAAoB;;;;AAKjC,MAAa,mBAAmB;;;;AAKhC,MAAa,+BAA+B;;;;AAK5C,MAAa,oCAAoC"}
|
|
1
|
+
{"version":3,"file":"loadClerkJsScript.js","names":["createDevOrStagingUrlCache","buildErrorThrower","ClerkRuntimeError","versionSelector","isProxyUrlRelative","isValidProxyUrl","proxyUrlToAbsoluteURL","parsePublishableKey","addClerkPrefix"],"sources":["../src/loadClerkJsScript.ts"],"sourcesContent":["import { buildErrorThrower, ClerkRuntimeError } from './error';\nimport { createDevOrStagingUrlCache, parsePublishableKey } from './keys';\nimport { loadScript } from './loadScript';\nimport { isProxyUrlRelative, 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 version = versionSelector(__internal_clerkJSVersion);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'clerk-js', version, 'clerk.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\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 version = versionSelector(__internal_clerkUIVersion, UI_PACKAGE_VERSION);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'ui', version, 'ui.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\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\nconst stripTrailingSlashes = (value: string) => {\n while (value.endsWith('/')) {\n value = value.slice(0, -1);\n }\n\n return value;\n};\n\nconst buildRelativeProxyScriptUrl = (proxyUrl: string, packageName: string, version: string, fileName: string) => {\n return `${stripTrailingSlashes(proxyUrl)}/npm/@clerk/${packageName}@${version}/dist/${fileName}`;\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 const resolvedProxyUrl = proxyUrlToAbsoluteURL(proxyUrl);\n\n if (isProxyUrlRelative(resolvedProxyUrl)) {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n\n return resolvedProxyUrl.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,wCAA2B;AAEzD,MAAM,eAAeC,gCAAkB,EAAE,aAAa,gBAAgB,CAAC;;;;;;;AA2CvE,SAAS,4BAA4B,MAAmD;CACtF,IAAI,OAAO,WAAW,eAAe,CAAE,OAAe,OACpD,OAAO;CAKT,OAAO,CAAC,CADK,OAAe;AAE9B;AACA,MAAM,8BAA8B,4BAA4B,OAAO;AACvE,MAAM,gCAAgC,4BAA4B,wBAAwB;;;;;;;AAQ1F,SAAS,sBAAsB,WAA4B;CACzD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,aAC3C,OAAO;CAGT,MAAM,UAAU,YAAY,iBAAiB,WAAW,UAAU;CAElE,IAAI,QAAQ,WAAW,GACrB,OAAO;CAGT,MAAM,cAAc,QAAQ,QAAQ,SAAS;CAI7C,IAAI,YAAY,iBAAiB,KAAK,YAAY,oBAAoB,GAAG;EAEvE,IAAI,YAAY,gBAAgB,GAC9B,OAAO;EAGT,IAAI,YAAY,cAAc,KAAK,YAAY,gBAAgB,GAC7D,OAAO;EAGT,IAAI,oBAAoB,aAAa;GAEnC,IADgB,YAAoB,kBACtB,KACZ,OAAO;GAET,IAAI,YAAY,mBAAmB,GACjC,OAAO;EAEX;CACF;CAEA,OAAO;AACT;;;;;;;;;;;;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MAAM,sBAAsB;GAC1B,IAAI,UACF;GAGF,WAAW;GACX,QAAQ,WAAW,YAAY;GAE/B,IAAI,CAAC,UAAU,GACb,OAAO,UAAU;QAEjB,QAAQ,IAAI;EAEhB;EAEA,MAAM,YAAY,WAAW,eAAe,SAAS;EAErD,gBAAgB;EAEhB,MAAM,eAAe,kBAAkB;GACrC,IAAI,UAAU;IACZ,cAAc,YAAY;IAC1B;GACF;GACA,gBAAgB;EAClB,GAAG,GAAG;CACR,CAAC;AACH;AAEA,SAAgB,kCAAkC,aAAqB;CACrE,aAAa,eAAe,EAAE,YAAY,CAAC;AAC7C;;;;AAKA,MAAa,oBAAoB;;;;AAKjC,MAAa,mBAAmB;;;;AAKhC,MAAa,+BAA+B;;;;AAK5C,MAAa,oCAAoC"}
|
|
@@ -139,7 +139,7 @@ const clerkJSScriptUrl = (opts) => {
|
|
|
139
139
|
const clerkUIScriptUrl = (opts) => {
|
|
140
140
|
const { __internal_clerkUIUrl, __internal_clerkUIVersion, proxyUrl, domain, publishableKey } = opts;
|
|
141
141
|
if (__internal_clerkUIUrl) return __internal_clerkUIUrl;
|
|
142
|
-
const version = versionSelector(__internal_clerkUIVersion, "1.25.1
|
|
142
|
+
const version = versionSelector(__internal_clerkUIVersion, "1.25.1");
|
|
143
143
|
if (proxyUrl && isProxyUrlRelative(proxyUrl)) return buildRelativeProxyScriptUrl(proxyUrl, "ui", version, "ui.browser.js");
|
|
144
144
|
return `https://${buildScriptHost({
|
|
145
145
|
publishableKey,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadClerkJsScript.mjs","names":[],"sources":["../src/loadClerkJsScript.ts"],"sourcesContent":["import { buildErrorThrower, ClerkRuntimeError } from './error';\nimport { createDevOrStagingUrlCache, parsePublishableKey } from './keys';\nimport { loadScript } from './loadScript';\nimport { isProxyUrlRelative, 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 version = versionSelector(__internal_clerkJSVersion);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'clerk-js', version, 'clerk.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\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 version = versionSelector(__internal_clerkUIVersion, UI_PACKAGE_VERSION);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'ui', version, 'ui.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\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\nconst stripTrailingSlashes = (value: string) => {\n while (value.endsWith('/')) {\n value = value.slice(0, -1);\n }\n\n return value;\n};\n\nconst buildRelativeProxyScriptUrl = (proxyUrl: string, packageName: string, version: string, fileName: string) => {\n return `${stripTrailingSlashes(proxyUrl)}/npm/@clerk/${packageName}@${version}/dist/${fileName}`;\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 const resolvedProxyUrl = proxyUrlToAbsoluteURL(proxyUrl);\n\n if (isProxyUrlRelative(resolvedProxyUrl)) {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n\n return resolvedProxyUrl.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,sBAAsB,2BAA2B;AAEzD,MAAM,eAAe,kBAAkB,EAAE,aAAa,gBAAgB,CAAC;;;;;;;AA2CvE,SAAS,4BAA4B,MAAmD;CACtF,IAAI,OAAO,WAAW,eAAe,CAAE,OAAe,OACpD,OAAO;CAKT,OAAO,CAAC,CADK,OAAe;AAE9B;AACA,MAAM,8BAA8B,4BAA4B,OAAO;AACvE,MAAM,gCAAgC,4BAA4B,wBAAwB;;;;;;;AAQ1F,SAAS,sBAAsB,WAA4B;CACzD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,aAC3C,OAAO;CAGT,MAAM,UAAU,YAAY,iBAAiB,WAAW,UAAU;CAElE,IAAI,QAAQ,WAAW,GACrB,OAAO;CAGT,MAAM,cAAc,QAAQ,QAAQ,SAAS;CAI7C,IAAI,YAAY,iBAAiB,KAAK,YAAY,oBAAoB,GAAG;EAEvE,IAAI,YAAY,gBAAgB,GAC9B,OAAO;EAGT,IAAI,YAAY,cAAc,KAAK,YAAY,gBAAgB,GAC7D,OAAO;EAGT,IAAI,oBAAoB,aAAa;GAEnC,IADgB,YAAoB,kBACtB,KACZ,OAAO;GAET,IAAI,YAAY,mB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AY;IAC/B,QAAQ,IAAI;GACd;EACF;EAEA,MAAM,sBAAsB;GAC1B,IAAI,UACF;GAGF,WAAW;GACX,QAAQ,WAAW,YAAY;GAE/B,IAAI,CAAC,UAAU,GACb,OAAO,UAAU;QAEjB,QAAQ,IAAI;EAEhB;EAEA,MAAM,YAAY,WAAW,eAAe,SAAS;EAErD,gBAAgB;EAEhB,MAAM,eAAe,kBAAkB;GACrC,IAAI,UAAU;IACZ,cAAc,YAAY;IAC1B;GACF;GACA,gBAAgB;EAClB,GAAG,GAAG;CACR,CAAC;AACH;AAEA,SAAgB,kCAAkC,aAAqB;CACrE,aAAa,eAAe,EAAE,YAAY,CAAC;AAC7C;;;;AAKA,MAAa,oBAAoB;;;;AAKjC,MAAa,mBAAmB;;;;AAKhC,MAAa,+BAA+B;;;;AAK5C,MAAa,oCAAoC"}
|
|
1
|
+
{"version":3,"file":"loadClerkJsScript.mjs","names":[],"sources":["../src/loadClerkJsScript.ts"],"sourcesContent":["import { buildErrorThrower, ClerkRuntimeError } from './error';\nimport { createDevOrStagingUrlCache, parsePublishableKey } from './keys';\nimport { loadScript } from './loadScript';\nimport { isProxyUrlRelative, 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 version = versionSelector(__internal_clerkJSVersion);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'clerk-js', version, 'clerk.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\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 version = versionSelector(__internal_clerkUIVersion, UI_PACKAGE_VERSION);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'ui', version, 'ui.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\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\nconst stripTrailingSlashes = (value: string) => {\n while (value.endsWith('/')) {\n value = value.slice(0, -1);\n }\n\n return value;\n};\n\nconst buildRelativeProxyScriptUrl = (proxyUrl: string, packageName: string, version: string, fileName: string) => {\n return `${stripTrailingSlashes(proxyUrl)}/npm/@clerk/${packageName}@${version}/dist/${fileName}`;\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 const resolvedProxyUrl = proxyUrlToAbsoluteURL(proxyUrl);\n\n if (isProxyUrlRelative(resolvedProxyUrl)) {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n\n return resolvedProxyUrl.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 */\nex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;AAKA,MAAa,oBAAoB;;;;AAKjC,MAAa,mBAAmB;;;;AAKhC,MAAa,+BAA+B;;;;AAK5C,MAAa,oCAAoC"}
|
package/dist/pathMatcher.d.mts
CHANGED
|
@@ -9,9 +9,17 @@ type StripTrailingSlash<T extends string> = T extends '/' ? T : T extends `${inf
|
|
|
9
9
|
/**
|
|
10
10
|
* Suggests the `:path*` subtree form (e.g. `/dashboard/:path*`), which matches on
|
|
11
11
|
* path-segment boundaries. `/` is special-cased to `/:path*` to avoid a malformed `//:path*`.
|
|
12
|
+
*
|
|
13
|
+
* @deprecated Will be removed in the next major version together with {@link createPathMatcher}.
|
|
12
14
|
*/
|
|
13
15
|
type WithPathSegmentWildcard<T = string> = T extends '/' ? '/:path*' : `${StripTrailingSlash<T & string>}/:path*`;
|
|
16
|
+
/**
|
|
17
|
+
* @deprecated Will be removed in the next major version together with {@link createPathMatcher}.
|
|
18
|
+
*/
|
|
14
19
|
type PathPattern = Autocomplete<WithPathSegmentWildcard>;
|
|
20
|
+
/**
|
|
21
|
+
* @deprecated Will be removed in the next major version together with {@link createPathMatcher}.
|
|
22
|
+
*/
|
|
15
23
|
type PathMatcherParam = Array<RegExp | PathPattern> | RegExp | PathPattern;
|
|
16
24
|
declare class MalformedURLError extends Error {
|
|
17
25
|
readonly statusCode = 400;
|
|
@@ -39,6 +47,10 @@ declare const normalizePath: (pathname: string) => string;
|
|
|
39
47
|
*
|
|
40
48
|
* @param patterns - A string, RegExp, or array of patterns to match against
|
|
41
49
|
* @returns A function that takes a pathname and returns true if it matches any of the patterns
|
|
50
|
+
*
|
|
51
|
+
* @deprecated This function will be removed in the next major version. Pattern-based path matching
|
|
52
|
+
* can diverge from how frameworks route requests; use your framework's native routing primitives
|
|
53
|
+
* to decide which paths to protect instead.
|
|
42
54
|
*/
|
|
43
55
|
declare const createPathMatcher: (patterns: PathMatcherParam) => (pathname: string) => boolean;
|
|
44
56
|
//#endregion
|
package/dist/pathMatcher.d.ts
CHANGED
|
@@ -9,9 +9,17 @@ type StripTrailingSlash<T extends string> = T extends '/' ? T : T extends `${inf
|
|
|
9
9
|
/**
|
|
10
10
|
* Suggests the `:path*` subtree form (e.g. `/dashboard/:path*`), which matches on
|
|
11
11
|
* path-segment boundaries. `/` is special-cased to `/:path*` to avoid a malformed `//:path*`.
|
|
12
|
+
*
|
|
13
|
+
* @deprecated Will be removed in the next major version together with {@link createPathMatcher}.
|
|
12
14
|
*/
|
|
13
15
|
type WithPathSegmentWildcard<T = string> = T extends '/' ? '/:path*' : `${StripTrailingSlash<T & string>}/:path*`;
|
|
16
|
+
/**
|
|
17
|
+
* @deprecated Will be removed in the next major version together with {@link createPathMatcher}.
|
|
18
|
+
*/
|
|
14
19
|
type PathPattern = Autocomplete<WithPathSegmentWildcard>;
|
|
20
|
+
/**
|
|
21
|
+
* @deprecated Will be removed in the next major version together with {@link createPathMatcher}.
|
|
22
|
+
*/
|
|
15
23
|
type PathMatcherParam = Array<RegExp | PathPattern> | RegExp | PathPattern;
|
|
16
24
|
declare class MalformedURLError extends Error {
|
|
17
25
|
readonly statusCode = 400;
|
|
@@ -39,6 +47,10 @@ declare const normalizePath: (pathname: string) => string;
|
|
|
39
47
|
*
|
|
40
48
|
* @param patterns - A string, RegExp, or array of patterns to match against
|
|
41
49
|
* @returns A function that takes a pathname and returns true if it matches any of the patterns
|
|
50
|
+
*
|
|
51
|
+
* @deprecated This function will be removed in the next major version. Pattern-based path matching
|
|
52
|
+
* can diverge from how frameworks route requests; use your framework's native routing primitives
|
|
53
|
+
* to decide which paths to protect instead.
|
|
42
54
|
*/
|
|
43
55
|
declare const createPathMatcher: (patterns: PathMatcherParam) => (pathname: string) => boolean;
|
|
44
56
|
//#endregion
|
package/dist/pathMatcher.js
CHANGED
|
@@ -44,6 +44,10 @@ const normalizePath = (pathname) => {
|
|
|
44
44
|
*
|
|
45
45
|
* @param patterns - A string, RegExp, or array of patterns to match against
|
|
46
46
|
* @returns A function that takes a pathname and returns true if it matches any of the patterns
|
|
47
|
+
*
|
|
48
|
+
* @deprecated This function will be removed in the next major version. Pattern-based path matching
|
|
49
|
+
* can diverge from how frameworks route requests; use your framework's native routing primitives
|
|
50
|
+
* to decide which paths to protect instead.
|
|
47
51
|
*/
|
|
48
52
|
const createPathMatcher = (patterns) => {
|
|
49
53
|
const matchers = precomputePathRegex([patterns || ""].flat().filter(Boolean));
|
package/dist/pathMatcher.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pathMatcher.js","names":["pathToRegexp"],"sources":["../src/pathMatcher.ts"],"sourcesContent":["import { pathToRegexp } from './pathToRegexp';\nimport type { Autocomplete } from './types';\n\n/**\n * @deprecated Prefer {@link WithPathSegmentWildcard}; `(.*)` also matches sibling routes\n * (e.g. `/dashboard(.*)` matches `/dashboardxyz`).\n */\nexport type WithPathPatternWildcard<T = string> = `${T & string}(.*)`;\n\ntype StripTrailingSlash<T extends string> = T extends '/'\n ? T\n : T extends `${infer Prefix}/`\n ? StripTrailingSlash<Prefix>\n : T;\n\n/**\n * Suggests the `:path*` subtree form (e.g. `/dashboard/:path*`), which matches on\n * path-segment boundaries. `/` is special-cased to `/:path*` to avoid a malformed `//:path*`.\n */\nexport type WithPathSegmentWildcard<T = string> = T extends '/'\n ? '/:path*'\n : `${StripTrailingSlash<T & string>}/:path*`;\nexport type PathPattern = Autocomplete<WithPathSegmentWildcard>;\nexport type PathMatcherParam = Array<RegExp | PathPattern> | RegExp | PathPattern;\n\nexport class MalformedURLError extends Error {\n public readonly statusCode = 400;\n\n constructor(pathname: string, cause?: unknown) {\n super(`Malformed encoding in URL path: ${pathname}`);\n this.name = 'MalformedURLError';\n this.cause = cause;\n }\n}\n\n/**\n * String-based check for MalformedURLError that works across package bundles\n * where `instanceof` would fail due to duplicate class identities.\n */\nexport function isMalformedURLError(e: unknown): e is MalformedURLError {\n return e instanceof Error && e.name === 'MalformedURLError';\n}\n\nconst precomputePathRegex = (patterns: Array<string | RegExp>) => {\n return patterns.map(pattern => (pattern instanceof RegExp ? pattern : pathToRegexp(pattern)));\n};\n\n/**\n * Normalizes a URL path for safe route matching.\n *\n * 1. Decodes percent-encoded unreserved characters using decodeURI (not\n * decodeURIComponent) so path-reserved delimiters like %2F, %3F, %23\n * are preserved — matching how framework routers interpret paths.\n * 2. Collapses consecutive slashes (e.g. //api/admin → /api/admin) to\n * prevent bypass via extra slashes.\n *\n * @throws {MalformedURLError} if the path contains invalid percent-encoding\n */\nexport const normalizePath = (pathname: string): string => {\n try {\n pathname = decodeURI(pathname);\n } catch (e) {\n throw new MalformedURLError(pathname, e);\n }\n return pathname.replace(/\\/\\/+/g, '/');\n};\n\n/**\n * Creates a function that matches paths against a set of patterns.\n *\n * @param patterns - A string, RegExp, or array of patterns to match against\n * @returns A function that takes a pathname and returns true if it matches any of the patterns\n */\nexport const createPathMatcher = (patterns: PathMatcherParam) => {\n const routePatterns = [patterns || ''].flat().filter(Boolean);\n const matchers = precomputePathRegex(routePatterns);\n return (pathname: string) => matchers.some(matcher => matcher.test(normalizePath(pathname)));\n};\n"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"pathMatcher.js","names":["pathToRegexp"],"sources":["../src/pathMatcher.ts"],"sourcesContent":["import { pathToRegexp } from './pathToRegexp';\nimport type { Autocomplete } from './types';\n\n/**\n * @deprecated Prefer {@link WithPathSegmentWildcard}; `(.*)` also matches sibling routes\n * (e.g. `/dashboard(.*)` matches `/dashboardxyz`).\n */\nexport type WithPathPatternWildcard<T = string> = `${T & string}(.*)`;\n\ntype StripTrailingSlash<T extends string> = T extends '/'\n ? T\n : T extends `${infer Prefix}/`\n ? StripTrailingSlash<Prefix>\n : T;\n\n/**\n * Suggests the `:path*` subtree form (e.g. `/dashboard/:path*`), which matches on\n * path-segment boundaries. `/` is special-cased to `/:path*` to avoid a malformed `//:path*`.\n *\n * @deprecated Will be removed in the next major version together with {@link createPathMatcher}.\n */\nexport type WithPathSegmentWildcard<T = string> = T extends '/'\n ? '/:path*'\n : `${StripTrailingSlash<T & string>}/:path*`;\n/**\n * @deprecated Will be removed in the next major version together with {@link createPathMatcher}.\n */\nexport type PathPattern = Autocomplete<WithPathSegmentWildcard>;\n/**\n * @deprecated Will be removed in the next major version together with {@link createPathMatcher}.\n */\nexport type PathMatcherParam = Array<RegExp | PathPattern> | RegExp | PathPattern;\n\nexport class MalformedURLError extends Error {\n public readonly statusCode = 400;\n\n constructor(pathname: string, cause?: unknown) {\n super(`Malformed encoding in URL path: ${pathname}`);\n this.name = 'MalformedURLError';\n this.cause = cause;\n }\n}\n\n/**\n * String-based check for MalformedURLError that works across package bundles\n * where `instanceof` would fail due to duplicate class identities.\n */\nexport function isMalformedURLError(e: unknown): e is MalformedURLError {\n return e instanceof Error && e.name === 'MalformedURLError';\n}\n\nconst precomputePathRegex = (patterns: Array<string | RegExp>) => {\n return patterns.map(pattern => (pattern instanceof RegExp ? pattern : pathToRegexp(pattern)));\n};\n\n/**\n * Normalizes a URL path for safe route matching.\n *\n * 1. Decodes percent-encoded unreserved characters using decodeURI (not\n * decodeURIComponent) so path-reserved delimiters like %2F, %3F, %23\n * are preserved — matching how framework routers interpret paths.\n * 2. Collapses consecutive slashes (e.g. //api/admin → /api/admin) to\n * prevent bypass via extra slashes.\n *\n * @throws {MalformedURLError} if the path contains invalid percent-encoding\n */\nexport const normalizePath = (pathname: string): string => {\n try {\n pathname = decodeURI(pathname);\n } catch (e) {\n throw new MalformedURLError(pathname, e);\n }\n return pathname.replace(/\\/\\/+/g, '/');\n};\n\n/**\n * Creates a function that matches paths against a set of patterns.\n *\n * @param patterns - A string, RegExp, or array of patterns to match against\n * @returns A function that takes a pathname and returns true if it matches any of the patterns\n *\n * @deprecated This function will be removed in the next major version. Pattern-based path matching\n * can diverge from how frameworks route requests; use your framework's native routing primitives\n * to decide which paths to protect instead.\n */\nexport const createPathMatcher = (patterns: PathMatcherParam) => {\n const routePatterns = [patterns || ''].flat().filter(Boolean);\n const matchers = precomputePathRegex(routePatterns);\n return (pathname: string) => matchers.some(matcher => matcher.test(normalizePath(pathname)));\n};\n"],"mappings":";;;;AAiCA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,AAAgB,aAAa;CAE7B,YAAY,UAAkB,OAAiB;EAC7C,MAAM,mCAAmC,UAAU;EACnD,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;;;;;AAMA,SAAgB,oBAAoB,GAAoC;CACtE,OAAO,aAAa,SAAS,EAAE,SAAS;AAC1C;AAEA,MAAM,uBAAuB,aAAqC;CAChE,OAAO,SAAS,KAAI,YAAY,mBAAmB,SAAS,UAAUA,kCAAa,OAAO,CAAE;AAC9F;;;;;;;;;;;;AAaA,MAAa,iBAAiB,aAA6B;CACzD,IAAI;EACF,WAAW,UAAU,QAAQ;CAC/B,SAAS,GAAG;EACV,MAAM,IAAI,kBAAkB,UAAU,CAAC;CACzC;CACA,OAAO,SAAS,QAAQ,UAAU,GAAG;AACvC;;;;;;;;;;;AAYA,MAAa,qBAAqB,aAA+B;CAE/D,MAAM,WAAW,oBADK,CAAC,YAAY,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,OAAO,OACJ,CAAC;CAClD,QAAQ,aAAqB,SAAS,MAAK,YAAW,QAAQ,KAAK,cAAc,QAAQ,CAAC,CAAC;AAC7F"}
|
package/dist/pathMatcher.mjs
CHANGED
|
@@ -43,6 +43,10 @@ const normalizePath = (pathname) => {
|
|
|
43
43
|
*
|
|
44
44
|
* @param patterns - A string, RegExp, or array of patterns to match against
|
|
45
45
|
* @returns A function that takes a pathname and returns true if it matches any of the patterns
|
|
46
|
+
*
|
|
47
|
+
* @deprecated This function will be removed in the next major version. Pattern-based path matching
|
|
48
|
+
* can diverge from how frameworks route requests; use your framework's native routing primitives
|
|
49
|
+
* to decide which paths to protect instead.
|
|
46
50
|
*/
|
|
47
51
|
const createPathMatcher = (patterns) => {
|
|
48
52
|
const matchers = precomputePathRegex([patterns || ""].flat().filter(Boolean));
|
package/dist/pathMatcher.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pathMatcher.mjs","names":[],"sources":["../src/pathMatcher.ts"],"sourcesContent":["import { pathToRegexp } from './pathToRegexp';\nimport type { Autocomplete } from './types';\n\n/**\n * @deprecated Prefer {@link WithPathSegmentWildcard}; `(.*)` also matches sibling routes\n * (e.g. `/dashboard(.*)` matches `/dashboardxyz`).\n */\nexport type WithPathPatternWildcard<T = string> = `${T & string}(.*)`;\n\ntype StripTrailingSlash<T extends string> = T extends '/'\n ? T\n : T extends `${infer Prefix}/`\n ? StripTrailingSlash<Prefix>\n : T;\n\n/**\n * Suggests the `:path*` subtree form (e.g. `/dashboard/:path*`), which matches on\n * path-segment boundaries. `/` is special-cased to `/:path*` to avoid a malformed `//:path*`.\n */\nexport type WithPathSegmentWildcard<T = string> = T extends '/'\n ? '/:path*'\n : `${StripTrailingSlash<T & string>}/:path*`;\nexport type PathPattern = Autocomplete<WithPathSegmentWildcard>;\nexport type PathMatcherParam = Array<RegExp | PathPattern> | RegExp | PathPattern;\n\nexport class MalformedURLError extends Error {\n public readonly statusCode = 400;\n\n constructor(pathname: string, cause?: unknown) {\n super(`Malformed encoding in URL path: ${pathname}`);\n this.name = 'MalformedURLError';\n this.cause = cause;\n }\n}\n\n/**\n * String-based check for MalformedURLError that works across package bundles\n * where `instanceof` would fail due to duplicate class identities.\n */\nexport function isMalformedURLError(e: unknown): e is MalformedURLError {\n return e instanceof Error && e.name === 'MalformedURLError';\n}\n\nconst precomputePathRegex = (patterns: Array<string | RegExp>) => {\n return patterns.map(pattern => (pattern instanceof RegExp ? pattern : pathToRegexp(pattern)));\n};\n\n/**\n * Normalizes a URL path for safe route matching.\n *\n * 1. Decodes percent-encoded unreserved characters using decodeURI (not\n * decodeURIComponent) so path-reserved delimiters like %2F, %3F, %23\n * are preserved — matching how framework routers interpret paths.\n * 2. Collapses consecutive slashes (e.g. //api/admin → /api/admin) to\n * prevent bypass via extra slashes.\n *\n * @throws {MalformedURLError} if the path contains invalid percent-encoding\n */\nexport const normalizePath = (pathname: string): string => {\n try {\n pathname = decodeURI(pathname);\n } catch (e) {\n throw new MalformedURLError(pathname, e);\n }\n return pathname.replace(/\\/\\/+/g, '/');\n};\n\n/**\n * Creates a function that matches paths against a set of patterns.\n *\n * @param patterns - A string, RegExp, or array of patterns to match against\n * @returns A function that takes a pathname and returns true if it matches any of the patterns\n */\nexport const createPathMatcher = (patterns: PathMatcherParam) => {\n const routePatterns = [patterns || ''].flat().filter(Boolean);\n const matchers = precomputePathRegex(routePatterns);\n return (pathname: string) => matchers.some(matcher => matcher.test(normalizePath(pathname)));\n};\n"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"pathMatcher.mjs","names":[],"sources":["../src/pathMatcher.ts"],"sourcesContent":["import { pathToRegexp } from './pathToRegexp';\nimport type { Autocomplete } from './types';\n\n/**\n * @deprecated Prefer {@link WithPathSegmentWildcard}; `(.*)` also matches sibling routes\n * (e.g. `/dashboard(.*)` matches `/dashboardxyz`).\n */\nexport type WithPathPatternWildcard<T = string> = `${T & string}(.*)`;\n\ntype StripTrailingSlash<T extends string> = T extends '/'\n ? T\n : T extends `${infer Prefix}/`\n ? StripTrailingSlash<Prefix>\n : T;\n\n/**\n * Suggests the `:path*` subtree form (e.g. `/dashboard/:path*`), which matches on\n * path-segment boundaries. `/` is special-cased to `/:path*` to avoid a malformed `//:path*`.\n *\n * @deprecated Will be removed in the next major version together with {@link createPathMatcher}.\n */\nexport type WithPathSegmentWildcard<T = string> = T extends '/'\n ? '/:path*'\n : `${StripTrailingSlash<T & string>}/:path*`;\n/**\n * @deprecated Will be removed in the next major version together with {@link createPathMatcher}.\n */\nexport type PathPattern = Autocomplete<WithPathSegmentWildcard>;\n/**\n * @deprecated Will be removed in the next major version together with {@link createPathMatcher}.\n */\nexport type PathMatcherParam = Array<RegExp | PathPattern> | RegExp | PathPattern;\n\nexport class MalformedURLError extends Error {\n public readonly statusCode = 400;\n\n constructor(pathname: string, cause?: unknown) {\n super(`Malformed encoding in URL path: ${pathname}`);\n this.name = 'MalformedURLError';\n this.cause = cause;\n }\n}\n\n/**\n * String-based check for MalformedURLError that works across package bundles\n * where `instanceof` would fail due to duplicate class identities.\n */\nexport function isMalformedURLError(e: unknown): e is MalformedURLError {\n return e instanceof Error && e.name === 'MalformedURLError';\n}\n\nconst precomputePathRegex = (patterns: Array<string | RegExp>) => {\n return patterns.map(pattern => (pattern instanceof RegExp ? pattern : pathToRegexp(pattern)));\n};\n\n/**\n * Normalizes a URL path for safe route matching.\n *\n * 1. Decodes percent-encoded unreserved characters using decodeURI (not\n * decodeURIComponent) so path-reserved delimiters like %2F, %3F, %23\n * are preserved — matching how framework routers interpret paths.\n * 2. Collapses consecutive slashes (e.g. //api/admin → /api/admin) to\n * prevent bypass via extra slashes.\n *\n * @throws {MalformedURLError} if the path contains invalid percent-encoding\n */\nexport const normalizePath = (pathname: string): string => {\n try {\n pathname = decodeURI(pathname);\n } catch (e) {\n throw new MalformedURLError(pathname, e);\n }\n return pathname.replace(/\\/\\/+/g, '/');\n};\n\n/**\n * Creates a function that matches paths against a set of patterns.\n *\n * @param patterns - A string, RegExp, or array of patterns to match against\n * @returns A function that takes a pathname and returns true if it matches any of the patterns\n *\n * @deprecated This function will be removed in the next major version. Pattern-based path matching\n * can diverge from how frameworks route requests; use your framework's native routing primitives\n * to decide which paths to protect instead.\n */\nexport const createPathMatcher = (patterns: PathMatcherParam) => {\n const routePatterns = [patterns || ''].flat().filter(Boolean);\n const matchers = precomputePathRegex(routePatterns);\n return (pathname: string) => matchers.some(matcher => matcher.test(normalizePath(pathname)));\n};\n"],"mappings":";;;AAiCA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,AAAgB,aAAa;CAE7B,YAAY,UAAkB,OAAiB;EAC7C,MAAM,mCAAmC,UAAU;EACnD,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;;;;;AAMA,SAAgB,oBAAoB,GAAoC;CACtE,OAAO,aAAa,SAAS,EAAE,SAAS;AAC1C;AAEA,MAAM,uBAAuB,aAAqC;CAChE,OAAO,SAAS,KAAI,YAAY,mBAAmB,SAAS,UAAU,aAAa,OAAO,CAAE;AAC9F;;;;;;;;;;;;AAaA,MAAa,iBAAiB,aAA6B;CACzD,IAAI;EACF,WAAW,UAAU,QAAQ;CAC/B,SAAS,GAAG;EACV,MAAM,IAAI,kBAAkB,UAAU,CAAC;CACzC;CACA,OAAO,SAAS,QAAQ,UAAU,GAAG;AACvC;;;;;;;;;;;AAYA,MAAa,qBAAqB,aAA+B;CAE/D,MAAM,WAAW,oBADK,CAAC,YAAY,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,OAAO,OACJ,CAAC;CAClD,QAAQ,aAAqB,SAAS,MAAK,YAAW,QAAQ,KAAK,cAAc,QAAQ,CAAC,CAAC;AAC7F"}
|
|
@@ -13,7 +13,7 @@ type ProtectCheckField = 'protect_check';
|
|
|
13
13
|
/** @inline */
|
|
14
14
|
type SignUpField = SignUpAttributeField | SignUpIdentificationField | ProtectCheckField;
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
16
|
+
* An interface that represents a pending Clerk Protect mid-flow challenge. Only surfaced when Protect mid-flow challenges are
|
|
17
17
|
* explicitly enabled for the instance; upgrading the SDK alone does not enable it.
|
|
18
18
|
*/
|
|
19
19
|
interface ProtectCheckResource {
|
|
@@ -21,12 +21,21 @@ interface ProtectCheckResource {
|
|
|
21
21
|
* Always `'pending'` when surfaced to clients.
|
|
22
22
|
*/
|
|
23
23
|
status: 'pending';
|
|
24
|
+
/**
|
|
25
|
+
* Opaque challenge token to pass to the Clerk Protect challenge SDK.
|
|
26
|
+
*/
|
|
24
27
|
token: string;
|
|
28
|
+
/**
|
|
29
|
+
* URL of the Clerk Protect challenge SDK to load for this challenge.
|
|
30
|
+
*/
|
|
25
31
|
sdkUrl: string;
|
|
26
32
|
/**
|
|
27
33
|
* Unix epoch timestamp in **milliseconds** at which the challenge expires.
|
|
28
34
|
*/
|
|
29
35
|
expiresAt?: number;
|
|
36
|
+
/**
|
|
37
|
+
* Optional UI hints for rendering the challenge.
|
|
38
|
+
*/
|
|
30
39
|
uiHints?: Record<string, string>;
|
|
31
40
|
}
|
|
32
41
|
type PrepareVerificationParams = {
|
|
@@ -13,7 +13,7 @@ type ProtectCheckField = 'protect_check';
|
|
|
13
13
|
/** @inline */
|
|
14
14
|
type SignUpField = SignUpAttributeField | SignUpIdentificationField | ProtectCheckField;
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
16
|
+
* An interface that represents a pending Clerk Protect mid-flow challenge. Only surfaced when Protect mid-flow challenges are
|
|
17
17
|
* explicitly enabled for the instance; upgrading the SDK alone does not enable it.
|
|
18
18
|
*/
|
|
19
19
|
interface ProtectCheckResource {
|
|
@@ -21,12 +21,21 @@ interface ProtectCheckResource {
|
|
|
21
21
|
* Always `'pending'` when surfaced to clients.
|
|
22
22
|
*/
|
|
23
23
|
status: 'pending';
|
|
24
|
+
/**
|
|
25
|
+
* Opaque challenge token to pass to the Clerk Protect challenge SDK.
|
|
26
|
+
*/
|
|
24
27
|
token: string;
|
|
28
|
+
/**
|
|
29
|
+
* URL of the Clerk Protect challenge SDK to load for this challenge.
|
|
30
|
+
*/
|
|
25
31
|
sdkUrl: string;
|
|
26
32
|
/**
|
|
27
33
|
* Unix epoch timestamp in **milliseconds** at which the challenge expires.
|
|
28
34
|
*/
|
|
29
35
|
expiresAt?: number;
|
|
36
|
+
/**
|
|
37
|
+
* Optional UI hints for rendering the challenge.
|
|
38
|
+
*/
|
|
30
39
|
uiHints?: Record<string, string>;
|
|
31
40
|
}
|
|
32
41
|
type PrepareVerificationParams = {
|
package/dist/versionSelector.js
CHANGED
|
@@ -12,7 +12,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
12
12
|
* @param packageVersion - The version of `@clerk/clerk-js` that will be used if an explicit version is not provided
|
|
13
13
|
* @returns The npm tag, version or major version to use
|
|
14
14
|
*/
|
|
15
|
-
const versionSelector = (clerkJSVersion, packageVersion = "6.25.1
|
|
15
|
+
const versionSelector = (clerkJSVersion, packageVersion = "6.25.1") => {
|
|
16
16
|
if (clerkJSVersion) return clerkJSVersion;
|
|
17
17
|
const prereleaseTag = getPrereleaseTag(packageVersion);
|
|
18
18
|
if (prereleaseTag) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"versionSelector.js","names":[],"sources":["../src/versionSelector.ts"],"sourcesContent":["/**\n * This version selector is a bit complicated, so here is the flow:\n * 1. Use the clerkJSVersion prop on the provider\n * 2. Use the exact `@clerk/clerk-js` version if it is a `@snapshot` prerelease\n * 3. Use the prerelease tag of `@clerk/clerk-js` or the packageVersion provided\n * 4. Fallback to the major version of `@clerk/clerk-js` or the packageVersion provided\n *\n * @param clerkJSVersion - The optional clerkJSVersion prop on the provider\n * @param packageVersion - The version of `@clerk/clerk-js` that will be used if an explicit version is not provided\n * @returns The npm tag, version or major version to use\n */\nexport const versionSelector = (clerkJSVersion: string | undefined, packageVersion = JS_PACKAGE_VERSION) => {\n if (clerkJSVersion) {\n return clerkJSVersion;\n }\n\n const prereleaseTag = getPrereleaseTag(packageVersion);\n if (prereleaseTag) {\n if (prereleaseTag === 'snapshot') {\n return packageVersion;\n }\n\n return prereleaseTag;\n }\n\n return getMajorVersion(packageVersion);\n};\n\nconst getPrereleaseTag = (packageVersion: string) =>\n packageVersion\n .trim()\n .replace(/^v/, '')\n .match(/-(.+?)(\\.|$)/)?.[1];\n\nexport const getMajorVersion = (packageVersion: string) => packageVersion.trim().replace(/^v/, '').split('.')[0];\n"],"mappings":";;;;;;;;;;;;;;AAWA,MAAa,mBAAmB,gBAAoC,
|
|
1
|
+
{"version":3,"file":"versionSelector.js","names":[],"sources":["../src/versionSelector.ts"],"sourcesContent":["/**\n * This version selector is a bit complicated, so here is the flow:\n * 1. Use the clerkJSVersion prop on the provider\n * 2. Use the exact `@clerk/clerk-js` version if it is a `@snapshot` prerelease\n * 3. Use the prerelease tag of `@clerk/clerk-js` or the packageVersion provided\n * 4. Fallback to the major version of `@clerk/clerk-js` or the packageVersion provided\n *\n * @param clerkJSVersion - The optional clerkJSVersion prop on the provider\n * @param packageVersion - The version of `@clerk/clerk-js` that will be used if an explicit version is not provided\n * @returns The npm tag, version or major version to use\n */\nexport const versionSelector = (clerkJSVersion: string | undefined, packageVersion = JS_PACKAGE_VERSION) => {\n if (clerkJSVersion) {\n return clerkJSVersion;\n }\n\n const prereleaseTag = getPrereleaseTag(packageVersion);\n if (prereleaseTag) {\n if (prereleaseTag === 'snapshot') {\n return packageVersion;\n }\n\n return prereleaseTag;\n }\n\n return getMajorVersion(packageVersion);\n};\n\nconst getPrereleaseTag = (packageVersion: string) =>\n packageVersion\n .trim()\n .replace(/^v/, '')\n .match(/-(.+?)(\\.|$)/)?.[1];\n\nexport const getMajorVersion = (packageVersion: string) => packageVersion.trim().replace(/^v/, '').split('.')[0];\n"],"mappings":";;;;;;;;;;;;;;AAWA,MAAa,mBAAmB,gBAAoC,8BAAwC;CAC1G,IAAI,gBACF,OAAO;CAGT,MAAM,gBAAgB,iBAAiB,cAAc;CACrD,IAAI,eAAe;EACjB,IAAI,kBAAkB,YACpB,OAAO;EAGT,OAAO;CACT;CAEA,OAAO,gBAAgB,cAAc;AACvC;AAEA,MAAM,oBAAoB,mBACxB,eACG,KAAK,CAAC,CACN,QAAQ,MAAM,EAAE,CAAC,CACjB,MAAM,cAAc,CAAC,GAAG;AAE7B,MAAa,mBAAmB,mBAA2B,eAAe,KAAK,CAAC,CAAC,QAAQ,MAAM,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC"}
|
package/dist/versionSelector.mjs
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* @param packageVersion - The version of `@clerk/clerk-js` that will be used if an explicit version is not provided
|
|
11
11
|
* @returns The npm tag, version or major version to use
|
|
12
12
|
*/
|
|
13
|
-
const versionSelector = (clerkJSVersion, packageVersion = "6.25.1
|
|
13
|
+
const versionSelector = (clerkJSVersion, packageVersion = "6.25.1") => {
|
|
14
14
|
if (clerkJSVersion) return clerkJSVersion;
|
|
15
15
|
const prereleaseTag = getPrereleaseTag(packageVersion);
|
|
16
16
|
if (prereleaseTag) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"versionSelector.mjs","names":[],"sources":["../src/versionSelector.ts"],"sourcesContent":["/**\n * This version selector is a bit complicated, so here is the flow:\n * 1. Use the clerkJSVersion prop on the provider\n * 2. Use the exact `@clerk/clerk-js` version if it is a `@snapshot` prerelease\n * 3. Use the prerelease tag of `@clerk/clerk-js` or the packageVersion provided\n * 4. Fallback to the major version of `@clerk/clerk-js` or the packageVersion provided\n *\n * @param clerkJSVersion - The optional clerkJSVersion prop on the provider\n * @param packageVersion - The version of `@clerk/clerk-js` that will be used if an explicit version is not provided\n * @returns The npm tag, version or major version to use\n */\nexport const versionSelector = (clerkJSVersion: string | undefined, packageVersion = JS_PACKAGE_VERSION) => {\n if (clerkJSVersion) {\n return clerkJSVersion;\n }\n\n const prereleaseTag = getPrereleaseTag(packageVersion);\n if (prereleaseTag) {\n if (prereleaseTag === 'snapshot') {\n return packageVersion;\n }\n\n return prereleaseTag;\n }\n\n return getMajorVersion(packageVersion);\n};\n\nconst getPrereleaseTag = (packageVersion: string) =>\n packageVersion\n .trim()\n .replace(/^v/, '')\n .match(/-(.+?)(\\.|$)/)?.[1];\n\nexport const getMajorVersion = (packageVersion: string) => packageVersion.trim().replace(/^v/, '').split('.')[0];\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,mBAAmB,gBAAoC,
|
|
1
|
+
{"version":3,"file":"versionSelector.mjs","names":[],"sources":["../src/versionSelector.ts"],"sourcesContent":["/**\n * This version selector is a bit complicated, so here is the flow:\n * 1. Use the clerkJSVersion prop on the provider\n * 2. Use the exact `@clerk/clerk-js` version if it is a `@snapshot` prerelease\n * 3. Use the prerelease tag of `@clerk/clerk-js` or the packageVersion provided\n * 4. Fallback to the major version of `@clerk/clerk-js` or the packageVersion provided\n *\n * @param clerkJSVersion - The optional clerkJSVersion prop on the provider\n * @param packageVersion - The version of `@clerk/clerk-js` that will be used if an explicit version is not provided\n * @returns The npm tag, version or major version to use\n */\nexport const versionSelector = (clerkJSVersion: string | undefined, packageVersion = JS_PACKAGE_VERSION) => {\n if (clerkJSVersion) {\n return clerkJSVersion;\n }\n\n const prereleaseTag = getPrereleaseTag(packageVersion);\n if (prereleaseTag) {\n if (prereleaseTag === 'snapshot') {\n return packageVersion;\n }\n\n return prereleaseTag;\n }\n\n return getMajorVersion(packageVersion);\n};\n\nconst getPrereleaseTag = (packageVersion: string) =>\n packageVersion\n .trim()\n .replace(/^v/, '')\n .match(/-(.+?)(\\.|$)/)?.[1];\n\nexport const getMajorVersion = (packageVersion: string) => packageVersion.trim().replace(/^v/, '').split('.')[0];\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,mBAAmB,gBAAoC,8BAAwC;CAC1G,IAAI,gBACF,OAAO;CAGT,MAAM,gBAAgB,iBAAiB,cAAc;CACrD,IAAI,eAAe;EACjB,IAAI,kBAAkB,YACpB,OAAO;EAGT,OAAO;CACT;CAEA,OAAO,gBAAgB,cAAc;AACvC;AAEA,MAAM,oBAAoB,mBACxB,eACG,KAAK,CAAC,CACN,QAAQ,MAAM,EAAE,CAAC,CACjB,MAAM,cAAc,CAAC,GAAG;AAE7B,MAAa,mBAAmB,mBAA2B,eAAe,KAAK,CAAC,CAAC,QAAQ,MAAM,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC"}
|