@clerk/shared
Advanced tools
Comparing version 0.15.6-staging.0 to 0.15.6
@@ -1,1930 +0,3 @@ | ||
import { | ||
noop | ||
} from "./chunk-N55KAAWL.js"; | ||
// src/errors/thrower.ts | ||
var DefaultMessages = Object.freeze({ | ||
InvalidFrontendApiErrorMessage: `The frontendApi passed to Clerk is invalid. You can get your Frontend API key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})`, | ||
InvalidProxyUrlErrorMessage: `The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})`, | ||
InvalidPublishableKeyErrorMessage: `The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})`, | ||
MissingPublishableKeyErrorMessage: `Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.` | ||
}); | ||
function buildErrorThrower({ packageName, customMessages }) { | ||
let pkg = packageName; | ||
const messages = { | ||
...DefaultMessages, | ||
...customMessages | ||
}; | ||
function buildMessage(rawMessage, replacements) { | ||
if (!replacements) { | ||
return `${pkg}: ${rawMessage}`; | ||
} | ||
let msg = rawMessage; | ||
const matches = rawMessage.matchAll(/{{([a-zA-Z0-9-_]+)}}/g); | ||
for (const match of matches) { | ||
const replacement = (replacements[match[1]] || "").toString(); | ||
msg = msg.replace(`{{${match[1]}}}`, replacement); | ||
} | ||
return `${pkg}: ${msg}`; | ||
} | ||
return { | ||
setPackageName({ packageName: packageName2 }) { | ||
if (typeof packageName2 === "string") { | ||
pkg = packageName2; | ||
} | ||
return this; | ||
}, | ||
setMessages({ customMessages: customMessages2 }) { | ||
Object.assign(messages, customMessages2 || {}); | ||
return this; | ||
}, | ||
throwInvalidPublishableKeyError(params) { | ||
throw new Error(buildMessage(messages.InvalidPublishableKeyErrorMessage, params)); | ||
}, | ||
throwInvalidFrontendApiError(params) { | ||
throw new Error(buildMessage(messages.InvalidFrontendApiErrorMessage, params)); | ||
}, | ||
throwInvalidProxyUrl(params) { | ||
throw new Error(buildMessage(messages.InvalidProxyUrlErrorMessage, params)); | ||
}, | ||
throwMissingPublishableKeyError() { | ||
throw new Error(buildMessage(messages.MissingPublishableKeyErrorMessage)); | ||
} | ||
}; | ||
} | ||
// src/utils/array.ts | ||
var toSentence = (items) => { | ||
if (items.length == 0) { | ||
return ""; | ||
} | ||
if (items.length == 1) { | ||
return items[0]; | ||
} | ||
let sentence = items.slice(0, -1).join(", "); | ||
sentence += `, or ${items.slice(-1)}`; | ||
return sentence; | ||
}; | ||
// src/utils/browser.ts | ||
function inBrowser() { | ||
return typeof window !== "undefined"; | ||
} | ||
function detectUserAgentRobot(userAgent) { | ||
const robots = new RegExp( | ||
[ | ||
/bot/, | ||
/spider/, | ||
/crawl/, | ||
/APIs-Google/, | ||
/AdsBot/, | ||
/Googlebot/, | ||
/mediapartners/, | ||
/Google Favicon/, | ||
/FeedFetcher/, | ||
/Google-Read-Aloud/, | ||
/DuplexWeb-Google/, | ||
/googleweblight/, | ||
/bing/, | ||
/yandex/, | ||
/baidu/, | ||
/duckduck/, | ||
/yahoo/, | ||
/ecosia/, | ||
/ia_archiver/, | ||
/facebook/, | ||
/instagram/, | ||
/pinterest/, | ||
/reddit/, | ||
/slack/, | ||
/twitter/, | ||
/whatsapp/, | ||
/youtube/, | ||
/semrush/ | ||
].map((r) => r.source).join("|"), | ||
"i" | ||
); | ||
return robots.test(userAgent); | ||
} | ||
function isValidBrowserOnline() { | ||
const navigator2 = window?.navigator; | ||
if (!inBrowser() || !navigator2) { | ||
return false; | ||
} | ||
const isUserAgentRobot = detectUserAgentRobot(navigator2?.userAgent); | ||
const isWebDriver = navigator2?.webdriver; | ||
const isNavigatorOnline = navigator2?.onLine; | ||
const isExperimentalConnectionOnline = navigator2?.connection?.rtt !== 0 && navigator2?.connection?.downlink !== 0; | ||
return !isUserAgentRobot && !isWebDriver && isExperimentalConnectionOnline && isNavigatorOnline; | ||
} | ||
// src/utils/color/predicates.ts | ||
var IS_HEX_COLOR_REGEX = /^#?([A-F0-9]{6}|[A-F0-9]{3})$/i; | ||
var IS_RGB_COLOR_REGEX = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/i; | ||
var IS_RGBA_COLOR_REGEX = /^rgba\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+(\.\d+)?)\)$/i; | ||
var IS_HSL_COLOR_REGEX = /^hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)$/i; | ||
var IS_HSLA_COLOR_REGEX = /^hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%(,\s*\d+(\.\d+)?)*\)$/i; | ||
var isValidHexString = (s) => { | ||
return !!s.match(IS_HEX_COLOR_REGEX); | ||
}; | ||
var isValidRgbaString = (s) => { | ||
return !!(s.match(IS_RGB_COLOR_REGEX) || s.match(IS_RGBA_COLOR_REGEX)); | ||
}; | ||
var isValidHslaString = (s) => { | ||
return !!s.match(IS_HSL_COLOR_REGEX) || !!s.match(IS_HSLA_COLOR_REGEX); | ||
}; | ||
var isRGBColor = (c) => { | ||
return typeof c !== "string" && "r" in c; | ||
}; | ||
var isHSLColor = (c) => { | ||
return typeof c !== "string" && "h" in c; | ||
}; | ||
var isTransparent = (c) => { | ||
return c === "transparent"; | ||
}; | ||
var hasAlpha = (color) => { | ||
return typeof color !== "string" && color.a != void 0 && color.a < 1; | ||
}; | ||
// src/utils/color/cssColorUtils.ts | ||
var CLEAN_HSLA_REGEX = /[hsla()]/g; | ||
var CLEAN_RGBA_REGEX = /[rgba()]/g; | ||
var stringToHslaColor = (value) => { | ||
if (value === "transparent") { | ||
return { h: 0, s: 0, l: 0, a: 0 }; | ||
} | ||
if (isValidHexString(value)) { | ||
return hexStringToHslaColor(value); | ||
} | ||
if (isValidHslaString(value)) { | ||
return parseHslaString(value); | ||
} | ||
if (isValidRgbaString(value)) { | ||
return rgbaStringToHslaColor(value); | ||
} | ||
return null; | ||
}; | ||
var stringToSameTypeColor = (value) => { | ||
value = value.trim(); | ||
if (isValidHexString(value)) { | ||
return value.startsWith("#") ? value : `#${value}`; | ||
} | ||
if (isValidRgbaString(value)) { | ||
return parseRgbaString(value); | ||
} | ||
if (isValidHslaString(value)) { | ||
return parseHslaString(value); | ||
} | ||
if (isTransparent(value)) { | ||
return value; | ||
} | ||
return ""; | ||
}; | ||
var colorToSameTypeString = (color) => { | ||
if (typeof color === "string" && (isValidHexString(color) || isTransparent(color))) { | ||
return color; | ||
} | ||
if (isRGBColor(color)) { | ||
return rgbaColorToRgbaString(color); | ||
} | ||
if (isHSLColor(color)) { | ||
return hslaColorToHslaString(color); | ||
} | ||
return ""; | ||
}; | ||
var hexStringToRgbaColor = (hex) => { | ||
hex = hex.replace("#", ""); | ||
const r = parseInt(hex.substring(0, 2), 16); | ||
const g = parseInt(hex.substring(2, 4), 16); | ||
const b = parseInt(hex.substring(4, 6), 16); | ||
return { r, g, b }; | ||
}; | ||
var rgbaColorToRgbaString = (color) => { | ||
const { a, b, g, r } = color; | ||
return color.a === 0 ? "transparent" : color.a != void 0 ? `rgba(${r},${g},${b},${a})` : `rgb(${r},${g},${b})`; | ||
}; | ||
var hslaColorToHslaString = (color) => { | ||
const { h, s, l, a } = color; | ||
const sPerc = Math.round(s * 100); | ||
const lPerc = Math.round(l * 100); | ||
return color.a === 0 ? "transparent" : color.a != void 0 ? `hsla(${h},${sPerc}%,${lPerc}%,${a})` : `hsl(${h},${sPerc}%,${lPerc}%)`; | ||
}; | ||
var hexStringToHslaColor = (hex) => { | ||
const rgbaString = colorToSameTypeString(hexStringToRgbaColor(hex)); | ||
return rgbaStringToHslaColor(rgbaString); | ||
}; | ||
var rgbaStringToHslaColor = (rgba) => { | ||
const rgbaColor = parseRgbaString(rgba); | ||
const r = rgbaColor.r / 255; | ||
const g = rgbaColor.g / 255; | ||
const b = rgbaColor.b / 255; | ||
const max = Math.max(r, g, b), min = Math.min(r, g, b); | ||
let h, s; | ||
const l = (max + min) / 2; | ||
if (max == min) { | ||
h = s = 0; | ||
} else { | ||
const d = max - min; | ||
s = l >= 0.5 ? d / (2 - (max + min)) : d / (max + min); | ||
switch (max) { | ||
case r: | ||
h = (g - b) / d * 60; | ||
break; | ||
case g: | ||
h = ((b - r) / d + 2) * 60; | ||
break; | ||
default: | ||
h = ((r - g) / d + 4) * 60; | ||
break; | ||
} | ||
} | ||
const res = { h: Math.round(h), s, l }; | ||
const a = rgbaColor.a; | ||
if (a != void 0) { | ||
res.a = a; | ||
} | ||
return res; | ||
}; | ||
var parseRgbaString = (str) => { | ||
const [r, g, b, a] = str.replace(CLEAN_RGBA_REGEX, "").split(",").map((c) => Number.parseFloat(c)); | ||
return { r, g, b, a }; | ||
}; | ||
var parseHslaString = (str) => { | ||
const [h, s, l, a] = str.replace(CLEAN_HSLA_REGEX, "").split(",").map((c) => Number.parseFloat(c)); | ||
return { h, s: s / 100, l: l / 100, a }; | ||
}; | ||
// ../../node_modules/js-cookie/dist/js.cookie.mjs | ||
function assign(target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
return target; | ||
} | ||
var defaultConverter = { | ||
read: function(value) { | ||
if (value[0] === '"') { | ||
value = value.slice(1, -1); | ||
} | ||
return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent); | ||
}, | ||
write: function(value) { | ||
return encodeURIComponent(value).replace( | ||
/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g, | ||
decodeURIComponent | ||
); | ||
} | ||
}; | ||
function init(converter, defaultAttributes) { | ||
function set(key, value, attributes) { | ||
if (typeof document === "undefined") { | ||
return; | ||
} | ||
attributes = assign({}, defaultAttributes, attributes); | ||
if (typeof attributes.expires === "number") { | ||
attributes.expires = new Date(Date.now() + attributes.expires * 864e5); | ||
} | ||
if (attributes.expires) { | ||
attributes.expires = attributes.expires.toUTCString(); | ||
} | ||
key = encodeURIComponent(key).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape); | ||
var stringifiedAttributes = ""; | ||
for (var attributeName in attributes) { | ||
if (!attributes[attributeName]) { | ||
continue; | ||
} | ||
stringifiedAttributes += "; " + attributeName; | ||
if (attributes[attributeName] === true) { | ||
continue; | ||
} | ||
stringifiedAttributes += "=" + attributes[attributeName].split(";")[0]; | ||
} | ||
return document.cookie = key + "=" + converter.write(value, key) + stringifiedAttributes; | ||
} | ||
function get(key) { | ||
if (typeof document === "undefined" || arguments.length && !key) { | ||
return; | ||
} | ||
var cookies = document.cookie ? document.cookie.split("; ") : []; | ||
var jar = {}; | ||
for (var i = 0; i < cookies.length; i++) { | ||
var parts = cookies[i].split("="); | ||
var value = parts.slice(1).join("="); | ||
try { | ||
var foundKey = decodeURIComponent(parts[0]); | ||
jar[foundKey] = converter.read(value, foundKey); | ||
if (key === foundKey) { | ||
break; | ||
} | ||
} catch (e) { | ||
} | ||
} | ||
return key ? jar[key] : jar; | ||
} | ||
return Object.create( | ||
{ | ||
set, | ||
get, | ||
remove: function(key, attributes) { | ||
set( | ||
key, | ||
"", | ||
assign({}, attributes, { | ||
expires: -1 | ||
}) | ||
); | ||
}, | ||
withAttributes: function(attributes) { | ||
return init(this.converter, assign({}, this.attributes, attributes)); | ||
}, | ||
withConverter: function(converter2) { | ||
return init(assign({}, this.converter, converter2), this.attributes); | ||
} | ||
}, | ||
{ | ||
attributes: { value: Object.freeze(defaultAttributes) }, | ||
converter: { value: Object.freeze(converter) } | ||
} | ||
); | ||
} | ||
var api = init(defaultConverter, { path: "/" }); | ||
var js_cookie_default = api; | ||
// src/utils/cookies.ts | ||
function createCookieHandler(cookieName) { | ||
return { | ||
get() { | ||
return js_cookie_default.get(cookieName); | ||
}, | ||
/** | ||
* Setting a cookie will use some defaults such as path being set to "/". | ||
*/ | ||
set(newValue, options = {}) { | ||
return js_cookie_default.set(cookieName, newValue, options); | ||
}, | ||
/** | ||
* On removing a cookie, you have to pass the exact same path/domain attributes used to set it initially | ||
* @see https://github.com/js-cookie/js-cookie#basic-usage | ||
*/ | ||
remove(locationAttributes) { | ||
js_cookie_default.remove(cookieName, locationAttributes); | ||
} | ||
}; | ||
} | ||
// src/utils/createDeferredPromise.ts | ||
var createDeferredPromise = () => { | ||
let resolve = noop; | ||
let reject = noop; | ||
const promise = new Promise((res, rej) => { | ||
resolve = res; | ||
reject = rej; | ||
}); | ||
return { promise, resolve, reject }; | ||
}; | ||
// src/utils/date.ts | ||
var MILLISECONDS_IN_DAY = 864e5; | ||
function dateTo12HourTime(date) { | ||
if (!date) { | ||
return ""; | ||
} | ||
return date.toLocaleString("en-US", { | ||
hour: "2-digit", | ||
minute: "numeric", | ||
hour12: true | ||
}); | ||
} | ||
function differenceInCalendarDays(a, b, { absolute = true } = {}) { | ||
if (!a || !b) { | ||
return 0; | ||
} | ||
const utcA = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate()); | ||
const utcB = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()); | ||
const diff = Math.floor((utcB - utcA) / MILLISECONDS_IN_DAY); | ||
return absolute ? Math.abs(diff) : diff; | ||
} | ||
function normalizeDate(d) { | ||
try { | ||
return new Date(d || /* @__PURE__ */ new Date()); | ||
} catch (e) { | ||
return /* @__PURE__ */ new Date(); | ||
} | ||
} | ||
function formatRelative(props) { | ||
const { date, relativeTo } = props; | ||
if (!date || !relativeTo) { | ||
return null; | ||
} | ||
const a = normalizeDate(date); | ||
const b = normalizeDate(relativeTo); | ||
const differenceInDays = differenceInCalendarDays(b, a, { absolute: false }); | ||
if (differenceInDays < -6) { | ||
return { relativeDateCase: "other", date: a }; | ||
} | ||
if (differenceInDays < -1) { | ||
return { relativeDateCase: "previous6Days", date: a }; | ||
} | ||
if (differenceInDays === -1) { | ||
return { relativeDateCase: "lastDay", date: a }; | ||
} | ||
if (differenceInDays === 0) { | ||
return { relativeDateCase: "sameDay", date: a }; | ||
} | ||
if (differenceInDays === 1) { | ||
return { relativeDateCase: "nextDay", date: a }; | ||
} | ||
if (differenceInDays < 7) { | ||
return { relativeDateCase: "next6Days", date: a }; | ||
} | ||
return { relativeDateCase: "other", date: a }; | ||
} | ||
function addYears(initialDate, yearsToAdd) { | ||
const date = normalizeDate(initialDate); | ||
date.setFullYear(date.getFullYear() + yearsToAdd); | ||
return date; | ||
} | ||
// src/utils/errors.ts | ||
function isUnauthorizedError(e) { | ||
const status = e?.status; | ||
const code = e?.errors?.[0]?.code; | ||
return code === "authentication_invalid" && status === 401; | ||
} | ||
function isNetworkError(e) { | ||
const message = (`${e.message}${e.name}` || "").toLowerCase().replace(/\s+/g, ""); | ||
return message.includes("networkerror"); | ||
} | ||
// src/utils/file.ts | ||
function readJSONFile(file) { | ||
return new Promise((resolve, reject) => { | ||
const reader = new FileReader(); | ||
reader.addEventListener("load", function() { | ||
const result = JSON.parse(reader.result); | ||
resolve(result); | ||
}); | ||
reader.addEventListener("error", reject); | ||
reader.readAsText(file); | ||
}); | ||
} | ||
// src/utils/isomorphicAtob.ts | ||
var isomorphicAtob = (data) => { | ||
if (typeof atob !== "undefined" && typeof atob === "function") { | ||
return atob(data); | ||
} else if (typeof global !== "undefined" && global.Buffer) { | ||
return new global.Buffer(data, "base64").toString(); | ||
} | ||
return data; | ||
}; | ||
// src/utils/keys.ts | ||
var PUBLISHABLE_KEY_LIVE_PREFIX = "pk_live_"; | ||
var PUBLISHABLE_KEY_TEST_PREFIX = "pk_test_"; | ||
var PUBLISHABLE_FRONTEND_API_DEV_REGEX = /^(([a-z]+)-){2}([0-9]{1,2})\.clerk\.accounts([a-z.]*)(dev|com)$/i; | ||
function buildPublishableKey(frontendApi) { | ||
const keyPrefix = PUBLISHABLE_FRONTEND_API_DEV_REGEX.test(frontendApi) ? PUBLISHABLE_KEY_TEST_PREFIX : PUBLISHABLE_KEY_LIVE_PREFIX; | ||
return `${keyPrefix}${btoa(`${frontendApi}$`)}`; | ||
} | ||
function parsePublishableKey(key) { | ||
key = key || ""; | ||
if (!isPublishableKey(key)) { | ||
return null; | ||
} | ||
const instanceType = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) ? "production" : "development"; | ||
let frontendApi = isomorphicAtob(key.split("_")[2]); | ||
if (!frontendApi.endsWith("$")) { | ||
return null; | ||
} | ||
frontendApi = frontendApi.slice(0, -1); | ||
return { | ||
instanceType, | ||
frontendApi | ||
}; | ||
} | ||
function isPublishableKey(key) { | ||
key = key || ""; | ||
const hasValidPrefix = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) || key.startsWith(PUBLISHABLE_KEY_TEST_PREFIX); | ||
const hasValidFrontendApiPostfix = isomorphicAtob(key.split("_")[2] || "").endsWith("$"); | ||
return hasValidPrefix && hasValidFrontendApiPostfix; | ||
} | ||
function isLegacyFrontendApiKey(key) { | ||
key = key || ""; | ||
return key.startsWith("clerk."); | ||
} | ||
function createDevOrStagingUrlCache() { | ||
const DEV_OR_STAGING_SUFFIXES = [ | ||
".lcl.dev", | ||
".stg.dev", | ||
".lclstage.dev", | ||
".stgstage.dev", | ||
".dev.lclclerk.com", | ||
".stg.lclclerk.com", | ||
".accounts.lclclerk.com", | ||
"accountsstage.dev", | ||
"accounts.dev" | ||
]; | ||
const devOrStagingUrlCache = /* @__PURE__ */ new Map(); | ||
return { | ||
isDevOrStagingUrl: (url) => { | ||
if (!url) { | ||
return false; | ||
} | ||
const hostname = typeof url === "string" ? url : url.hostname; | ||
let res = devOrStagingUrlCache.get(hostname); | ||
if (res === void 0) { | ||
res = DEV_OR_STAGING_SUFFIXES.some((s) => hostname.endsWith(s)); | ||
devOrStagingUrlCache.set(hostname, res); | ||
} | ||
return res; | ||
} | ||
}; | ||
} | ||
// src/utils/isRetinaDisplay.ts | ||
function isRetinaDisplay() { | ||
if (!window.matchMedia) { | ||
return false; | ||
} | ||
const mq = window.matchMedia( | ||
"only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)" | ||
); | ||
return mq && mq.matches || window.devicePixelRatio > 1; | ||
} | ||
// src/utils/localStorageBroadcastChannel.ts | ||
var KEY_PREFIX = "__lsbc__"; | ||
var LocalStorageBroadcastChannel = class { | ||
constructor(name) { | ||
this.eventTarget = window; | ||
this.postMessage = (data) => { | ||
try { | ||
localStorage.setItem(this.channelKey, JSON.stringify(data)); | ||
localStorage.removeItem(this.channelKey); | ||
} catch (e) { | ||
} | ||
}; | ||
this.addEventListener = (eventName, listener) => { | ||
this.eventTarget.addEventListener(this.prefixEventName(eventName), (e) => { | ||
listener(e); | ||
}); | ||
}; | ||
this.setupLocalStorageListener = () => { | ||
const notifyListeners = (e) => { | ||
if (e.key !== this.channelKey || !e.newValue) { | ||
return; | ||
} | ||
try { | ||
const data = JSON.parse(e.newValue || ""); | ||
const event = new MessageEvent(this.prefixEventName("message"), { | ||
data | ||
}); | ||
this.eventTarget.dispatchEvent(event); | ||
} catch (e2) { | ||
} | ||
}; | ||
window.addEventListener("storage", notifyListeners); | ||
}; | ||
this.channelKey = KEY_PREFIX + name; | ||
this.setupLocalStorageListener(); | ||
} | ||
prefixEventName(eventName) { | ||
return this.channelKey + eventName; | ||
} | ||
}; | ||
// src/utils/mimeTypeExtensions.ts | ||
var MimeTypeToExtensionMap = Object.freeze({ | ||
"image/png": "png", | ||
"image/jpeg": "jpg", | ||
"image/gif": "gif", | ||
"image/webp": "webp", | ||
"image/x-icon": "ico", | ||
"image/vnd.microsoft.icon": "ico" | ||
}); | ||
var extension = (mimeType) => { | ||
return MimeTypeToExtensionMap[mimeType]; | ||
}; | ||
// src/utils/multiDomain.ts | ||
function handleValueOrFn(value, url, defaultValue) { | ||
if (typeof value === "function") { | ||
return value(url); | ||
} | ||
if (typeof value !== "undefined") { | ||
return value; | ||
} | ||
if (typeof defaultValue !== "undefined") { | ||
return defaultValue; | ||
} | ||
return void 0; | ||
} | ||
// src/utils/string.ts | ||
var IP_V4_ADDRESS_REGEX = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; | ||
function isIPV4Address(str) { | ||
return IP_V4_ADDRESS_REGEX.test(str || ""); | ||
} | ||
function titleize(str) { | ||
const s = str || ""; | ||
return s.charAt(0).toUpperCase() + s.slice(1); | ||
} | ||
function snakeToCamel(str) { | ||
return str ? str.replace(/([-_][a-z])/g, (match) => match.toUpperCase().replace(/-|_/, "")) : ""; | ||
} | ||
function camelToSnake(str) { | ||
return str ? str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`) : ""; | ||
} | ||
// src/utils/object.ts | ||
var createDeepObjectTransformer = (transform) => { | ||
const deepTransform = (obj) => { | ||
if (!obj) { | ||
return obj; | ||
} | ||
if (Array.isArray(obj)) { | ||
return obj.map((el) => { | ||
if (typeof el === "object" || Array.isArray(el)) { | ||
return deepTransform(el); | ||
} | ||
return el; | ||
}); | ||
} | ||
const copy = { ...obj }; | ||
const keys = Object.keys(copy); | ||
for (const oldName of keys) { | ||
const newName = transform(oldName.toString()); | ||
if (newName !== oldName) { | ||
copy[newName] = copy[oldName]; | ||
delete copy[oldName]; | ||
} | ||
if (typeof copy[newName] === "object") { | ||
copy[newName] = deepTransform(copy[newName]); | ||
} | ||
} | ||
return copy; | ||
}; | ||
return deepTransform; | ||
}; | ||
var deepCamelToSnake = createDeepObjectTransformer(camelToSnake); | ||
var deepSnakeToCamel = createDeepObjectTransformer(snakeToCamel); | ||
// src/utils/workerTimers/workerTimers.worker.ts | ||
var workerTimers_worker_default = 'const respond=r=>{self.postMessage(r)},workerToTabIds={};self.addEventListener("message",r=>{const e=r.data;switch(e.type){case"setTimeout":workerToTabIds[e.id]=setTimeout(()=>{respond({id:e.id})},e.ms);break;case"clearTimeout":workerToTabIds[e.id]&&(clearTimeout(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break;case"setInterval":workerToTabIds[e.id]=setInterval(()=>{respond({id:e.id})},e.ms);break;case"clearInterval":workerToTabIds[e.id]&&(clearInterval(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break}});\n'; | ||
// src/utils/workerTimers/createWorkerTimers.ts | ||
var createWebWorker = (source, opts = {}) => { | ||
if (typeof Worker === "undefined") { | ||
return null; | ||
} | ||
try { | ||
const blob = new Blob([source], { type: "application/javascript; charset=utf-8" }); | ||
const workerScript = globalThis.URL.createObjectURL(blob); | ||
return new Worker(workerScript, opts); | ||
} catch (e) { | ||
console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"); | ||
return null; | ||
} | ||
}; | ||
var fallbackTimers = () => { | ||
const setTimeout2 = globalThis.setTimeout.bind(globalThis); | ||
const setInterval = globalThis.setInterval.bind(globalThis); | ||
const clearTimeout2 = globalThis.clearTimeout.bind(globalThis); | ||
const clearInterval = globalThis.clearInterval.bind(globalThis); | ||
return { setTimeout: setTimeout2, setInterval, clearTimeout: clearTimeout2, clearInterval, cleanup: noop }; | ||
}; | ||
var createWorkerTimers = () => { | ||
let id = 0; | ||
const generateId = () => id++; | ||
const callbacks = /* @__PURE__ */ new Map(); | ||
const post = (w, p) => w?.postMessage(p); | ||
const handleMessage = (e) => { | ||
callbacks.get(e.data.id)?.(); | ||
}; | ||
let worker = createWebWorker(workerTimers_worker_default, { name: "clerk-timers" }); | ||
worker?.addEventListener("message", handleMessage); | ||
if (!worker) { | ||
return fallbackTimers(); | ||
} | ||
const init2 = () => { | ||
if (!worker) { | ||
worker = createWebWorker(workerTimers_worker_default, { name: "clerk-timers" }); | ||
worker?.addEventListener("message", handleMessage); | ||
} | ||
}; | ||
const cleanup = () => { | ||
if (worker) { | ||
worker.terminate(); | ||
worker = null; | ||
callbacks.clear(); | ||
} | ||
}; | ||
const setTimeout2 = (cb, ms) => { | ||
init2(); | ||
const id2 = generateId(); | ||
callbacks.set(id2, cb); | ||
post(worker, { type: "setTimeout", id: id2, ms }); | ||
return id2; | ||
}; | ||
const setInterval = (cb, ms) => { | ||
init2(); | ||
const id2 = generateId(); | ||
callbacks.set(id2, cb); | ||
post(worker, { type: "setInterval", id: id2, ms }); | ||
return id2; | ||
}; | ||
const clearTimeout2 = (id2) => { | ||
init2(); | ||
callbacks.delete(id2); | ||
post(worker, { type: "clearTimeout", id: id2 }); | ||
}; | ||
const clearInterval = (id2) => { | ||
init2(); | ||
callbacks.delete(id2); | ||
post(worker, { type: "clearInterval", id: id2 }); | ||
}; | ||
return { setTimeout: setTimeout2, setInterval, clearTimeout: clearTimeout2, clearInterval, cleanup }; | ||
}; | ||
// src/utils/poller.ts | ||
function Poller({ delayInMs } = { delayInMs: 1e3 }) { | ||
const workerTimers = createWorkerTimers(); | ||
let timerId; | ||
let stopped = false; | ||
const stop = () => { | ||
if (timerId) { | ||
workerTimers.clearTimeout(timerId); | ||
workerTimers.cleanup(); | ||
} | ||
stopped = true; | ||
}; | ||
const run = async (cb) => { | ||
stopped = false; | ||
await cb(stop); | ||
if (stopped) { | ||
return; | ||
} | ||
timerId = workerTimers.setTimeout(() => { | ||
void run(cb); | ||
}, delayInMs); | ||
}; | ||
return { run, stop }; | ||
} | ||
// src/utils/proxy.ts | ||
function isValidProxyUrl(key) { | ||
if (!key) { | ||
return true; | ||
} | ||
return isHttpOrHttps(key) || isProxyUrlRelative(key); | ||
} | ||
function isHttpOrHttps(key) { | ||
return /^http(s)?:\/\//.test(key || ""); | ||
} | ||
function isProxyUrlRelative(key) { | ||
return key.startsWith("/"); | ||
} | ||
function proxyUrlToAbsoluteURL(url) { | ||
if (!url) { | ||
return ""; | ||
} | ||
return isProxyUrlRelative(url) ? new URL(url, window.location.origin).toString() : url; | ||
} | ||
// src/utils/ssr.ts | ||
var inClientSide = () => { | ||
return typeof window !== "undefined"; | ||
}; | ||
// src/utils/url.ts | ||
function parseSearchParams(queryString = "") { | ||
if (queryString.startsWith("?")) { | ||
queryString = queryString.slice(1); | ||
} | ||
return new URLSearchParams(queryString); | ||
} | ||
function stripScheme(url = "") { | ||
return (url || "").replace(/^.+:\/\//, ""); | ||
} | ||
function addClerkPrefix(str) { | ||
if (!str) { | ||
return ""; | ||
} | ||
let regex; | ||
if (str.match(/^(clerk\.)+\w*$/)) { | ||
regex = /(clerk\.)*(?=clerk\.)/; | ||
} else if (str.match(/\.clerk.accounts/)) { | ||
return str; | ||
} else { | ||
regex = /^(clerk\.)*/gi; | ||
} | ||
const stripped = str.replace(regex, ""); | ||
return `clerk.${stripped}`; | ||
} | ||
// src/utils/runWithExponentialBackOff.ts | ||
var defaultOptions = { | ||
maxRetries: 10, | ||
firstDelay: 125, | ||
maxDelay: 0, | ||
timeMultiple: 2, | ||
shouldRetry: () => true | ||
}; | ||
var sleep = async (ms) => new Promise((s) => setTimeout(s, ms)); | ||
var createExponentialDelayAsyncFn = (opts) => { | ||
let timesCalled = 0; | ||
const calculateDelayInMs = () => { | ||
const constant = opts.firstDelay; | ||
const base = opts.timeMultiple; | ||
const delay = constant * Math.pow(base, timesCalled); | ||
return Math.min(opts.maxDelay || delay, delay); | ||
}; | ||
return async () => { | ||
await sleep(calculateDelayInMs()); | ||
timesCalled++; | ||
}; | ||
}; | ||
var runWithExponentialBackOff = async (callback, options = {}) => { | ||
let iterationsCount = 0; | ||
const { maxRetries, shouldRetry, firstDelay, maxDelay, timeMultiple } = { | ||
...defaultOptions, | ||
...options | ||
}; | ||
const maxRetriesReached = () => iterationsCount === maxRetries; | ||
const delay = createExponentialDelayAsyncFn({ firstDelay, maxDelay, timeMultiple }); | ||
while (!maxRetriesReached()) { | ||
try { | ||
return await callback(); | ||
} catch (e) { | ||
iterationsCount++; | ||
if (!shouldRetry(e, iterationsCount) || maxRetriesReached()) { | ||
throw e; | ||
} | ||
await delay(); | ||
} | ||
} | ||
throw new Error("Something went wrong"); | ||
}; | ||
// src/hooks/createContextAndHook.ts | ||
import React from "react"; | ||
function assertContextExists(contextVal, msgOrCtx) { | ||
if (!contextVal) { | ||
throw typeof msgOrCtx === "string" ? new Error(msgOrCtx) : new Error(`${msgOrCtx.displayName} not found`); | ||
} | ||
} | ||
var createContextAndHook = (displayName, options) => { | ||
const { assertCtxFn = assertContextExists } = options || {}; | ||
const Ctx = React.createContext(void 0); | ||
Ctx.displayName = displayName; | ||
const useCtx = () => { | ||
const ctx = React.useContext(Ctx); | ||
assertCtxFn(ctx, `${displayName} not found`); | ||
return ctx.value; | ||
}; | ||
const useCtxWithoutGuarantee = () => { | ||
const ctx = React.useContext(Ctx); | ||
return ctx ? ctx.value : {}; | ||
}; | ||
return [Ctx, useCtx, useCtxWithoutGuarantee]; | ||
}; | ||
// ../../node_modules/swr/dist/index.mjs | ||
import { useEffect, useLayoutEffect, createContext, useContext, useState, createElement, useRef, useCallback, useDebugValue } from "react"; | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
function adopt(value) { | ||
return value instanceof P ? value : new P(function(resolve) { | ||
resolve(value); | ||
}); | ||
} | ||
return new (P || (P = Promise))(function(resolve, reject) { | ||
function fulfilled(value) { | ||
try { | ||
step(generator.next(value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
function rejected(value) { | ||
try { | ||
step(generator["throw"](value)); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
} | ||
function step(result) { | ||
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); | ||
} | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
function __generator(thisArg, body) { | ||
var _ = { label: 0, sent: function() { | ||
if (t[0] & 1) | ||
throw t[1]; | ||
return t[1]; | ||
}, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { | ||
return this; | ||
}), g; | ||
function verb(n) { | ||
return function(v) { | ||
return step([n, v]); | ||
}; | ||
} | ||
function step(op) { | ||
if (f) | ||
throw new TypeError("Generator is already executing."); | ||
while (_) | ||
try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) | ||
return t; | ||
if (y = 0, t) | ||
op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: | ||
case 1: | ||
t = op; | ||
break; | ||
case 4: | ||
_.label++; | ||
return { value: op[1], done: false }; | ||
case 5: | ||
_.label++; | ||
y = op[1]; | ||
op = [0]; | ||
continue; | ||
case 7: | ||
op = _.ops.pop(); | ||
_.trys.pop(); | ||
continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { | ||
_ = 0; | ||
continue; | ||
} | ||
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { | ||
_.label = op[1]; | ||
break; | ||
} | ||
if (op[0] === 6 && _.label < t[1]) { | ||
_.label = t[1]; | ||
t = op; | ||
break; | ||
} | ||
if (t && _.label < t[2]) { | ||
_.label = t[2]; | ||
_.ops.push(op); | ||
break; | ||
} | ||
if (t[2]) | ||
_.ops.pop(); | ||
_.trys.pop(); | ||
continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { | ||
op = [6, e]; | ||
y = 0; | ||
} finally { | ||
f = t = 0; | ||
} | ||
if (op[0] & 5) | ||
throw op[1]; | ||
return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
} | ||
var noop2 = function() { | ||
}; | ||
var UNDEFINED = ( | ||
/*#__NOINLINE__*/ | ||
noop2() | ||
); | ||
var OBJECT = Object; | ||
var isUndefined = function(v) { | ||
return v === UNDEFINED; | ||
}; | ||
var isFunction = function(v) { | ||
return typeof v == "function"; | ||
}; | ||
var mergeObjects = function(a, b) { | ||
return OBJECT.assign({}, a, b); | ||
}; | ||
var STR_UNDEFINED = "undefined"; | ||
var hasWindow = function() { | ||
return typeof window != STR_UNDEFINED; | ||
}; | ||
var hasDocument = function() { | ||
return typeof document != STR_UNDEFINED; | ||
}; | ||
var hasRequestAnimationFrame = function() { | ||
return hasWindow() && typeof window["requestAnimationFrame"] != STR_UNDEFINED; | ||
}; | ||
var table = /* @__PURE__ */ new WeakMap(); | ||
var counter = 0; | ||
var stableHash = function(arg) { | ||
var type = typeof arg; | ||
var constructor = arg && arg.constructor; | ||
var isDate = constructor == Date; | ||
var result; | ||
var index; | ||
if (OBJECT(arg) === arg && !isDate && constructor != RegExp) { | ||
result = table.get(arg); | ||
if (result) | ||
return result; | ||
result = ++counter + "~"; | ||
table.set(arg, result); | ||
if (constructor == Array) { | ||
result = "@"; | ||
for (index = 0; index < arg.length; index++) { | ||
result += stableHash(arg[index]) + ","; | ||
} | ||
table.set(arg, result); | ||
} | ||
if (constructor == OBJECT) { | ||
result = "#"; | ||
var keys = OBJECT.keys(arg).sort(); | ||
while (!isUndefined(index = keys.pop())) { | ||
if (!isUndefined(arg[index])) { | ||
result += index + ":" + stableHash(arg[index]) + ","; | ||
} | ||
} | ||
table.set(arg, result); | ||
} | ||
} else { | ||
result = isDate ? arg.toJSON() : type == "symbol" ? arg.toString() : type == "string" ? JSON.stringify(arg) : "" + arg; | ||
} | ||
return result; | ||
}; | ||
var online = true; | ||
var isOnline = function() { | ||
return online; | ||
}; | ||
var hasWin = hasWindow(); | ||
var hasDoc = hasDocument(); | ||
var onWindowEvent = hasWin && window.addEventListener ? window.addEventListener.bind(window) : noop2; | ||
var onDocumentEvent = hasDoc ? document.addEventListener.bind(document) : noop2; | ||
var offWindowEvent = hasWin && window.removeEventListener ? window.removeEventListener.bind(window) : noop2; | ||
var offDocumentEvent = hasDoc ? document.removeEventListener.bind(document) : noop2; | ||
var isVisible = function() { | ||
var visibilityState = hasDoc && document.visibilityState; | ||
return isUndefined(visibilityState) || visibilityState !== "hidden"; | ||
}; | ||
var initFocus = function(callback) { | ||
onDocumentEvent("visibilitychange", callback); | ||
onWindowEvent("focus", callback); | ||
return function() { | ||
offDocumentEvent("visibilitychange", callback); | ||
offWindowEvent("focus", callback); | ||
}; | ||
}; | ||
var initReconnect = function(callback) { | ||
var onOnline = function() { | ||
online = true; | ||
callback(); | ||
}; | ||
var onOffline = function() { | ||
online = false; | ||
}; | ||
onWindowEvent("online", onOnline); | ||
onWindowEvent("offline", onOffline); | ||
return function() { | ||
offWindowEvent("online", onOnline); | ||
offWindowEvent("offline", onOffline); | ||
}; | ||
}; | ||
var preset = { | ||
isOnline, | ||
isVisible | ||
}; | ||
var defaultConfigOptions = { | ||
initFocus, | ||
initReconnect | ||
}; | ||
var IS_SERVER = !hasWindow() || "Deno" in window; | ||
var rAF = function(f) { | ||
return hasRequestAnimationFrame() ? window["requestAnimationFrame"](f) : setTimeout(f, 1); | ||
}; | ||
var useIsomorphicLayoutEffect = IS_SERVER ? useEffect : useLayoutEffect; | ||
var navigatorConnection = typeof navigator !== "undefined" && navigator.connection; | ||
var slowConnection = !IS_SERVER && navigatorConnection && (["slow-2g", "2g"].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData); | ||
var serialize = function(key) { | ||
if (isFunction(key)) { | ||
try { | ||
key = key(); | ||
} catch (err) { | ||
key = ""; | ||
} | ||
} | ||
var args = [].concat(key); | ||
key = typeof key == "string" ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : ""; | ||
var infoKey = key ? "$swr$" + key : ""; | ||
return [key, args, infoKey]; | ||
}; | ||
var SWRGlobalState = /* @__PURE__ */ new WeakMap(); | ||
var FOCUS_EVENT = 0; | ||
var RECONNECT_EVENT = 1; | ||
var MUTATE_EVENT = 2; | ||
var broadcastState = function(cache2, key, data, error, isValidating, revalidate, broadcast) { | ||
if (broadcast === void 0) { | ||
broadcast = true; | ||
} | ||
var _a2 = SWRGlobalState.get(cache2), EVENT_REVALIDATORS = _a2[0], STATE_UPDATERS = _a2[1], FETCH = _a2[3]; | ||
var revalidators = EVENT_REVALIDATORS[key]; | ||
var updaters = STATE_UPDATERS[key]; | ||
if (broadcast && updaters) { | ||
for (var i = 0; i < updaters.length; ++i) { | ||
updaters[i](data, error, isValidating); | ||
} | ||
} | ||
if (revalidate) { | ||
delete FETCH[key]; | ||
if (revalidators && revalidators[0]) { | ||
return revalidators[0](MUTATE_EVENT).then(function() { | ||
return cache2.get(key); | ||
}); | ||
} | ||
} | ||
return cache2.get(key); | ||
}; | ||
var __timestamp = 0; | ||
var getTimestamp = function() { | ||
return ++__timestamp; | ||
}; | ||
var internalMutate = function() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return __awaiter(void 0, void 0, void 0, function() { | ||
var cache2, _key, _data, _opts, options, populateCache, revalidate, rollbackOnError, customOptimisticData, _a2, key, keyInfo, _b, MUTATION, data, error, beforeMutationTs, hasCustomOptimisticData, rollbackData, optimisticData, res; | ||
return __generator(this, function(_c) { | ||
switch (_c.label) { | ||
case 0: | ||
cache2 = args[0], _key = args[1], _data = args[2], _opts = args[3]; | ||
options = typeof _opts === "boolean" ? { revalidate: _opts } : _opts || {}; | ||
populateCache = isUndefined(options.populateCache) ? true : options.populateCache; | ||
revalidate = options.revalidate !== false; | ||
rollbackOnError = options.rollbackOnError !== false; | ||
customOptimisticData = options.optimisticData; | ||
_a2 = serialize(_key), key = _a2[0], keyInfo = _a2[2]; | ||
if (!key) | ||
return [ | ||
2 | ||
/*return*/ | ||
]; | ||
_b = SWRGlobalState.get(cache2), MUTATION = _b[2]; | ||
if (args.length < 3) { | ||
return [2, broadcastState(cache2, key, cache2.get(key), UNDEFINED, UNDEFINED, revalidate, true)]; | ||
} | ||
data = _data; | ||
beforeMutationTs = getTimestamp(); | ||
MUTATION[key] = [beforeMutationTs, 0]; | ||
hasCustomOptimisticData = !isUndefined(customOptimisticData); | ||
rollbackData = cache2.get(key); | ||
if (hasCustomOptimisticData) { | ||
optimisticData = isFunction(customOptimisticData) ? customOptimisticData(rollbackData) : customOptimisticData; | ||
cache2.set(key, optimisticData); | ||
broadcastState(cache2, key, optimisticData); | ||
} | ||
if (isFunction(data)) { | ||
try { | ||
data = data(cache2.get(key)); | ||
} catch (err) { | ||
error = err; | ||
} | ||
} | ||
if (!(data && isFunction(data.then))) | ||
return [3, 2]; | ||
return [ | ||
4, | ||
data.catch(function(err) { | ||
error = err; | ||
}) | ||
// Check if other mutations have occurred since we've started this mutation. | ||
// If there's a race we don't update cache or broadcast the change, | ||
// just return the data. | ||
]; | ||
case 1: | ||
data = _c.sent(); | ||
if (beforeMutationTs !== MUTATION[key][0]) { | ||
if (error) | ||
throw error; | ||
return [2, data]; | ||
} else if (error && hasCustomOptimisticData && rollbackOnError) { | ||
populateCache = true; | ||
data = rollbackData; | ||
cache2.set(key, rollbackData); | ||
} | ||
_c.label = 2; | ||
case 2: | ||
if (populateCache) { | ||
if (!error) { | ||
if (isFunction(populateCache)) { | ||
data = populateCache(data, rollbackData); | ||
} | ||
cache2.set(key, data); | ||
} | ||
cache2.set(keyInfo, mergeObjects(cache2.get(keyInfo), { error })); | ||
} | ||
MUTATION[key][1] = getTimestamp(); | ||
return [ | ||
4, | ||
broadcastState(cache2, key, data, error, UNDEFINED, revalidate, !!populateCache) | ||
// Throw error or return data | ||
]; | ||
case 3: | ||
res = _c.sent(); | ||
if (error) | ||
throw error; | ||
return [2, populateCache ? res : data]; | ||
} | ||
}); | ||
}); | ||
}; | ||
var revalidateAllKeys = function(revalidators, type) { | ||
for (var key in revalidators) { | ||
if (revalidators[key][0]) | ||
revalidators[key][0](type); | ||
} | ||
}; | ||
var initCache = function(provider, options) { | ||
if (!SWRGlobalState.has(provider)) { | ||
var opts = mergeObjects(defaultConfigOptions, options); | ||
var EVENT_REVALIDATORS = {}; | ||
var mutate2 = internalMutate.bind(UNDEFINED, provider); | ||
var unmount = noop2; | ||
SWRGlobalState.set(provider, [EVENT_REVALIDATORS, {}, {}, {}, mutate2]); | ||
if (!IS_SERVER) { | ||
var releaseFocus_1 = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT))); | ||
var releaseReconnect_1 = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT))); | ||
unmount = function() { | ||
releaseFocus_1 && releaseFocus_1(); | ||
releaseReconnect_1 && releaseReconnect_1(); | ||
SWRGlobalState.delete(provider); | ||
}; | ||
} | ||
return [provider, mutate2, unmount]; | ||
} | ||
return [provider, SWRGlobalState.get(provider)[4]]; | ||
}; | ||
var onErrorRetry = function(_, __, config, revalidate, opts) { | ||
var maxRetryCount = config.errorRetryCount; | ||
var currentRetryCount = opts.retryCount; | ||
var timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval; | ||
if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) { | ||
return; | ||
} | ||
setTimeout(revalidate, timeout, opts); | ||
}; | ||
var _a = initCache(/* @__PURE__ */ new Map()); | ||
var cache = _a[0]; | ||
var mutate = _a[1]; | ||
var defaultConfig = mergeObjects( | ||
{ | ||
// events | ||
onLoadingSlow: noop2, | ||
onSuccess: noop2, | ||
onError: noop2, | ||
onErrorRetry, | ||
onDiscarded: noop2, | ||
// switches | ||
revalidateOnFocus: true, | ||
revalidateOnReconnect: true, | ||
revalidateIfStale: true, | ||
shouldRetryOnError: true, | ||
// timeouts | ||
errorRetryInterval: slowConnection ? 1e4 : 5e3, | ||
focusThrottleInterval: 5 * 1e3, | ||
dedupingInterval: 2 * 1e3, | ||
loadingTimeout: slowConnection ? 5e3 : 3e3, | ||
// providers | ||
compare: function(currentData, newData) { | ||
return stableHash(currentData) == stableHash(newData); | ||
}, | ||
isPaused: function() { | ||
return false; | ||
}, | ||
cache, | ||
mutate, | ||
fallback: {} | ||
}, | ||
// use web preset by default | ||
preset | ||
); | ||
var mergeConfigs = function(a, b) { | ||
var v = mergeObjects(a, b); | ||
if (b) { | ||
var u1 = a.use, f1 = a.fallback; | ||
var u2 = b.use, f2 = b.fallback; | ||
if (u1 && u2) { | ||
v.use = u1.concat(u2); | ||
} | ||
if (f1 && f2) { | ||
v.fallback = mergeObjects(f1, f2); | ||
} | ||
} | ||
return v; | ||
}; | ||
var SWRConfigContext = createContext({}); | ||
var SWRConfig$1 = function(props) { | ||
var value = props.value; | ||
var extendedConfig = mergeConfigs(useContext(SWRConfigContext), value); | ||
var provider = value && value.provider; | ||
var cacheContext = useState(function() { | ||
return provider ? initCache(provider(extendedConfig.cache || cache), value) : UNDEFINED; | ||
})[0]; | ||
if (cacheContext) { | ||
extendedConfig.cache = cacheContext[0]; | ||
extendedConfig.mutate = cacheContext[1]; | ||
} | ||
useIsomorphicLayoutEffect(function() { | ||
return cacheContext ? cacheContext[2] : UNDEFINED; | ||
}, []); | ||
return createElement(SWRConfigContext.Provider, mergeObjects(props, { | ||
value: extendedConfig | ||
})); | ||
}; | ||
var useStateWithDeps = function(state, unmountedRef) { | ||
var rerender = useState({})[1]; | ||
var stateRef = useRef(state); | ||
var stateDependenciesRef = useRef({ | ||
data: false, | ||
error: false, | ||
isValidating: false | ||
}); | ||
var setState = useCallback( | ||
function(payload) { | ||
var shouldRerender = false; | ||
var currentState = stateRef.current; | ||
for (var _ in payload) { | ||
var k = _; | ||
if (currentState[k] !== payload[k]) { | ||
currentState[k] = payload[k]; | ||
if (stateDependenciesRef.current[k]) { | ||
shouldRerender = true; | ||
} | ||
} | ||
} | ||
if (shouldRerender && !unmountedRef.current) { | ||
rerender({}); | ||
} | ||
}, | ||
// config.suspense isn't allowed to change during the lifecycle | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
[] | ||
); | ||
useIsomorphicLayoutEffect(function() { | ||
stateRef.current = state; | ||
}); | ||
return [stateRef, stateDependenciesRef.current, setState]; | ||
}; | ||
var normalize = function(args) { | ||
return isFunction(args[1]) ? [args[0], args[1], args[2] || {}] : [args[0], null, (args[1] === null ? args[2] : args[1]) || {}]; | ||
}; | ||
var useSWRConfig = function() { | ||
return mergeObjects(defaultConfig, useContext(SWRConfigContext)); | ||
}; | ||
var withArgs = function(hook) { | ||
return function useSWRArgs() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var fallbackConfig = useSWRConfig(); | ||
var _a2 = normalize(args), key = _a2[0], fn = _a2[1], _config = _a2[2]; | ||
var config = mergeConfigs(fallbackConfig, _config); | ||
var next = hook; | ||
var use = config.use; | ||
if (use) { | ||
for (var i = use.length; i-- > 0; ) { | ||
next = use[i](next); | ||
} | ||
} | ||
return next(key, fn || config.fetcher, config); | ||
}; | ||
}; | ||
var subscribeCallback = function(key, callbacks, callback) { | ||
var keyedRevalidators = callbacks[key] || (callbacks[key] = []); | ||
keyedRevalidators.push(callback); | ||
return function() { | ||
var index = keyedRevalidators.indexOf(callback); | ||
if (index >= 0) { | ||
keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1]; | ||
keyedRevalidators.pop(); | ||
} | ||
}; | ||
}; | ||
var WITH_DEDUPE = { dedupe: true }; | ||
var useSWRHandler = function(_key, fetcher, config) { | ||
var cache2 = config.cache, compare = config.compare, fallbackData = config.fallbackData, suspense = config.suspense, revalidateOnMount = config.revalidateOnMount, refreshInterval = config.refreshInterval, refreshWhenHidden = config.refreshWhenHidden, refreshWhenOffline = config.refreshWhenOffline; | ||
var _a2 = SWRGlobalState.get(cache2), EVENT_REVALIDATORS = _a2[0], STATE_UPDATERS = _a2[1], MUTATION = _a2[2], FETCH = _a2[3]; | ||
var _b = serialize(_key), key = _b[0], fnArgs = _b[1], keyInfo = _b[2]; | ||
var initialMountedRef = useRef(false); | ||
var unmountedRef = useRef(false); | ||
var keyRef = useRef(key); | ||
var fetcherRef = useRef(fetcher); | ||
var configRef = useRef(config); | ||
var getConfig = function() { | ||
return configRef.current; | ||
}; | ||
var isActive = function() { | ||
return getConfig().isVisible() && getConfig().isOnline(); | ||
}; | ||
var patchFetchInfo = function(info2) { | ||
return cache2.set(keyInfo, mergeObjects(cache2.get(keyInfo), info2)); | ||
}; | ||
var cached = cache2.get(key); | ||
var fallback = isUndefined(fallbackData) ? config.fallback[key] : fallbackData; | ||
var data = isUndefined(cached) ? fallback : cached; | ||
var info = cache2.get(keyInfo) || {}; | ||
var error = info.error; | ||
var isInitialMount = !initialMountedRef.current; | ||
var shouldRevalidate = function() { | ||
if (isInitialMount && !isUndefined(revalidateOnMount)) | ||
return revalidateOnMount; | ||
if (getConfig().isPaused()) | ||
return false; | ||
if (suspense) | ||
return isUndefined(data) ? false : config.revalidateIfStale; | ||
return isUndefined(data) || config.revalidateIfStale; | ||
}; | ||
var resolveValidating = function() { | ||
if (!key || !fetcher) | ||
return false; | ||
if (info.isValidating) | ||
return true; | ||
return isInitialMount && shouldRevalidate(); | ||
}; | ||
var isValidating = resolveValidating(); | ||
var _c = useStateWithDeps({ | ||
data, | ||
error, | ||
isValidating | ||
}, unmountedRef), stateRef = _c[0], stateDependencies = _c[1], setState = _c[2]; | ||
var revalidate = useCallback( | ||
function(revalidateOpts) { | ||
return __awaiter(void 0, void 0, void 0, function() { | ||
var currentFetcher, newData, startAt, loading, opts, shouldStartNewRequest, isCurrentKeyMounted, cleanupState, newState, finishRequestAndUpdateState, mutationInfo, err_1; | ||
var _a3; | ||
return __generator(this, function(_b2) { | ||
switch (_b2.label) { | ||
case 0: | ||
currentFetcher = fetcherRef.current; | ||
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) { | ||
return [2, false]; | ||
} | ||
loading = true; | ||
opts = revalidateOpts || {}; | ||
shouldStartNewRequest = !FETCH[key] || !opts.dedupe; | ||
isCurrentKeyMounted = function() { | ||
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current; | ||
}; | ||
cleanupState = function() { | ||
var requestInfo = FETCH[key]; | ||
if (requestInfo && requestInfo[1] === startAt) { | ||
delete FETCH[key]; | ||
} | ||
}; | ||
newState = { isValidating: false }; | ||
finishRequestAndUpdateState = function() { | ||
patchFetchInfo({ isValidating: false }); | ||
if (isCurrentKeyMounted()) { | ||
setState(newState); | ||
} | ||
}; | ||
patchFetchInfo({ | ||
isValidating: true | ||
}); | ||
setState({ isValidating: true }); | ||
_b2.label = 1; | ||
case 1: | ||
_b2.trys.push([1, 3, , 4]); | ||
if (shouldStartNewRequest) { | ||
broadcastState(cache2, key, stateRef.current.data, stateRef.current.error, true); | ||
if (config.loadingTimeout && !cache2.get(key)) { | ||
setTimeout(function() { | ||
if (loading && isCurrentKeyMounted()) { | ||
getConfig().onLoadingSlow(key, config); | ||
} | ||
}, config.loadingTimeout); | ||
} | ||
FETCH[key] = [currentFetcher.apply(void 0, fnArgs), getTimestamp()]; | ||
} | ||
_a3 = FETCH[key], newData = _a3[0], startAt = _a3[1]; | ||
return [4, newData]; | ||
case 2: | ||
newData = _b2.sent(); | ||
if (shouldStartNewRequest) { | ||
setTimeout(cleanupState, config.dedupingInterval); | ||
} | ||
if (!FETCH[key] || FETCH[key][1] !== startAt) { | ||
if (shouldStartNewRequest) { | ||
if (isCurrentKeyMounted()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return [2, false]; | ||
} | ||
patchFetchInfo({ | ||
error: UNDEFINED | ||
}); | ||
newState.error = UNDEFINED; | ||
mutationInfo = MUTATION[key]; | ||
if (!isUndefined(mutationInfo) && // case 1 | ||
(startAt <= mutationInfo[0] || // case 2 | ||
startAt <= mutationInfo[1] || // case 3 | ||
mutationInfo[1] === 0)) { | ||
finishRequestAndUpdateState(); | ||
if (shouldStartNewRequest) { | ||
if (isCurrentKeyMounted()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return [2, false]; | ||
} | ||
if (!compare(stateRef.current.data, newData)) { | ||
newState.data = newData; | ||
} else { | ||
newState.data = stateRef.current.data; | ||
} | ||
if (!compare(cache2.get(key), newData)) { | ||
cache2.set(key, newData); | ||
} | ||
if (shouldStartNewRequest) { | ||
if (isCurrentKeyMounted()) { | ||
getConfig().onSuccess(newData, key, config); | ||
} | ||
} | ||
return [3, 4]; | ||
case 3: | ||
err_1 = _b2.sent(); | ||
cleanupState(); | ||
if (!getConfig().isPaused()) { | ||
patchFetchInfo({ error: err_1 }); | ||
newState.error = err_1; | ||
if (shouldStartNewRequest && isCurrentKeyMounted()) { | ||
getConfig().onError(err_1, key, config); | ||
if (typeof config.shouldRetryOnError === "boolean" && config.shouldRetryOnError || isFunction(config.shouldRetryOnError) && config.shouldRetryOnError(err_1)) { | ||
if (isActive()) { | ||
getConfig().onErrorRetry(err_1, key, config, revalidate, { | ||
retryCount: (opts.retryCount || 0) + 1, | ||
dedupe: true | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
return [3, 4]; | ||
case 4: | ||
loading = false; | ||
finishRequestAndUpdateState(); | ||
if (isCurrentKeyMounted() && shouldStartNewRequest) { | ||
broadcastState(cache2, key, newState.data, newState.error, false); | ||
} | ||
return [2, true]; | ||
} | ||
}); | ||
}); | ||
}, | ||
// `setState` is immutable, and `eventsCallback`, `fnArgs`, `keyInfo`, | ||
// and `keyValidating` are depending on `key`, so we can exclude them from | ||
// the deps array. | ||
// | ||
// FIXME: | ||
// `fn` and `config` might be changed during the lifecycle, | ||
// but they might be changed every render like this. | ||
// `useSWR('key', () => fetch('/api/'), { suspense: true })` | ||
// So we omit the values from the deps array | ||
// even though it might cause unexpected behaviors. | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
[key] | ||
); | ||
var boundMutate = useCallback( | ||
// By using `bind` we don't need to modify the size of the rest arguments. | ||
// Due to https://github.com/microsoft/TypeScript/issues/37181, we have to | ||
// cast it to any for now. | ||
internalMutate.bind(UNDEFINED, cache2, function() { | ||
return keyRef.current; | ||
}), | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
[] | ||
); | ||
useIsomorphicLayoutEffect(function() { | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
}); | ||
useIsomorphicLayoutEffect(function() { | ||
if (!key) | ||
return; | ||
var keyChanged = key !== keyRef.current; | ||
var softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE); | ||
var onStateUpdate = function(updatedData, updatedError, updatedIsValidating) { | ||
setState(mergeObjects( | ||
{ | ||
error: updatedError, | ||
isValidating: updatedIsValidating | ||
}, | ||
// Since `setState` only shallowly compares states, we do a deep | ||
// comparison here. | ||
compare(stateRef.current.data, updatedData) ? UNDEFINED : { | ||
data: updatedData | ||
} | ||
)); | ||
}; | ||
var nextFocusRevalidatedAt = 0; | ||
var onRevalidate = function(type) { | ||
if (type == FOCUS_EVENT) { | ||
var now = Date.now(); | ||
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) { | ||
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval; | ||
softRevalidate(); | ||
} | ||
} else if (type == RECONNECT_EVENT) { | ||
if (getConfig().revalidateOnReconnect && isActive()) { | ||
softRevalidate(); | ||
} | ||
} else if (type == MUTATE_EVENT) { | ||
return revalidate(); | ||
} | ||
return; | ||
}; | ||
var unsubUpdate = subscribeCallback(key, STATE_UPDATERS, onStateUpdate); | ||
var unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate); | ||
unmountedRef.current = false; | ||
keyRef.current = key; | ||
initialMountedRef.current = true; | ||
if (keyChanged) { | ||
setState({ | ||
data, | ||
error, | ||
isValidating | ||
}); | ||
} | ||
if (shouldRevalidate()) { | ||
if (isUndefined(data) || IS_SERVER) { | ||
softRevalidate(); | ||
} else { | ||
rAF(softRevalidate); | ||
} | ||
} | ||
return function() { | ||
unmountedRef.current = true; | ||
unsubUpdate(); | ||
unsubEvents(); | ||
}; | ||
}, [key, revalidate]); | ||
useIsomorphicLayoutEffect(function() { | ||
var timer; | ||
function next() { | ||
var interval = isFunction(refreshInterval) ? refreshInterval(data) : refreshInterval; | ||
if (interval && timer !== -1) { | ||
timer = setTimeout(execute, interval); | ||
} | ||
} | ||
function execute() { | ||
if (!stateRef.current.error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) { | ||
revalidate(WITH_DEDUPE).then(next); | ||
} else { | ||
next(); | ||
} | ||
} | ||
next(); | ||
return function() { | ||
if (timer) { | ||
clearTimeout(timer); | ||
timer = -1; | ||
} | ||
}; | ||
}, [refreshInterval, refreshWhenHidden, refreshWhenOffline, revalidate]); | ||
useDebugValue(data); | ||
if (suspense && isUndefined(data) && key) { | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
unmountedRef.current = false; | ||
throw isUndefined(error) ? revalidate(WITH_DEDUPE) : error; | ||
} | ||
return { | ||
mutate: boundMutate, | ||
get data() { | ||
stateDependencies.data = true; | ||
return data; | ||
}, | ||
get error() { | ||
stateDependencies.error = true; | ||
return error; | ||
}, | ||
get isValidating() { | ||
stateDependencies.isValidating = true; | ||
return isValidating; | ||
} | ||
}; | ||
}; | ||
var SWRConfig = OBJECT.defineProperty(SWRConfig$1, "default", { | ||
value: defaultConfig | ||
}); | ||
var useSWR = withArgs(useSWRHandler); | ||
// src/hooks/contexts.tsx | ||
var [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook("ClerkInstanceContext"); | ||
var [UserContext, useUserContext] = createContextAndHook("UserContext"); | ||
var [ClientContext, useClientContext] = createContextAndHook("ClientContext"); | ||
var [SessionContext, useSessionContext] = createContextAndHook( | ||
"SessionContext" | ||
); | ||
var [OrganizationContext, useOrganizationContext] = createContextAndHook("OrganizationContext"); | ||
// src/hooks/useOrganization.tsx | ||
var useOrganization = (params) => { | ||
const { invitationList: invitationListParams, membershipList: membershipListParams } = params || {}; | ||
const { organization, lastOrganizationMember, lastOrganizationInvitation } = useOrganizationContext(); | ||
const session = useSessionContext(); | ||
const clerk = useClerkInstanceContext(); | ||
const shouldFetch = clerk.loaded && session && organization; | ||
const pendingInvitations = !clerk.loaded ? () => [] : () => clerk.organization?.getPendingInvitations(invitationListParams); | ||
const currentOrganizationMemberships = !clerk.loaded ? () => [] : () => clerk.organization?.getMemberships(membershipListParams); | ||
const { | ||
data: invitationList, | ||
isValidating: isInvitationsLoading, | ||
mutate: mutateInvitationList | ||
} = useSWR( | ||
shouldFetch && invitationListParams ? cacheKey("invites", organization, lastOrganizationInvitation, invitationListParams) : null, | ||
pendingInvitations | ||
); | ||
const { | ||
data: membershipList, | ||
isValidating: isMembershipsLoading, | ||
mutate: mutateMembershipList | ||
} = useSWR( | ||
shouldFetch && membershipListParams ? cacheKey("memberships", organization, lastOrganizationMember, membershipListParams) : null, | ||
currentOrganizationMemberships | ||
); | ||
if (organization === void 0) { | ||
return { | ||
isLoaded: false, | ||
organization: void 0, | ||
invitationList: void 0, | ||
membershipList: void 0, | ||
membership: void 0 | ||
}; | ||
} | ||
if (organization === null) { | ||
return { | ||
isLoaded: true, | ||
organization: null, | ||
invitationList: null, | ||
membershipList: null, | ||
membership: null | ||
}; | ||
} | ||
if (!clerk.loaded && organization) { | ||
return { | ||
isLoaded: true, | ||
organization, | ||
invitationList: void 0, | ||
membershipList: void 0, | ||
membership: void 0 | ||
}; | ||
} | ||
return { | ||
isLoaded: !isMembershipsLoading && !isInvitationsLoading, | ||
organization, | ||
membershipList, | ||
membership: getCurrentOrganizationMembership(session.user.organizationMemberships, organization.id), | ||
// your membership in the current org | ||
invitationList, | ||
unstable__mutate: () => { | ||
void mutateMembershipList(); | ||
void mutateInvitationList(); | ||
} | ||
}; | ||
}; | ||
function getCurrentOrganizationMembership(organizationMemberships, activeOrganizationId) { | ||
return organizationMemberships.find( | ||
(organizationMembership) => organizationMembership.organization.id === activeOrganizationId | ||
); | ||
} | ||
function cacheKey(type, organization, resource, pagination) { | ||
return [type, organization.id, resource?.id, resource?.updatedAt, pagination.offset, pagination.limit].filter(Boolean).join("-"); | ||
} | ||
// src/hooks/useOrganizationList.tsx | ||
var useOrganizationList = () => { | ||
const clerk = useClerkInstanceContext(); | ||
const user = useUserContext(); | ||
if (!clerk.loaded || !user) { | ||
return { isLoaded: false, organizationList: void 0, createOrganization: void 0, setActive: void 0 }; | ||
} | ||
return { | ||
isLoaded: true, | ||
organizationList: createOrganizationList(user.organizationMemberships), | ||
setActive: clerk.setActive, | ||
createOrganization: clerk.createOrganization | ||
}; | ||
}; | ||
function createOrganizationList(organizationMemberships) { | ||
return organizationMemberships.map((organizationMembership) => ({ | ||
membership: organizationMembership, | ||
organization: organizationMembership.organization | ||
})); | ||
} | ||
// src/hooks/useOrganizations.tsx | ||
var useOrganizations = () => { | ||
const clerk = useClerkInstanceContext(); | ||
if (!clerk.loaded) { | ||
return { | ||
isLoaded: false, | ||
createOrganization: void 0, | ||
getOrganizationMemberships: void 0, | ||
getOrganization: void 0 | ||
}; | ||
} | ||
return { | ||
isLoaded: true, | ||
createOrganization: clerk.createOrganization, | ||
getOrganizationMemberships: clerk.getOrganizationMemberships, | ||
getOrganization: clerk.getOrganization | ||
}; | ||
}; | ||
// src/hooks/useSafeLayoutEffect.tsx | ||
import React2 from "react"; | ||
var useSafeLayoutEffect = typeof window !== "undefined" ? React2.useLayoutEffect : React2.useEffect; | ||
export { | ||
ClerkInstanceContext, | ||
ClientContext, | ||
LocalStorageBroadcastChannel, | ||
OrganizationContext, | ||
Poller, | ||
SessionContext, | ||
UserContext, | ||
addClerkPrefix, | ||
addYears, | ||
assertContextExists, | ||
buildErrorThrower, | ||
buildPublishableKey, | ||
camelToSnake, | ||
colorToSameTypeString, | ||
createContextAndHook, | ||
createCookieHandler, | ||
createDeferredPromise, | ||
createDevOrStagingUrlCache, | ||
createWorkerTimers, | ||
dateTo12HourTime, | ||
deepCamelToSnake, | ||
deepSnakeToCamel, | ||
detectUserAgentRobot, | ||
differenceInCalendarDays, | ||
extension, | ||
formatRelative, | ||
handleValueOrFn, | ||
hasAlpha, | ||
hexStringToRgbaColor, | ||
inBrowser, | ||
inClientSide, | ||
isHSLColor, | ||
isHttpOrHttps, | ||
isIPV4Address, | ||
isLegacyFrontendApiKey, | ||
isNetworkError, | ||
isProxyUrlRelative, | ||
isPublishableKey, | ||
isRGBColor, | ||
isRetinaDisplay, | ||
isTransparent, | ||
isUnauthorizedError, | ||
isValidBrowserOnline, | ||
isValidHexString, | ||
isValidHslaString, | ||
isValidProxyUrl, | ||
isValidRgbaString, | ||
isomorphicAtob, | ||
noop, | ||
normalizeDate, | ||
parsePublishableKey, | ||
parseSearchParams, | ||
proxyUrlToAbsoluteURL, | ||
readJSONFile, | ||
runWithExponentialBackOff, | ||
snakeToCamel, | ||
stringToHslaColor, | ||
stringToSameTypeColor, | ||
stripScheme, | ||
titleize, | ||
toSentence, | ||
useClerkInstanceContext, | ||
useClientContext, | ||
useOrganization, | ||
useOrganizationContext, | ||
useOrganizationList, | ||
useOrganizations, | ||
useSafeLayoutEffect, | ||
useSessionContext, | ||
useUserContext | ||
}; | ||
import{c as Z}from"./chunk-GW3MP3TA.js";var St=Object.freeze({InvalidFrontendApiErrorMessage:"The frontendApi passed to Clerk is invalid. You can get your Frontend API key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})",InvalidProxyUrlErrorMessage:"The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})",InvalidPublishableKeyErrorMessage:"The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})",MissingPublishableKeyErrorMessage:"Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys."});function It({packageName:e,customMessages:r}){let t=e,n={...St,...r};function o(i,a){if(!a)return`${t}: ${i}`;let u=i,f=i.matchAll(/{{([a-zA-Z0-9-_]+)}}/g);for(let s of f){let l=(a[s[1]]||"").toString();u=u.replace(`{{${s[1]}}}`,l)}return`${t}: ${u}`}return{setPackageName({packageName:i}){return typeof i=="string"&&(t=i),this},setMessages({customMessages:i}){return Object.assign(n,i||{}),this},throwInvalidPublishableKeyError(i){throw new Error(o(n.InvalidPublishableKeyErrorMessage,i))},throwInvalidFrontendApiError(i){throw new Error(o(n.InvalidFrontendApiErrorMessage,i))},throwInvalidProxyUrl(i){throw new Error(o(n.InvalidProxyUrlErrorMessage,i))},throwMissingPublishableKeyError(){throw new Error(o(n.MissingPublishableKeyErrorMessage))}}}var Nr=e=>{if(e.length==0)return"";if(e.length==1)return e[0];let r=e.slice(0,-1).join(", ");return r+=`, or ${e.slice(-1)}`,r};function Lt(){return typeof window<"u"}function zt(e){return new RegExp([/bot/,/spider/,/crawl/,/APIs-Google/,/AdsBot/,/Googlebot/,/mediapartners/,/Google Favicon/,/FeedFetcher/,/Google-Read-Aloud/,/DuplexWeb-Google/,/googleweblight/,/bing/,/yandex/,/baidu/,/duckduck/,/yahoo/,/ecosia/,/ia_archiver/,/facebook/,/instagram/,/pinterest/,/reddit/,/slack/,/twitter/,/whatsapp/,/youtube/,/semrush/].map(t=>t.source).join("|"),"i").test(e)}function Kr(){let e=window?.navigator;if(!Lt()||!e)return!1;let r=zt(e?.userAgent),t=e?.webdriver,n=e?.onLine,o=e?.connection?.rtt!==0&&e?.connection?.downlink!==0;return!r&&!t&&o&&n}var Mt=/^#?([A-F0-9]{6}|[A-F0-9]{3})$/i,Dt=/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/i,Pt=/^rgba\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+(\.\d+)?)\)$/i,At=/^hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)$/i,Ut=/^hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%(,\s*\d+(\.\d+)?)*\)$/i,oe=e=>!!e.match(Mt),ve=e=>!!(e.match(Dt)||e.match(Pt)),he=e=>!!e.match(At)||!!e.match(Ut),Be=e=>typeof e!="string"&&"r"in e,je=e=>typeof e!="string"&&"h"in e,be=e=>e==="transparent",jr=e=>typeof e!="string"&&e.a!=null&&e.a<1;var _t=/[hsla()]/g,Wt=/[rgba()]/g,Jr=e=>e==="transparent"?{h:0,s:0,l:0,a:0}:oe(e)?Nt(e):he(e)?Je(e):ve(e)?Xe(e):null,qr=e=>(e=e.trim(),oe(e)?e.startsWith("#")?e:`#${e}`:ve(e)?Ye(e):he(e)?Je(e):be(e)?e:""),Ft=e=>typeof e=="string"&&(oe(e)||be(e))?e:Be(e)?$t(e):je(e)?Ht(e):"",Vt=e=>{e=e.replace("#","");let r=parseInt(e.substring(0,2),16),t=parseInt(e.substring(2,4),16),n=parseInt(e.substring(4,6),16);return{r,g:t,b:n}},$t=e=>{let{a:r,b:t,g:n,r:o}=e;return e.a===0?"transparent":e.a!=null?`rgba(${o},${n},${t},${r})`:`rgb(${o},${n},${t})`},Ht=e=>{let{h:r,s:t,l:n,a:o}=e,i=Math.round(t*100),a=Math.round(n*100);return e.a===0?"transparent":e.a!=null?`hsla(${r},${i}%,${a}%,${o})`:`hsl(${r},${i}%,${a}%)`},Nt=e=>{let r=Ft(Vt(e));return Xe(r)},Xe=e=>{let r=Ye(e),t=r.r/255,n=r.g/255,o=r.b/255,i=Math.max(t,n,o),a=Math.min(t,n,o),u,f,s=(i+a)/2;if(i==a)u=f=0;else{let c=i-a;switch(f=s>=.5?c/(2-(i+a)):c/(i+a),i){case t:u=(n-o)/c*60;break;case n:u=((o-t)/c+2)*60;break;default:u=((t-n)/c+4)*60;break}}let l={h:Math.round(u),s:f,l:s},p=r.a;return p!=null&&(l.a=p),l},Ye=e=>{let[r,t,n,o]=e.replace(Wt,"").split(",").map(i=>Number.parseFloat(i));return{r,g:t,b:n,a:o}},Je=e=>{let[r,t,n,o]=e.replace(_t,"").split(",").map(i=>Number.parseFloat(i));return{h:r,s:t/100,l:n/100,a:o}};function ae(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)e[n]=t[n]}return e}var Gt={read:function(e){return e[0]==='"'&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function ye(e,r){function t(o,i,a){if(!(typeof document>"u")){a=ae({},r,a),typeof a.expires=="number"&&(a.expires=new Date(Date.now()+a.expires*864e5)),a.expires&&(a.expires=a.expires.toUTCString()),o=encodeURIComponent(o).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var f in a)a[f]&&(u+="; "+f,a[f]!==!0&&(u+="="+a[f].split(";")[0]));return document.cookie=o+"="+e.write(i,o)+u}}function n(o){if(!(typeof document>"u"||arguments.length&&!o)){for(var i=document.cookie?document.cookie.split("; "):[],a={},u=0;u<i.length;u++){var f=i[u].split("="),s=f.slice(1).join("=");try{var l=decodeURIComponent(f[0]);if(a[l]=e.read(s,l),o===l)break}catch{}}return o?a[o]:a}}return Object.create({set:t,get:n,remove:function(o,i){t(o,"",ae({},i,{expires:-1}))},withAttributes:function(o){return ye(this.converter,ae({},this.attributes,o))},withConverter:function(o){return ye(ae({},this.converter,o),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(e)}})}var Kt=ye(Gt,{path:"/"}),se=Kt;function tn(e){return{get(){return se.get(e)},set(r,t={}){return se.set(e,r,t)},remove(r){se.remove(e,r)}}}var on=()=>{let e=Z,r=Z;return{promise:new Promise((n,o)=>{e=n,r=o}),resolve:e,reject:r}};function sn(e){return e?e.toLocaleString("en-US",{hour:"2-digit",minute:"numeric",hour12:!0}):""}function Bt(e,r,{absolute:t=!0}={}){if(!e||!r)return 0;let n=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()),o=Date.UTC(r.getFullYear(),r.getMonth(),r.getDate()),i=Math.floor((o-n)/864e5);return t?Math.abs(i):i}function Ce(e){try{return new Date(e||new Date)}catch{return new Date}}function un(e){let{date:r,relativeTo:t}=e;if(!r||!t)return null;let n=Ce(r),o=Ce(t),i=Bt(o,n,{absolute:!1});return i<-6?{relativeDateCase:"other",date:n}:i<-1?{relativeDateCase:"previous6Days",date:n}:i===-1?{relativeDateCase:"lastDay",date:n}:i===0?{relativeDateCase:"sameDay",date:n}:i===1?{relativeDateCase:"nextDay",date:n}:i<7?{relativeDateCase:"next6Days",date:n}:{relativeDateCase:"other",date:n}}function ln(e,r){let t=Ce(e);return t.setFullYear(t.getFullYear()+r),t}function dn(e){let r=e?.status;return e?.errors?.[0]?.code==="authentication_invalid"&&r===401}function fn(e){return(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")}function gn(e){return new Promise((r,t)=>{let n=new FileReader;n.addEventListener("load",function(){let o=JSON.parse(n.result);r(o)}),n.addEventListener("error",t),n.readAsText(e)})}var xe=e=>typeof atob<"u"&&typeof atob=="function"?atob(e):typeof global<"u"&&global.Buffer?new global.Buffer(e,"base64").toString():e;var Te="pk_live_",qe="pk_test_",jt=/^(([a-z]+)-){2}([0-9]{1,2})\.clerk\.accounts([a-z.]*)(dev|com)$/i;function bn(e){return`${jt.test(e)?qe:Te}${btoa(`${e}$`)}`}function yn(e){if(e=e||"",!Xt(e))return null;let r=e.startsWith(Te)?"production":"development",t=xe(e.split("_")[2]);return t.endsWith("$")?(t=t.slice(0,-1),{instanceType:r,frontendApi:t}):null}function Xt(e){e=e||"";let r=e.startsWith(Te)||e.startsWith(qe),t=xe(e.split("_")[2]||"").endsWith("$");return r&&t}function Cn(e){return e=e||"",e.startsWith("clerk.")}function xn(){let e=[".lcl.dev",".stg.dev",".lclstage.dev",".stgstage.dev",".dev.lclclerk.com",".stg.lclclerk.com",".accounts.lclclerk.com","accountsstage.dev","accounts.dev"],r=new Map;return{isDevOrStagingUrl:t=>{if(!t)return!1;let n=typeof t=="string"?t:t.hostname,o=r.get(n);return o===void 0&&(o=e.some(i=>n.endsWith(i)),r.set(n,o)),o}}}function Rn(){if(!window.matchMedia)return!1;let e=window.matchMedia("only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)");return e&&e.matches||window.devicePixelRatio>1}var Yt="__lsbc__",Ze=class{constructor(r){this.eventTarget=window;this.postMessage=r=>{try{localStorage.setItem(this.channelKey,JSON.stringify(r)),localStorage.removeItem(this.channelKey)}catch{}};this.addEventListener=(r,t)=>{this.eventTarget.addEventListener(this.prefixEventName(r),n=>{t(n)})};this.setupLocalStorageListener=()=>{let r=t=>{if(!(t.key!==this.channelKey||!t.newValue))try{let n=JSON.parse(t.newValue||""),o=new MessageEvent(this.prefixEventName("message"),{data:n});this.eventTarget.dispatchEvent(o)}catch{}};window.addEventListener("storage",r)};this.channelKey=Yt+r,this.setupLocalStorageListener()}prefixEventName(r){return this.channelKey+r}};var Jt=Object.freeze({"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/x-icon":"ico","image/vnd.microsoft.icon":"ico"}),En=e=>Jt[e];function Sn(e,r,t){if(typeof e=="function")return e(r);if(typeof e<"u")return e;if(typeof t<"u")return t}var qt=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;function Ln(e){return qt.test(e||"")}function zn(e){let r=e||"";return r.charAt(0).toUpperCase()+r.slice(1)}function Qe(e){return e?e.replace(/([-_][a-z])/g,r=>r.toUpperCase().replace(/-|_/,"")):""}function et(e){return e?e.replace(/[A-Z]/g,r=>`_${r.toLowerCase()}`):""}var tt=e=>{let r=t=>{if(!t)return t;if(Array.isArray(t))return t.map(i=>typeof i=="object"||Array.isArray(i)?r(i):i);let n={...t},o=Object.keys(n);for(let i of o){let a=e(i.toString());a!==i&&(n[a]=n[i],delete n[i]),typeof n[a]=="object"&&(n[a]=r(n[a]))}return n};return r},Pn=tt(et),An=tt(Qe);var Re=`const respond=r=>{self.postMessage(r)},workerToTabIds={};self.addEventListener("message",r=>{const e=r.data;switch(e.type){case"setTimeout":workerToTabIds[e.id]=setTimeout(()=>{respond({id:e.id})},e.ms);break;case"clearTimeout":workerToTabIds[e.id]&&(clearTimeout(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break;case"setInterval":workerToTabIds[e.id]=setInterval(()=>{respond({id:e.id})},e.ms);break;case"clearInterval":workerToTabIds[e.id]&&(clearInterval(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break}}); | ||
`;var rt=(e,r={})=>{if(typeof Worker>"u")return null;try{let t=new Blob([e],{type:"application/javascript; charset=utf-8"}),n=globalThis.URL.createObjectURL(t);return new Worker(n,r)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},Qt=()=>{let e=globalThis.setTimeout.bind(globalThis),r=globalThis.setInterval.bind(globalThis),t=globalThis.clearTimeout.bind(globalThis),n=globalThis.clearInterval.bind(globalThis);return{setTimeout:e,setInterval:r,clearTimeout:t,clearInterval:n,cleanup:Z}},we=()=>{let e=0,r=()=>e++,t=new Map,n=(c,m)=>c?.postMessage(m),o=c=>{t.get(c.data.id)?.()},i=rt(Re,{name:"clerk-timers"});if(i?.addEventListener("message",o),!i)return Qt();let a=()=>{i||(i=rt(Re,{name:"clerk-timers"}),i?.addEventListener("message",o))};return{setTimeout:(c,m)=>{a();let C=r();return t.set(C,c),n(i,{type:"setTimeout",id:C,ms:m}),C},setInterval:(c,m)=>{a();let C=r();return t.set(C,c),n(i,{type:"setInterval",id:C,ms:m}),C},clearTimeout:c=>{a(),t.delete(c),n(i,{type:"clearTimeout",id:c})},clearInterval:c=>{a(),t.delete(c),n(i,{type:"clearInterval",id:c})},cleanup:()=>{i&&(i.terminate(),i=null,t.clear())}}};function Gn({delayInMs:e}={delayInMs:1e3}){let r=we(),t,n=!1,o=()=>{t&&(r.clearTimeout(t),r.cleanup()),n=!0},i=async a=>{n=!1,await a(o),!n&&(t=r.setTimeout(()=>{i(a)},e))};return{run:i,stop:o}}function Bn(e){return e?er(e)||nt(e):!0}function er(e){return/^http(s)?:\/\//.test(e||"")}function nt(e){return e.startsWith("/")}function jn(e){return e?nt(e)?new URL(e,window.location.origin).toString():e:""}var Yn=()=>typeof window<"u";function qn(e=""){return e.startsWith("?")&&(e=e.slice(1)),new URLSearchParams(e)}function Zn(e=""){return(e||"").replace(/^.+:\/\//,"")}function Qn(e){if(!e)return"";let r;if(e.match(/^(clerk\.)+\w*$/))r=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;r=/^(clerk\.)*/gi}return`clerk.${e.replace(r,"")}`}var tr={maxRetries:10,firstDelay:125,maxDelay:0,timeMultiple:2,shouldRetry:()=>!0},rr=async e=>new Promise(r=>setTimeout(r,e)),nr=e=>{let r=0,t=()=>{let n=e.firstDelay,o=e.timeMultiple,i=n*Math.pow(o,r);return Math.min(e.maxDelay||i,i)};return async()=>{await rr(t()),r++}},ti=async(e,r={})=>{let t=0,{maxRetries:n,shouldRetry:o,firstDelay:i,maxDelay:a,timeMultiple:u}={...tr,...r},f=()=>t===n,s=nr({firstDelay:i,maxDelay:a,timeMultiple:u});for(;!f();)try{return await e()}catch(l){if(t++,!o(l,t)||f())throw l;await s()}throw new Error("Something went wrong")};import Oe from"react";function it(e,r){if(!e)throw typeof r=="string"?new Error(r):new Error(`${r.displayName} not found`)}var V=(e,r)=>{let{assertCtxFn:t=it}=r||{},n=Oe.createContext(void 0);return n.displayName=e,[n,()=>{let a=Oe.useContext(n);return t(a,`${e} not found`),a.value},()=>{let a=Oe.useContext(n);return a?a.value:{}}]};import{useEffect as ir,useLayoutEffect as or,createContext as ar,useContext as ut,useState as lt,createElement as sr,useRef as $,useCallback as Se,useDebugValue as ur}from"react";function ct(e,r,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(l){try{s(n.next(l))}catch(p){a(p)}}function f(l){try{s(n.throw(l))}catch(p){a(p)}}function s(l){l.done?i(l.value):o(l.value).then(u,f)}s((n=n.apply(e,r||[])).next())})}function dt(e,r){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function u(s){return function(l){return f([s,l])}}function f(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=r.call(e,t)}catch(l){s=[6,l],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}var I=function(){},h=I(),Q=Object,y=function(e){return e===h},A=function(e){return typeof e=="function"},M=function(e,r){return Q.assign({},e,r)},Pe="undefined",Ae=function(){return typeof window!=Pe},lr=function(){return typeof document!=Pe},cr=function(){return Ae()&&typeof window.requestAnimationFrame!=Pe},ue=new WeakMap,dr=0,re=function(e){var r=typeof e,t=e&&e.constructor,n=t==Date,o,i;if(Q(e)===e&&!n&&t!=RegExp){if(o=ue.get(e),o)return o;if(o=++dr+"~",ue.set(e,o),t==Array){for(o="@",i=0;i<e.length;i++)o+=re(e[i])+",";ue.set(e,o)}if(t==Q){o="#";for(var a=Q.keys(e).sort();!y(i=a.pop());)y(e[i])||(o+=i+":"+re(e[i])+",");ue.set(e,o)}}else o=n?e.toJSON():r=="symbol"?e.toString():r=="string"?JSON.stringify(e):""+e;return o},Ie=!0,fr=function(){return Ie},ft=Ae(),Ue=lr(),Le=ft&&window.addEventListener?window.addEventListener.bind(window):I,pr=Ue?document.addEventListener.bind(document):I,ze=ft&&window.removeEventListener?window.removeEventListener.bind(window):I,gr=Ue?document.removeEventListener.bind(document):I,mr=function(){var e=Ue&&document.visibilityState;return y(e)||e!=="hidden"},vr=function(e){return pr("visibilitychange",e),Le("focus",e),function(){gr("visibilitychange",e),ze("focus",e)}},hr=function(e){var r=function(){Ie=!0,e()},t=function(){Ie=!1};return Le("online",r),Le("offline",t),function(){ze("online",r),ze("offline",t)}},br={isOnline:fr,isVisible:mr},yr={initFocus:vr,initReconnect:hr},le=!Ae()||"Deno"in window,Cr=function(e){return cr()?window.requestAnimationFrame(e):setTimeout(e,1)},ee=le?ir:or,Ee=typeof navigator<"u"&&navigator.connection,ot=!le&&Ee&&(["slow-2g","2g"].includes(Ee.effectiveType)||Ee.saveData),pt=function(e){if(A(e))try{e=e()}catch{e=""}var r=[].concat(e);e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?re(e):"";var t=e?"$swr$"+e:"";return[e,r,t]},H=new WeakMap,gt=0,mt=1,vt=2,te=function(e,r,t,n,o,i,a){a===void 0&&(a=!0);var u=H.get(e),f=u[0],s=u[1],l=u[3],p=f[r],c=s[r];if(a&&c)for(var m=0;m<c.length;++m)c[m](t,n,o);return i&&(delete l[r],p&&p[0])?p[0](vt).then(function(){return e.get(r)}):e.get(r)},xr=0,Me=function(){return++xr},ht=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return ct(void 0,void 0,void 0,function(){var t,n,o,i,a,u,f,s,l,p,c,m,C,x,g,d,B,U,L,E,_;return dt(this,function(D){switch(D.label){case 0:if(t=e[0],n=e[1],o=e[2],i=e[3],a=typeof i=="boolean"?{revalidate:i}:i||{},u=y(a.populateCache)?!0:a.populateCache,f=a.revalidate!==!1,s=a.rollbackOnError!==!1,l=a.optimisticData,p=pt(n),c=p[0],m=p[2],!c)return[2];if(C=H.get(t),x=C[2],e.length<3)return[2,te(t,c,t.get(c),h,h,f,!0)];if(g=o,B=Me(),x[c]=[B,0],U=!y(l),L=t.get(c),U&&(E=A(l)?l(L):l,t.set(c,E),te(t,c,E)),A(g))try{g=g(t.get(c))}catch(W){d=W}return g&&A(g.then)?[4,g.catch(function(W){d=W})]:[3,2];case 1:if(g=D.sent(),B!==x[c][0]){if(d)throw d;return[2,g]}else d&&U&&s&&(u=!0,g=L,t.set(c,L));D.label=2;case 2:return u&&(d||(A(u)&&(g=u(g,L)),t.set(c,g)),t.set(m,M(t.get(m),{error:d}))),x[c][1]=Me(),[4,te(t,c,g,d,h,f,!!u)];case 3:if(_=D.sent(),d)throw d;return[2,u?_:g]}})})},at=function(e,r){for(var t in e)e[t][0]&&e[t][0](r)},bt=function(e,r){if(!H.has(e)){var t=M(yr,r),n={},o=ht.bind(h,e),i=I;if(H.set(e,[n,{},{},{},o]),!le){var a=t.initFocus(setTimeout.bind(h,at.bind(h,n,gt))),u=t.initReconnect(setTimeout.bind(h,at.bind(h,n,mt)));i=function(){a&&a(),u&&u(),H.delete(e)}}return[e,o,i]}return[e,H.get(e)[4]]},Tr=function(e,r,t,n,o){var i=t.errorRetryCount,a=o.retryCount,u=~~((Math.random()+.5)*(1<<(a<8?a:8)))*t.errorRetryInterval;!y(i)&&a>i||setTimeout(n,u,o)},yt=bt(new Map),Ct=yt[0],Rr=yt[1],xt=M({onLoadingSlow:I,onSuccess:I,onError:I,onErrorRetry:Tr,onDiscarded:I,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:ot?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:ot?5e3:3e3,compare:function(e,r){return re(e)==re(r)},isPaused:function(){return!1},cache:Ct,mutate:Rr,fallback:{}},br),Tt=function(e,r){var t=M(e,r);if(r){var n=e.use,o=e.fallback,i=r.use,a=r.fallback;n&&i&&(t.use=n.concat(i)),o&&a&&(t.fallback=M(o,a))}return t},De=ar({}),wr=function(e){var r=e.value,t=Tt(ut(De),r),n=r&&r.provider,o=lt(function(){return n?bt(n(t.cache||Ct),r):h})[0];return o&&(t.cache=o[0],t.mutate=o[1]),ee(function(){return o?o[2]:h},[]),sr(De.Provider,M(e,{value:t}))},Or=function(e,r){var t=lt({})[1],n=$(e),o=$({data:!1,error:!1,isValidating:!1}),i=Se(function(a){var u=!1,f=n.current;for(var s in a){var l=s;f[l]!==a[l]&&(f[l]=a[l],o.current[l]&&(u=!0))}u&&!r.current&&t({})},[]);return ee(function(){n.current=e}),[n,o.current,i]},Er=function(e){return A(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}]},kr=function(){return M(xt,ut(De))},Sr=function(e){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var o=kr(),i=Er(t),a=i[0],u=i[1],f=i[2],s=Tt(o,f),l=e,p=s.use;if(p)for(var c=p.length;c-- >0;)l=p[c](l);return l(a,u||s.fetcher,s)}},st=function(e,r,t){var n=r[e]||(r[e]=[]);return n.push(t),function(){var o=n.indexOf(t);o>=0&&(n[o]=n[n.length-1],n.pop())}},ke={dedupe:!0},Ir=function(e,r,t){var n=t.cache,o=t.compare,i=t.fallbackData,a=t.suspense,u=t.revalidateOnMount,f=t.refreshInterval,s=t.refreshWhenHidden,l=t.refreshWhenOffline,p=H.get(n),c=p[0],m=p[1],C=p[2],x=p[3],g=pt(e),d=g[0],B=g[1],U=g[2],L=$(!1),E=$(!1),_=$(d),D=$(r),W=$(t),v=function(){return W.current},ce=function(){return v().isVisible()&&v().isOnline()},ne=function(w){return n.set(U,M(n.get(U),w))},$e=n.get(d),Ot=y(i)?t.fallback[d]:i,z=y($e)?Ot:$e,He=n.get(U)||{},j=He.error,Ne=!L.current,Ge=function(){return Ne&&!y(u)?u:v().isPaused()?!1:a?y(z)?!1:t.revalidateIfStale:y(z)||t.revalidateIfStale},Et=function(){return!d||!r?!1:He.isValidating?!0:Ne&&Ge()},de=Et(),fe=Or({data:z,error:j,isValidating:de},E),G=fe[0],pe=fe[1],ie=fe[2],F=Se(function(w){return ct(void 0,void 0,void 0,function(){var T,R,O,X,Y,k,b,P,S,ge,J,K,me;return dt(this,function(q){switch(q.label){case 0:if(T=D.current,!d||!T||E.current||v().isPaused())return[2,!1];X=!0,Y=w||{},k=!x[d]||!Y.dedupe,b=function(){return!E.current&&d===_.current&&L.current},P=function(){var Ke=x[d];Ke&&Ke[1]===O&&delete x[d]},S={isValidating:!1},ge=function(){ne({isValidating:!1}),b()&&ie(S)},ne({isValidating:!0}),ie({isValidating:!0}),q.label=1;case 1:return q.trys.push([1,3,,4]),k&&(te(n,d,G.current.data,G.current.error,!0),t.loadingTimeout&&!n.get(d)&&setTimeout(function(){X&&b()&&v().onLoadingSlow(d,t)},t.loadingTimeout),x[d]=[T.apply(void 0,B),Me()]),me=x[d],R=me[0],O=me[1],[4,R];case 2:return R=q.sent(),k&&setTimeout(P,t.dedupingInterval),!x[d]||x[d][1]!==O?(k&&b()&&v().onDiscarded(d),[2,!1]):(ne({error:h}),S.error=h,J=C[d],!y(J)&&(O<=J[0]||O<=J[1]||J[1]===0)?(ge(),k&&b()&&v().onDiscarded(d),[2,!1]):(o(G.current.data,R)?S.data=G.current.data:S.data=R,o(n.get(d),R)||n.set(d,R),k&&b()&&v().onSuccess(R,d,t),[3,4]));case 3:return K=q.sent(),P(),v().isPaused()||(ne({error:K}),S.error=K,k&&b()&&(v().onError(K,d,t),(typeof t.shouldRetryOnError=="boolean"&&t.shouldRetryOnError||A(t.shouldRetryOnError)&&t.shouldRetryOnError(K))&&ce()&&v().onErrorRetry(K,d,t,F,{retryCount:(Y.retryCount||0)+1,dedupe:!0}))),[3,4];case 4:return X=!1,ge(),b()&&k&&te(n,d,S.data,S.error,!1),[2,!0]}})})},[d]),kt=Se(ht.bind(h,n,function(){return _.current}),[]);if(ee(function(){D.current=r,W.current=t}),ee(function(){if(d){var w=d!==_.current,T=F.bind(h,ke),R=function(b,P,S){ie(M({error:P,isValidating:S},o(G.current.data,b)?h:{data:b}))},O=0,X=function(b){if(b==gt){var P=Date.now();v().revalidateOnFocus&&P>O&&ce()&&(O=P+v().focusThrottleInterval,T())}else if(b==mt)v().revalidateOnReconnect&&ce()&&T();else if(b==vt)return F()},Y=st(d,m,R),k=st(d,c,X);return E.current=!1,_.current=d,L.current=!0,w&&ie({data:z,error:j,isValidating:de}),Ge()&&(y(z)||le?T():Cr(T)),function(){E.current=!0,Y(),k()}}},[d,F]),ee(function(){var w;function T(){var O=A(f)?f(z):f;O&&w!==-1&&(w=setTimeout(R,O))}function R(){!G.current.error&&(s||v().isVisible())&&(l||v().isOnline())?F(ke).then(T):T()}return T(),function(){w&&(clearTimeout(w),w=-1)}},[f,s,l,F]),ur(z),a&&y(z)&&d)throw D.current=r,W.current=t,E.current=!1,y(j)?F(ke):j;return{mutate:kt,get data(){return pe.data=!0,z},get error(){return pe.error=!0,j},get isValidating(){return pe.isValidating=!0,de}}},ai=Q.defineProperty(wr,"default",{value:xt});var _e=Sr(Ir);var[Lr,N]=V("ClerkInstanceContext"),[zr,We]=V("UserContext"),[Mr,Dr]=V("ClientContext"),[Pr,Fe]=V("SessionContext"),[Ar,Ve]=V("OrganizationContext");var Ur=e=>{let{invitationList:r,membershipList:t}=e||{},{organization:n,lastOrganizationMember:o,lastOrganizationInvitation:i}=Ve(),a=Fe(),u=N(),f=u.loaded&&a&&n,s=u.loaded?()=>u.organization?.getPendingInvitations(r):()=>[],l=u.loaded?()=>u.organization?.getMemberships(t):()=>[],{data:p,isValidating:c,mutate:m}=_e(f&&r?Rt("invites",n,i,r):null,s),{data:C,isValidating:x,mutate:g}=_e(f&&t?Rt("memberships",n,o,t):null,l);return n===void 0?{isLoaded:!1,organization:void 0,invitationList:void 0,membershipList:void 0,membership:void 0}:n===null?{isLoaded:!0,organization:null,invitationList:null,membershipList:null,membership:null}:!u.loaded&&n?{isLoaded:!0,organization:n,invitationList:void 0,membershipList:void 0,membership:void 0}:{isLoaded:!x&&!c,organization:n,membershipList:C,membership:_r(a.user.organizationMemberships,n.id),invitationList:p,unstable__mutate:()=>{g(),m()}}};function _r(e,r){return e.find(t=>t.organization.id===r)}function Rt(e,r,t,n){return[e,r.id,t?.id,t?.updatedAt,n.offset,n.limit].filter(Boolean).join("-")}var Wr=()=>{let e=N(),r=We();return!e.loaded||!r?{isLoaded:!1,organizationList:void 0,createOrganization:void 0,setActive:void 0}:{isLoaded:!0,organizationList:Fr(r.organizationMemberships),setActive:e.setActive,createOrganization:e.createOrganization}};function Fr(e){return e.map(r=>({membership:r,organization:r.organization}))}var Vr=()=>{let e=N();return e.loaded?{isLoaded:!0,createOrganization:e.createOrganization,getOrganizationMemberships:e.getOrganizationMemberships,getOrganization:e.getOrganization}:{isLoaded:!1,createOrganization:void 0,getOrganizationMemberships:void 0,getOrganization:void 0}};import wt from"react";var $r=typeof window<"u"?wt.useLayoutEffect:wt.useEffect;export{Lr as ClerkInstanceContext,Mr as ClientContext,Ze as LocalStorageBroadcastChannel,Ar as OrganizationContext,Gn as Poller,Pr as SessionContext,zr as UserContext,Qn as addClerkPrefix,ln as addYears,it as assertContextExists,It as buildErrorThrower,bn as buildPublishableKey,et as camelToSnake,Ft as colorToSameTypeString,V as createContextAndHook,tn as createCookieHandler,on as createDeferredPromise,xn as createDevOrStagingUrlCache,we as createWorkerTimers,sn as dateTo12HourTime,Pn as deepCamelToSnake,An as deepSnakeToCamel,zt as detectUserAgentRobot,Bt as differenceInCalendarDays,En as extension,un as formatRelative,Sn as handleValueOrFn,jr as hasAlpha,Vt as hexStringToRgbaColor,Lt as inBrowser,Yn as inClientSide,je as isHSLColor,er as isHttpOrHttps,Ln as isIPV4Address,Cn as isLegacyFrontendApiKey,fn as isNetworkError,nt as isProxyUrlRelative,Xt as isPublishableKey,Be as isRGBColor,Rn as isRetinaDisplay,be as isTransparent,dn as isUnauthorizedError,Kr as isValidBrowserOnline,oe as isValidHexString,he as isValidHslaString,Bn as isValidProxyUrl,ve as isValidRgbaString,xe as isomorphicAtob,Z as noop,Ce as normalizeDate,yn as parsePublishableKey,qn as parseSearchParams,jn as proxyUrlToAbsoluteURL,gn as readJSONFile,ti as runWithExponentialBackOff,Qe as snakeToCamel,Jr as stringToHslaColor,qr as stringToSameTypeColor,Zn as stripScheme,zn as titleize,Nr as toSentence,N as useClerkInstanceContext,Dr as useClientContext,Ur as useOrganization,Ve as useOrganizationContext,Wr as useOrganizationList,Vr as useOrganizations,$r as useSafeLayoutEffect,Fe as useSessionContext,We as useUserContext}; | ||
/*! Bundled license information: | ||
@@ -1931,0 +4,0 @@ |
@@ -1,38 +0,2 @@ | ||
import { | ||
__export, | ||
__reExport, | ||
noop | ||
} from "../chunk-N55KAAWL.js"; | ||
// src/testUtils/index.ts | ||
var testUtils_exports2 = {}; | ||
__export(testUtils_exports2, { | ||
noop: () => noop, | ||
render: () => customRender, | ||
userEvent: () => default2 | ||
}); | ||
// src/testUtils/testUtils.ts | ||
var testUtils_exports = {}; | ||
__export(testUtils_exports, { | ||
noop: () => noop, | ||
render: () => customRender, | ||
userEvent: () => default2 | ||
}); | ||
import "@testing-library/jest-dom/extend-expect"; | ||
import { render } from "@testing-library/react"; | ||
__reExport(testUtils_exports, react_star); | ||
import * as react_star from "@testing-library/react"; | ||
import { default as default2 } from "@testing-library/user-event"; | ||
var customRender = (ui, options) => { | ||
return render(ui, options); | ||
}; | ||
// src/testUtils/index.ts | ||
__reExport(testUtils_exports2, testUtils_exports); | ||
export { | ||
noop, | ||
customRender as render, | ||
default2 as userEvent | ||
}; | ||
import{a as n,b as e,c as o}from"../chunk-GW3MP3TA.js";var t={};n(t,{noop:()=>o,render:()=>m,userEvent:()=>p});var r={};n(r,{noop:()=>o,render:()=>m,userEvent:()=>p});import"@testing-library/jest-dom/extend-expect";import{render as a}from"@testing-library/react";e(r,R);import*as R from"@testing-library/react";import{default as p}from"@testing-library/user-event";var m=(i,s)=>a(i,s);e(t,r);export{o as noop,m as render,p as userEvent}; | ||
//# sourceMappingURL=index.js.map |
@@ -1,69 +0,2 @@ | ||
"use strict"; | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
// src/testUtils/index.ts | ||
var testUtils_exports2 = {}; | ||
__export(testUtils_exports2, { | ||
noop: () => noop, | ||
render: () => customRender, | ||
userEvent: () => import_user_event.default | ||
}); | ||
module.exports = __toCommonJS(testUtils_exports2); | ||
// src/testUtils/testUtils.ts | ||
var testUtils_exports = {}; | ||
__export(testUtils_exports, { | ||
noop: () => noop, | ||
render: () => customRender, | ||
userEvent: () => import_user_event.default | ||
}); | ||
var import_extend_expect = require("@testing-library/jest-dom/extend-expect"); | ||
var import_react = require("@testing-library/react"); | ||
// src/utils/noop.ts | ||
var noop = (..._args) => { | ||
}; | ||
// src/testUtils/testUtils.ts | ||
__reExport(testUtils_exports, require("@testing-library/react")); | ||
var import_user_event = __toESM(require("@testing-library/user-event")); | ||
var customRender = (ui, options) => { | ||
return (0, import_react.render)(ui, options); | ||
}; | ||
// src/testUtils/index.ts | ||
__reExport(testUtils_exports2, testUtils_exports, module.exports); | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
noop, | ||
render, | ||
userEvent | ||
}); | ||
"use strict";var u=Object.create;var s=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var g=Object.getPrototypeOf,v=Object.prototype.hasOwnProperty;var c=(r,e)=>{for(var t in e)s(r,t,{get:e[t],enumerable:!0})},m=(r,e,t,f)=>{if(e&&typeof e=="object"||typeof e=="function")for(let p of y(e))!v.call(r,p)&&p!==t&&s(r,p,{get:()=>e[p],enumerable:!(f=l(e,p))||f.enumerable});return r},n=(r,e,t)=>(m(r,e,"default"),t&&m(t,e,"default")),E=(r,e,t)=>(t=r!=null?u(g(r)):{},m(e||!r||!r.__esModule?s(t,"default",{value:r,enumerable:!0}):t,r)),O=r=>m(s({},"__esModule",{value:!0}),r);var a={};c(a,{noop:()=>i,render:()=>R,userEvent:()=>d.default});module.exports=O(a);var o={};c(o,{noop:()=>i,render:()=>R,userEvent:()=>d.default});var h=require("@testing-library/jest-dom/extend-expect"),x=require("@testing-library/react");var i=(...r)=>{};n(o,require("@testing-library/react"));var d=E(require("@testing-library/user-event")),R=(r,e)=>(0,x.render)(r,e);n(a,o,module.exports);0&&(module.exports={noop,render,userEvent}); | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@clerk/shared", | ||
"version": "0.15.6-staging.0", | ||
"version": "0.15.6", | ||
"description": "Internal package utils used by the Clerk SDKs", | ||
@@ -22,3 +22,3 @@ "types": "./dist/types/index.d.ts", | ||
"devDependencies": { | ||
"@clerk/types": "^3.35.3-staging.0", | ||
"@clerk/types": "^3.35.3", | ||
"@testing-library/dom": "8.19.0", | ||
@@ -42,3 +42,3 @@ "@testing-library/jest-dom": "5.16.5", | ||
"license": "ISC", | ||
"gitHead": "da83f02639327c9eedb49610c843f8c82fab2868", | ||
"gitHead": "8292455b906bc1ab2cdb80252a3e129a35244a92", | ||
"publishConfig": { | ||
@@ -45,0 +45,0 @@ "access": "public" |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
372304
619
4