@clerk/react 6.9.0 → 6.9.1-canary.v20260610190754

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/ClerkProvider-9lxHp9j5.cjs +1623 -0
  2. package/dist/ClerkProvider-9lxHp9j5.cjs.map +1 -0
  3. package/dist/ClerkProvider-LQpPtmNL.mjs +1533 -0
  4. package/dist/ClerkProvider-LQpPtmNL.mjs.map +1 -0
  5. package/dist/errors.cjs +69 -0
  6. package/dist/errors.d.cts +2 -0
  7. package/dist/errors.d.mts +2 -1
  8. package/dist/errors.mjs +2 -29
  9. package/dist/experimental.cjs +270 -0
  10. package/dist/experimental.cjs.map +1 -0
  11. package/dist/{experimental.d.ts → experimental.d.cts} +18 -18
  12. package/dist/experimental.d.mts +18 -18
  13. package/dist/experimental.mjs +201 -165
  14. package/dist/experimental.mjs.map +1 -1
  15. package/dist/hooks-BiY5Zgpp.mjs +1369 -0
  16. package/dist/hooks-BiY5Zgpp.mjs.map +1 -0
  17. package/dist/hooks-CBghYU21.cjs +1606 -0
  18. package/dist/hooks-CBghYU21.cjs.map +1 -0
  19. package/dist/index.cjs +447 -0
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.cts +345 -0
  22. package/dist/index.d.mts +183 -157
  23. package/dist/index.mjs +285 -380
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/internal.cjs +107 -0
  26. package/dist/internal.cjs.map +1 -0
  27. package/dist/internal.d.cts +51 -0
  28. package/dist/internal.d.mts +24 -26
  29. package/dist/internal.mjs +39 -73
  30. package/dist/internal.mjs.map +1 -1
  31. package/dist/legacy.cjs +134 -0
  32. package/dist/legacy.cjs.map +1 -0
  33. package/dist/{legacy.d.ts → legacy.d.cts} +6 -3
  34. package/dist/legacy.d.mts +6 -3
  35. package/dist/legacy.mjs +126 -42
  36. package/dist/legacy.mjs.map +1 -1
  37. package/dist/types-Bwenmt7y.d.cts +10951 -0
  38. package/dist/types-CiIhevkA.d.mts +10951 -0
  39. package/dist/types.cjs +0 -0
  40. package/dist/types.d.cts +3 -0
  41. package/dist/types.d.mts +3 -109
  42. package/dist/types.mjs +1 -2
  43. package/dist/useAssertWrappedByClerkProvider-Cm0djUcB.cjs +52 -0
  44. package/dist/useAssertWrappedByClerkProvider-Cm0djUcB.cjs.map +1 -0
  45. package/dist/useAssertWrappedByClerkProvider-GaNwZpWo.mjs +29 -0
  46. package/dist/useAssertWrappedByClerkProvider-GaNwZpWo.mjs.map +1 -0
  47. package/dist/{useAuth-Dlg_G1_7.d.mts → useAuth-BK5Y4htK.d.mts} +58 -39
  48. package/dist/{useAuth-Cv6iRjL9.d.ts → useAuth-BMxaWktj.d.cts} +58 -39
  49. package/package.json +18 -18
  50. package/dist/chunk-E5QRIS4Z.mjs +0 -20
  51. package/dist/chunk-E5QRIS4Z.mjs.map +0 -1
  52. package/dist/chunk-FQVXBXXF.mjs +0 -1487
  53. package/dist/chunk-FQVXBXXF.mjs.map +0 -1
  54. package/dist/chunk-GVGS7DUS.mjs +0 -2097
  55. package/dist/chunk-GVGS7DUS.mjs.map +0 -1
  56. package/dist/chunk-RQWALB2R.mjs +0 -26
  57. package/dist/chunk-RQWALB2R.mjs.map +0 -1
  58. package/dist/errors.d.ts +0 -1
  59. package/dist/errors.js +0 -51
  60. package/dist/errors.js.map +0 -1
  61. package/dist/errors.mjs.map +0 -1
  62. package/dist/experimental.js +0 -1505
  63. package/dist/experimental.js.map +0 -1
  64. package/dist/index.d.ts +0 -319
  65. package/dist/index.js +0 -3919
  66. package/dist/index.js.map +0 -1
  67. package/dist/internal.d.ts +0 -53
  68. package/dist/internal.js +0 -3339
  69. package/dist/internal.js.map +0 -1
  70. package/dist/legacy.js +0 -90
  71. package/dist/legacy.js.map +0 -1
  72. package/dist/types.d.ts +0 -109
  73. package/dist/types.js +0 -19
  74. package/dist/types.js.map +0 -1
  75. package/dist/types.mjs.map +0 -1
@@ -0,0 +1,1369 @@
1
+ import { n as useIsomorphicClerkContext, r as errorThrower, t as useAssertWrappedByClerkProvider$1 } from "./useAssertWrappedByClerkProvider-GaNwZpWo.mjs";
2
+ import React, { createContext, createElement, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
3
+ import { createPortal } from "react-dom";
4
+ import { ClerkRuntimeError } from "@clerk/shared/error";
5
+ import { logErrorInDevMode } from "@clerk/shared/utils";
6
+ import { getEnvVariable } from "@clerk/shared/getEnvVariable";
7
+ import { without } from "@clerk/shared/object";
8
+ import { __experimental_CheckoutProvider, __experimental_PaymentElement, __experimental_PaymentElementProvider, __experimental_useCheckout, __experimental_usePaymentElement, isDeeplyEqual, useAPIKeys, useClerk, useClerkInstanceContext, useInitialStateContext, useOAuthConsent as useOAuthConsent$1, useOrganization, useOrganizationCreationDefaults, useOrganizationList, usePortalRoot, useReverification, useSession, useSessionList, useUser } from "@clerk/shared/react";
9
+ import { createCheckAuthorization, resolveAuthState } from "@clerk/shared/authorization";
10
+ import { eventMethodCalled } from "@clerk/shared/telemetry";
11
+ import { deriveState } from "@clerk/shared/deriveState";
12
+ import { inBrowser } from "@clerk/shared/browser";
13
+
14
+ //#region src/errors/messages.ts
15
+ const multipleClerkProvidersError = "You've added multiple <ClerkProvider> components in your React component tree. Wrap your components in a single <ClerkProvider>.";
16
+ const multipleChildrenInButtonComponent = (name) => `You've passed multiple children components to <${name}/>. You can only pass a single child component or text.`;
17
+ const invalidStateError = "Invalid state. Feel free to submit a bug or reach out to support here: https://clerk.com/contact/support";
18
+ const unsupportedNonBrowserDomainOrProxyUrlFunction = "Unsupported usage of isSatellite, domain or proxyUrl. The usage of isSatellite, domain or proxyUrl as function is not supported in non-browser environments.";
19
+ const userProfilePageRenderedError = "<UserProfile.Page /> component needs to be a direct child of `<UserProfile />` or `<UserButton />`.";
20
+ const userProfileLinkRenderedError = "<UserProfile.Link /> component needs to be a direct child of `<UserProfile />` or `<UserButton />`.";
21
+ const organizationProfilePageRenderedError = "<OrganizationProfile.Page /> component needs to be a direct child of `<OrganizationProfile />` or `<OrganizationSwitcher />`.";
22
+ const organizationProfileLinkRenderedError = "<OrganizationProfile.Link /> component needs to be a direct child of `<OrganizationProfile />` or `<OrganizationSwitcher />`.";
23
+ const customPagesIgnoredComponent = (componentName) => `<${componentName} /> can only accept <${componentName}.Page /> and <${componentName}.Link /> as its children. Any other provided component will be ignored. Additionally, please ensure that the component is rendered in a client component.`;
24
+ const customPageWrongProps = (componentName) => `Missing props. <${componentName}.Page /> component requires the following props: url, label, labelIcon, alongside with children to be rendered inside the page.`;
25
+ const customLinkWrongProps = (componentName) => `Missing props. <${componentName}.Link /> component requires the following props: url, label and labelIcon.`;
26
+ const noPathProvidedError = (componentName) => `The <${componentName}/> component uses path-based routing by default unless a different routing strategy is provided using the \`routing\` prop. When path-based routing is used, you need to provide the path where the component is mounted on by using the \`path\` prop. Example: <${componentName} path={'/my-path'} />`;
27
+ const incompatibleRoutingWithPathProvidedError = (componentName) => `The \`path\` prop will only be respected when the Clerk component uses path-based routing. To resolve this error, pass \`routing='path'\` to the <${componentName}/> component, or drop the \`path\` prop to switch to hash-based routing. For more details please refer to our docs: https://clerk.com/docs`;
28
+ const userButtonIgnoredComponent = `<UserButton /> can only accept <UserButton.UserProfilePage />, <UserButton.UserProfileLink /> and <UserButton.MenuItems /> as its children. Any other provided component will be ignored. Additionally, please ensure that the component is rendered in a client component.`;
29
+ const customMenuItemsIgnoredComponent = "<UserButton.MenuItems /> component can only accept <UserButton.Action /> and <UserButton.Link /> as its children. Any other provided component will be ignored. Additionally, please ensure that the component is rendered in a client component.";
30
+ const userButtonMenuItemsRenderedError = "<UserButton.MenuItems /> component needs to be a direct child of `<UserButton />`.";
31
+ const userButtonMenuActionRenderedError = "<UserButton.Action /> component needs to be a direct child of `<UserButton.MenuItems />`.";
32
+ const userButtonMenuLinkRenderedError = "<UserButton.Link /> component needs to be a direct child of `<UserButton.MenuItems />`.";
33
+ const userButtonMenuItemLinkWrongProps = "Missing props. <UserButton.Link /> component requires the following props: href, label and labelIcon.";
34
+ const userButtonMenuItemsActionWrongsProps = "Missing props. <UserButton.Action /> component requires the following props: label.";
35
+
36
+ //#endregion
37
+ //#region src/utils/childrenUtils.tsx
38
+ const assertSingleChild = (children) => (name) => {
39
+ try {
40
+ return React.Children.only(children);
41
+ } catch {
42
+ const childArray = React.Children.toArray(children);
43
+ if (childArray.length === 1 && React.isValidElement(childArray[0])) return childArray[0];
44
+ return errorThrower.throw(multipleChildrenInButtonComponent(name));
45
+ }
46
+ };
47
+ const normalizeWithDefaultValue = (children, defaultText) => {
48
+ if (!children) children = defaultText;
49
+ if (typeof children === "string") children = /* @__PURE__ */ React.createElement("button", null, children);
50
+ return children;
51
+ };
52
+ const safeExecute = (cb) => (...args) => {
53
+ if (cb && typeof cb === "function") return cb(...args);
54
+ };
55
+
56
+ //#endregion
57
+ //#region src/utils/envVariables.ts
58
+ /**
59
+ * Gets an environment variable value, checking for Vite's VITE_ prefix first.
60
+ * This allows React SDK users with Vite to use VITE_CLERK_* env vars
61
+ * (which Vite exposes client-side) without manual configuration.
62
+ *
63
+ * Note: Empty string values are treated as "not set" and will fall through to
64
+ * the next env var in the chain. This is intentional since empty values are
65
+ * typically invalid for these options.
66
+ *
67
+ * @param name - The environment variable name without prefix (e.g., 'CLERK_PUBLISHABLE_KEY')
68
+ * @returns The value of the environment variable, or empty string if not found
69
+ */
70
+ const getEnvVar = (name) => {
71
+ return getEnvVariable(`VITE_${name}`) || getEnvVariable(name);
72
+ };
73
+ /**
74
+ * Helper to get env fallback only when the option is undefined.
75
+ * We check for undefined specifically (not falsy) to avoid conflicting with framework SDKs
76
+ * that may pass an empty string when their env var is not set.
77
+ *
78
+ * Returns the env var value only if it's non-empty, otherwise returns undefined
79
+ * to preserve the original behavior when no env var is set.
80
+ */
81
+ const withEnvFallback = (value, envVarName) => {
82
+ if (value !== void 0) return value;
83
+ return getEnvVar(envVarName) || void 0;
84
+ };
85
+ /**
86
+ * Merges ClerkProvider options with environment variable fallbacks.
87
+ * This supports Vite users who set VITE_CLERK_* or CLERK_* env vars.
88
+ * Passed-in options always take priority over environment variables.
89
+ *
90
+ * Supported environment variables:
91
+ * - VITE_CLERK_PUBLISHABLE_KEY / CLERK_PUBLISHABLE_KEY
92
+ *
93
+ * @param options - The options passed to ClerkProvider
94
+ * @returns Options with environment variable fallbacks applied
95
+ */
96
+ const mergeWithEnv = (options) => {
97
+ const publishableKey = withEnvFallback(options.publishableKey, "CLERK_PUBLISHABLE_KEY");
98
+ return {
99
+ ...options,
100
+ ...publishableKey !== void 0 && { publishableKey }
101
+ };
102
+ };
103
+
104
+ //#endregion
105
+ //#region src/utils/isConstructor.ts
106
+ function isConstructor(f) {
107
+ return typeof f === "function";
108
+ }
109
+
110
+ //#endregion
111
+ //#region src/utils/useMaxAllowedInstancesGuard.tsx
112
+ const counts = /* @__PURE__ */ new Map();
113
+ function useMaxAllowedInstancesGuard(name, error, maxCount = 1) {
114
+ React.useEffect(() => {
115
+ const count = counts.get(name) || 0;
116
+ if (count == maxCount) return errorThrower.throw(error);
117
+ counts.set(name, count + 1);
118
+ return () => {
119
+ counts.set(name, (counts.get(name) || 1) - 1);
120
+ };
121
+ }, []);
122
+ }
123
+ function withMaxAllowedInstancesGuard(WrappedComponent, name, error) {
124
+ const displayName = WrappedComponent.displayName || WrappedComponent.name || name || "Component";
125
+ const Hoc = (props) => {
126
+ useMaxAllowedInstancesGuard(name, error);
127
+ return /* @__PURE__ */ React.createElement(WrappedComponent, props);
128
+ };
129
+ Hoc.displayName = `withMaxAllowedInstancesGuard(${displayName})`;
130
+ return Hoc;
131
+ }
132
+
133
+ //#endregion
134
+ //#region src/utils/useCustomElementPortal.tsx
135
+ const useCustomElementPortal = (elements) => {
136
+ const [nodeMap, setNodeMap] = useState(/* @__PURE__ */ new Map());
137
+ const nodeMapRef = useRef(nodeMap);
138
+ const elementsRef = useRef(/* @__PURE__ */ new Map());
139
+ const portalsRef = useRef(/* @__PURE__ */ new Map());
140
+ nodeMapRef.current = nodeMap;
141
+ elementsRef.current = new Map(elements.map((el) => [el.id, el.component]));
142
+ const elementIds = new Set(elements.map((el) => el.id));
143
+ portalsRef.current.forEach((_, id) => {
144
+ if (!elementIds.has(id)) portalsRef.current.delete(id);
145
+ });
146
+ return elements.map((el) => {
147
+ const id = el.id;
148
+ const existingPortal = portalsRef.current.get(id);
149
+ if (existingPortal) return existingPortal;
150
+ const portal = () => {
151
+ const node = nodeMapRef.current.get(id);
152
+ const component = elementsRef.current.get(id);
153
+ return node ? createPortal(component, node) : null;
154
+ };
155
+ const customElementPortal = {
156
+ id: el.id,
157
+ mount: (node) => setNodeMap((prev) => new Map(prev).set(id, node)),
158
+ unmount: () => setNodeMap((prev) => {
159
+ const newMap = new Map(prev);
160
+ newMap.set(id, null);
161
+ return newMap;
162
+ }),
163
+ portal
164
+ };
165
+ portalsRef.current.set(id, customElementPortal);
166
+ return customElementPortal;
167
+ });
168
+ };
169
+
170
+ //#endregion
171
+ //#region src/utils/componentValidation.ts
172
+ const isThatComponent = (v, component) => {
173
+ return !!v && React.isValidElement(v) && v?.type === component;
174
+ };
175
+
176
+ //#endregion
177
+ //#region src/utils/useCustomPages.tsx
178
+ const useUserProfileCustomPages = (children, options) => {
179
+ return useCustomPages({
180
+ children,
181
+ reorderItemsLabels: [
182
+ "account",
183
+ "security",
184
+ "billing",
185
+ "apiKeys"
186
+ ],
187
+ LinkComponent: UserProfileLink,
188
+ PageComponent: UserProfilePage,
189
+ MenuItemsComponent: MenuItems,
190
+ componentName: "UserProfile"
191
+ }, options);
192
+ };
193
+ const useOrganizationProfileCustomPages = (children, options) => {
194
+ return useCustomPages({
195
+ children,
196
+ reorderItemsLabels: [
197
+ "general",
198
+ "members",
199
+ "billing",
200
+ "apiKeys"
201
+ ],
202
+ LinkComponent: OrganizationProfileLink,
203
+ PageComponent: OrganizationProfilePage,
204
+ componentName: "OrganizationProfile"
205
+ }, options);
206
+ };
207
+ /**
208
+ * Exclude any children that is used for identifying Custom Pages or Custom Items.
209
+ * Passing:
210
+ * ```tsx
211
+ * <UserProfile.Page/>
212
+ * <OrganizationProfile.Link/>
213
+ * <MyComponent>
214
+ * <UserButton.MenuItems/>
215
+ * ```
216
+ * Gives back
217
+ * ```tsx
218
+ * <MyComponent>
219
+ * ````
220
+ */
221
+ const useSanitizedChildren = (children) => {
222
+ const sanitizedChildren = [];
223
+ const excludedComponents = [
224
+ OrganizationProfileLink,
225
+ OrganizationProfilePage,
226
+ MenuItems,
227
+ UserProfilePage,
228
+ UserProfileLink
229
+ ];
230
+ React.Children.forEach(children, (child) => {
231
+ if (!excludedComponents.some((component) => isThatComponent(child, component))) sanitizedChildren.push(child);
232
+ });
233
+ return sanitizedChildren;
234
+ };
235
+ const useCustomPages = (params, options) => {
236
+ const { children, LinkComponent, PageComponent, MenuItemsComponent, reorderItemsLabels, componentName } = params;
237
+ const { allowForAnyChildren = false } = options || {};
238
+ const validChildren = [];
239
+ const portalIdCounts = /* @__PURE__ */ new Map();
240
+ React.Children.forEach(children, (child) => {
241
+ if (!isThatComponent(child, PageComponent) && !isThatComponent(child, LinkComponent) && !isThatComponent(child, MenuItemsComponent)) {
242
+ if (child && !allowForAnyChildren) logErrorInDevMode(customPagesIgnoredComponent(componentName));
243
+ return;
244
+ }
245
+ const { props } = child;
246
+ const { children, label, url, labelIcon } = props;
247
+ const childKey = child.key;
248
+ if (isThatComponent(child, PageComponent)) if (isReorderItem$1(props, reorderItemsLabels)) validChildren.push({ label });
249
+ else if (isCustomPage(props)) validChildren.push({
250
+ label,
251
+ labelIcon,
252
+ children,
253
+ url,
254
+ portalId: getCustomPagePortalId("page", props, childKey, portalIdCounts)
255
+ });
256
+ else {
257
+ logErrorInDevMode(customPageWrongProps(componentName));
258
+ return;
259
+ }
260
+ if (isThatComponent(child, LinkComponent)) if (isExternalLink$1(props)) validChildren.push({
261
+ label,
262
+ labelIcon,
263
+ url,
264
+ portalId: getCustomPagePortalId("link", props, childKey, portalIdCounts)
265
+ });
266
+ else {
267
+ logErrorInDevMode(customLinkWrongProps(componentName));
268
+ return;
269
+ }
270
+ });
271
+ const customPageContents = [];
272
+ const customPageLabelIcons = [];
273
+ const customLinkLabelIcons = [];
274
+ validChildren.forEach((cp, index) => {
275
+ if (isCustomPage(cp)) {
276
+ customPageContents.push({
277
+ component: cp.children,
278
+ id: cp.portalId || index
279
+ });
280
+ customPageLabelIcons.push({
281
+ component: cp.labelIcon,
282
+ id: cp.portalId || index
283
+ });
284
+ return;
285
+ }
286
+ if (isExternalLink$1(cp)) customLinkLabelIcons.push({
287
+ component: cp.labelIcon,
288
+ id: cp.portalId || index
289
+ });
290
+ });
291
+ const customPageContentsPortals = useCustomElementPortal(customPageContents);
292
+ const customPageLabelIconsPortals = useCustomElementPortal(customPageLabelIcons);
293
+ const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);
294
+ const customPages = [];
295
+ const customPagesPortals = [];
296
+ validChildren.forEach((cp, index) => {
297
+ if (isReorderItem$1(cp, reorderItemsLabels)) {
298
+ customPages.push({ label: cp.label });
299
+ return;
300
+ }
301
+ if (isCustomPage(cp)) {
302
+ const { portal: contentPortal, mount, unmount } = customPageContentsPortals.find((p) => p.id === (cp.portalId || index));
303
+ const { portal: labelPortal, mount: mountIcon, unmount: unmountIcon } = customPageLabelIconsPortals.find((p) => p.id === (cp.portalId || index));
304
+ customPages.push({
305
+ label: cp.label,
306
+ url: cp.url,
307
+ mount,
308
+ unmount,
309
+ mountIcon,
310
+ unmountIcon
311
+ });
312
+ customPagesPortals.push({
313
+ key: `content:${cp.portalId || index}`,
314
+ portal: contentPortal
315
+ });
316
+ customPagesPortals.push({
317
+ key: `label:${cp.portalId || index}`,
318
+ portal: labelPortal
319
+ });
320
+ return;
321
+ }
322
+ if (isExternalLink$1(cp)) {
323
+ const { portal: labelPortal, mount: mountIcon, unmount: unmountIcon } = customLinkLabelIconsPortals.find((p) => p.id === (cp.portalId || index));
324
+ customPages.push({
325
+ label: cp.label,
326
+ url: cp.url,
327
+ mountIcon,
328
+ unmountIcon
329
+ });
330
+ customPagesPortals.push({
331
+ key: `label:${cp.portalId || index}`,
332
+ portal: labelPortal
333
+ });
334
+ return;
335
+ }
336
+ });
337
+ return {
338
+ customPages,
339
+ customPagesPortals
340
+ };
341
+ };
342
+ const getCustomPagePortalId = (type, props, key, portalIdCounts) => {
343
+ if (key != null) return `${type}:key:${key}`;
344
+ const baseId = `${type}:${props.label}:${props.url}`;
345
+ const occurrence = portalIdCounts.get(baseId) ?? 0;
346
+ portalIdCounts.set(baseId, occurrence + 1);
347
+ return `${baseId}:${occurrence}`;
348
+ };
349
+ const isReorderItem$1 = (childProps, validItems) => {
350
+ const { children, label, url, labelIcon } = childProps;
351
+ return !children && !url && !labelIcon && validItems.some((v) => v === label);
352
+ };
353
+ const isCustomPage = (childProps) => {
354
+ const { children, label, url, labelIcon } = childProps;
355
+ return !!children && !!url && !!labelIcon && !!label;
356
+ };
357
+ const isExternalLink$1 = (childProps) => {
358
+ const { children, label, url, labelIcon } = childProps;
359
+ return !children && !!url && !!labelIcon && !!label;
360
+ };
361
+
362
+ //#endregion
363
+ //#region src/utils/useCustomMenuItems.tsx
364
+ const useUserButtonCustomMenuItems = (children, options) => {
365
+ return useCustomMenuItems({
366
+ children,
367
+ reorderItemsLabels: ["manageAccount", "signOut"],
368
+ MenuItemsComponent: MenuItems,
369
+ MenuActionComponent: MenuAction,
370
+ MenuLinkComponent: MenuLink,
371
+ UserProfileLinkComponent: UserProfileLink,
372
+ UserProfilePageComponent: UserProfilePage,
373
+ allowForAnyChildren: options?.allowForAnyChildren ?? false
374
+ });
375
+ };
376
+ const useCustomMenuItems = ({ children, MenuItemsComponent, MenuActionComponent, MenuLinkComponent, UserProfileLinkComponent, UserProfilePageComponent, reorderItemsLabels, allowForAnyChildren = false }) => {
377
+ const validChildren = [];
378
+ const customMenuItems = [];
379
+ const customMenuItemsPortals = [];
380
+ const portalIdCounts = /* @__PURE__ */ new Map();
381
+ React.Children.forEach(children, (child) => {
382
+ if (!isThatComponent(child, MenuItemsComponent) && !isThatComponent(child, UserProfileLinkComponent) && !isThatComponent(child, UserProfilePageComponent)) {
383
+ if (child && !allowForAnyChildren) logErrorInDevMode(userButtonIgnoredComponent);
384
+ return;
385
+ }
386
+ if (isThatComponent(child, UserProfileLinkComponent) || isThatComponent(child, UserProfilePageComponent)) return;
387
+ const { props } = child;
388
+ React.Children.forEach(props.children, (child) => {
389
+ if (!isThatComponent(child, MenuActionComponent) && !isThatComponent(child, MenuLinkComponent)) {
390
+ if (child) logErrorInDevMode(customMenuItemsIgnoredComponent);
391
+ return;
392
+ }
393
+ const { props } = child;
394
+ const childKey = child.key;
395
+ const { label, labelIcon, href, onClick, open } = props;
396
+ if (isThatComponent(child, MenuActionComponent)) if (isReorderItem(props, reorderItemsLabels)) validChildren.push({ label });
397
+ else if (isCustomMenuItem(props)) {
398
+ const baseItem = {
399
+ label,
400
+ labelIcon
401
+ };
402
+ if (onClick !== void 0) validChildren.push({
403
+ ...baseItem,
404
+ onClick,
405
+ portalId: getCustomMenuItemPortalId("action", props, childKey, portalIdCounts)
406
+ });
407
+ else if (open !== void 0) validChildren.push({
408
+ ...baseItem,
409
+ open: open.startsWith("/") ? open : `/${open}`,
410
+ portalId: getCustomMenuItemPortalId("action", props, childKey, portalIdCounts)
411
+ });
412
+ else {
413
+ logErrorInDevMode("Custom menu item must have either onClick or open property");
414
+ return;
415
+ }
416
+ } else {
417
+ logErrorInDevMode(userButtonMenuItemsActionWrongsProps);
418
+ return;
419
+ }
420
+ if (isThatComponent(child, MenuLinkComponent)) if (isExternalLink(props)) validChildren.push({
421
+ label,
422
+ labelIcon,
423
+ href,
424
+ portalId: getCustomMenuItemPortalId("link", props, childKey, portalIdCounts)
425
+ });
426
+ else {
427
+ logErrorInDevMode(userButtonMenuItemLinkWrongProps);
428
+ return;
429
+ }
430
+ });
431
+ });
432
+ const customMenuItemLabelIcons = [];
433
+ const customLinkLabelIcons = [];
434
+ validChildren.forEach((mi, index) => {
435
+ if (isCustomMenuItem(mi)) customMenuItemLabelIcons.push({
436
+ component: mi.labelIcon,
437
+ id: mi.portalId || index
438
+ });
439
+ if (isExternalLink(mi)) customLinkLabelIcons.push({
440
+ component: mi.labelIcon,
441
+ id: mi.portalId || index
442
+ });
443
+ });
444
+ const customMenuItemLabelIconsPortals = useCustomElementPortal(customMenuItemLabelIcons);
445
+ const customLinkLabelIconsPortals = useCustomElementPortal(customLinkLabelIcons);
446
+ validChildren.forEach((mi, index) => {
447
+ if (isReorderItem(mi, reorderItemsLabels)) customMenuItems.push({ label: mi.label });
448
+ if (isCustomMenuItem(mi)) {
449
+ const { portal: iconPortal, mount: mountIcon, unmount: unmountIcon } = customMenuItemLabelIconsPortals.find((p) => p.id === (mi.portalId || index));
450
+ const menuItem = {
451
+ label: mi.label,
452
+ mountIcon,
453
+ unmountIcon
454
+ };
455
+ if ("onClick" in mi) menuItem.onClick = mi.onClick;
456
+ else if ("open" in mi) menuItem.open = mi.open;
457
+ customMenuItems.push(menuItem);
458
+ customMenuItemsPortals.push({
459
+ key: `icon:${mi.portalId || index}`,
460
+ portal: iconPortal
461
+ });
462
+ }
463
+ if (isExternalLink(mi)) {
464
+ const { portal: iconPortal, mount: mountIcon, unmount: unmountIcon } = customLinkLabelIconsPortals.find((p) => p.id === (mi.portalId || index));
465
+ customMenuItems.push({
466
+ label: mi.label,
467
+ href: mi.href,
468
+ mountIcon,
469
+ unmountIcon
470
+ });
471
+ customMenuItemsPortals.push({
472
+ key: `icon:${mi.portalId || index}`,
473
+ portal: iconPortal
474
+ });
475
+ }
476
+ });
477
+ return {
478
+ customMenuItems,
479
+ customMenuItemsPortals
480
+ };
481
+ };
482
+ const getCustomMenuItemPortalId = (type, props, key, portalIdCounts) => {
483
+ if (key != null) return `${type}:key:${key}`;
484
+ const target = props.href || props.open || "";
485
+ const baseId = `${type}:${props.label}:${target}`;
486
+ const occurrence = portalIdCounts.get(baseId) ?? 0;
487
+ portalIdCounts.set(baseId, occurrence + 1);
488
+ return `${baseId}:${occurrence}`;
489
+ };
490
+ const isReorderItem = (childProps, validItems) => {
491
+ const { children, label, onClick, labelIcon } = childProps;
492
+ return !children && !onClick && !labelIcon && validItems.some((v) => v === label);
493
+ };
494
+ const isCustomMenuItem = (childProps) => {
495
+ const { label, labelIcon, onClick, open } = childProps;
496
+ return !!labelIcon && !!label && (typeof onClick === "function" || typeof open === "string");
497
+ };
498
+ const isExternalLink = (childProps) => {
499
+ const { label, href, labelIcon } = childProps;
500
+ return !!href && !!labelIcon && !!label;
501
+ };
502
+
503
+ //#endregion
504
+ //#region src/utils/useWaitForComponentMount.ts
505
+ const createAwaitableMutationObserver = (globalOptions) => {
506
+ const isReady = globalOptions?.isReady;
507
+ return (options) => new Promise((resolve, reject) => {
508
+ const { root = document?.body, selector, timeout = 0 } = options;
509
+ if (!root) {
510
+ reject(/* @__PURE__ */ new Error("No root element provided"));
511
+ return;
512
+ }
513
+ let elementToWatch = root;
514
+ if (selector) elementToWatch = root?.querySelector(selector);
515
+ if (isReady(elementToWatch, selector)) {
516
+ resolve();
517
+ return;
518
+ }
519
+ const observer = new MutationObserver((mutationsList) => {
520
+ for (const mutation of mutationsList) {
521
+ if (!elementToWatch && selector) elementToWatch = root?.querySelector(selector);
522
+ if (globalOptions.childList && mutation.type === "childList" || globalOptions.attributes && mutation.type === "attributes") {
523
+ if (isReady(elementToWatch, selector)) {
524
+ observer.disconnect();
525
+ resolve();
526
+ return;
527
+ }
528
+ }
529
+ }
530
+ });
531
+ observer.observe(root, globalOptions);
532
+ if (timeout > 0) setTimeout(() => {
533
+ observer.disconnect();
534
+ reject(/* @__PURE__ */ new Error(`Timeout waiting for ${selector}`));
535
+ }, timeout);
536
+ });
537
+ };
538
+ const waitForElementChildren = createAwaitableMutationObserver({
539
+ childList: true,
540
+ subtree: true,
541
+ isReady: (el, selector) => !!el?.childElementCount && el?.matches?.(selector) && el.childElementCount > 0
542
+ });
543
+ /**
544
+ * Detect when a Clerk component has mounted by watching DOM updates to an element with a `data-clerk-component="${component}"` property.
545
+ */
546
+ function useWaitForComponentMount(component, options) {
547
+ const watcherRef = useRef();
548
+ const [status, setStatus] = useState("rendering");
549
+ useEffect(() => {
550
+ if (!component) throw new Error("Clerk: no component name provided, unable to detect mount.");
551
+ if (typeof window !== "undefined" && !watcherRef.current) {
552
+ const defaultSelector = `[data-clerk-component="${component}"]`;
553
+ const selector = options?.selector;
554
+ watcherRef.current = waitForElementChildren({ selector: selector ? defaultSelector + selector : defaultSelector }).then(() => {
555
+ setStatus("rendered");
556
+ }).catch(() => {
557
+ setStatus("error");
558
+ });
559
+ }
560
+ }, [component, options?.selector]);
561
+ return status;
562
+ }
563
+
564
+ //#endregion
565
+ //#region src/components/ClerkHostRenderer.tsx
566
+ const isMountProps = (props) => {
567
+ return "mount" in props;
568
+ };
569
+ const isOpenProps = (props) => {
570
+ return "open" in props;
571
+ };
572
+ const stripMenuItemIconHandlers = (menuItems) => {
573
+ return menuItems?.map(({ mountIcon, unmountIcon, ...rest }) => rest);
574
+ };
575
+ /**
576
+ * Used to orchestrate mounting of Clerk components in a host React application.
577
+ * Components are rendered into a specific DOM node using mount/unmount methods provided by the Clerk class.
578
+ */
579
+ var ClerkHostRenderer = class extends React.PureComponent {
580
+ constructor(..._args) {
581
+ super(..._args);
582
+ this.rootRef = React.createRef();
583
+ }
584
+ componentDidUpdate(_prevProps) {
585
+ if (!isMountProps(_prevProps) || !isMountProps(this.props)) return;
586
+ const prevProps = without(_prevProps.props || {}, "customPages", "customMenuItems", "children");
587
+ const newProps = without(this.props.props || {}, "customPages", "customMenuItems", "children");
588
+ const customPagesChanged = _prevProps.props?.customPages?.length !== this.props.props?.customPages?.length;
589
+ const customMenuItemsChanged = _prevProps.props?.customMenuItems?.length !== this.props.props?.customMenuItems?.length;
590
+ const prevMenuItemsWithoutHandlers = stripMenuItemIconHandlers(_prevProps.props?.customMenuItems);
591
+ const newMenuItemsWithoutHandlers = stripMenuItemIconHandlers(this.props.props?.customMenuItems);
592
+ if (!isDeeplyEqual(prevProps, newProps) || !isDeeplyEqual(prevMenuItemsWithoutHandlers, newMenuItemsWithoutHandlers) || customPagesChanged || customMenuItemsChanged) {
593
+ if (this.rootRef.current) this.props.updateProps({
594
+ node: this.rootRef.current,
595
+ props: this.props.props
596
+ });
597
+ }
598
+ }
599
+ componentDidMount() {
600
+ if (this.rootRef.current) {
601
+ if (isMountProps(this.props)) this.props.mount(this.rootRef.current, this.props.props);
602
+ if (isOpenProps(this.props)) this.props.open(this.props.props);
603
+ }
604
+ }
605
+ componentWillUnmount() {
606
+ if (this.rootRef.current) {
607
+ if (isMountProps(this.props)) this.props.unmount(this.rootRef.current);
608
+ if (isOpenProps(this.props)) this.props.close();
609
+ }
610
+ }
611
+ render() {
612
+ const { hideRootHtmlElement = false } = this.props;
613
+ const rootAttributes = {
614
+ ref: this.rootRef,
615
+ ...this.props.rootProps,
616
+ ...this.props.component && { "data-clerk-component": this.props.component }
617
+ };
618
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, !hideRootHtmlElement && /* @__PURE__ */ React.createElement("div", rootAttributes), this.props.children);
619
+ }
620
+ };
621
+
622
+ //#endregion
623
+ //#region src/components/withClerk.tsx
624
+ const withClerk = (Component, displayNameOrOptions) => {
625
+ const displayName = (typeof displayNameOrOptions === "string" ? displayNameOrOptions : displayNameOrOptions?.component) || Component.displayName || Component.name || "Component";
626
+ Component.displayName = displayName;
627
+ const options = typeof displayNameOrOptions === "string" ? void 0 : displayNameOrOptions;
628
+ const HOC = (props) => {
629
+ useAssertWrappedByClerkProvider$1(displayName || "withClerk");
630
+ const clerk = useIsomorphicClerkContext();
631
+ const getContainer = usePortalRoot();
632
+ if (!clerk.loaded && !options?.renderWhileLoading) return null;
633
+ return /* @__PURE__ */ React.createElement(Component, {
634
+ getContainer,
635
+ ...props,
636
+ component: displayName,
637
+ clerk
638
+ });
639
+ };
640
+ HOC.displayName = `withClerk(${displayName})`;
641
+ return HOC;
642
+ };
643
+
644
+ //#endregion
645
+ //#region src/components/uiComponents.tsx
646
+ const CustomPortalsRenderer = (props) => {
647
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, props?.customPagesPortals?.map(({ key, portal }) => createElement(portal, { key })), props?.customMenuItemsPortals?.map(({ key, portal }) => createElement(portal, { key })));
648
+ };
649
+ const SignIn = withClerk(({ clerk, component, fallback, ...props }) => {
650
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
651
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
652
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
653
+ component,
654
+ mount: clerk.mountSignIn,
655
+ unmount: clerk.unmountSignIn,
656
+ updateProps: clerk.__internal_updateProps,
657
+ props,
658
+ rootProps: rendererRootProps
659
+ }));
660
+ }, {
661
+ component: "SignIn",
662
+ renderWhileLoading: true
663
+ });
664
+ const SignUp = withClerk(({ clerk, component, fallback, ...props }) => {
665
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
666
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
667
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
668
+ component,
669
+ mount: clerk.mountSignUp,
670
+ unmount: clerk.unmountSignUp,
671
+ updateProps: clerk.__internal_updateProps,
672
+ props,
673
+ rootProps: rendererRootProps
674
+ }));
675
+ }, {
676
+ component: "SignUp",
677
+ renderWhileLoading: true
678
+ });
679
+ function UserProfilePage({ children }) {
680
+ logErrorInDevMode(userProfilePageRenderedError);
681
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, children);
682
+ }
683
+ function UserProfileLink({ children }) {
684
+ logErrorInDevMode(userProfileLinkRenderedError);
685
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, children);
686
+ }
687
+ const _UserProfile = withClerk(({ clerk, component, fallback, ...props }) => {
688
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
689
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
690
+ const { customPages, customPagesPortals } = useUserProfileCustomPages(props.children);
691
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
692
+ component,
693
+ mount: clerk.mountUserProfile,
694
+ unmount: clerk.unmountUserProfile,
695
+ updateProps: clerk.__internal_updateProps,
696
+ props: {
697
+ ...props,
698
+ customPages
699
+ },
700
+ rootProps: rendererRootProps
701
+ }, /* @__PURE__ */ React.createElement(CustomPortalsRenderer, { customPagesPortals })));
702
+ }, {
703
+ component: "UserProfile",
704
+ renderWhileLoading: true
705
+ });
706
+ const UserProfile = Object.assign(_UserProfile, {
707
+ Page: UserProfilePage,
708
+ Link: UserProfileLink
709
+ });
710
+ const UserButtonContext = createContext({
711
+ mount: () => {},
712
+ unmount: () => {},
713
+ updateProps: () => {}
714
+ });
715
+ const _UserButton = withClerk(({ clerk, component, fallback, ...props }) => {
716
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
717
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
718
+ const { customPages, customPagesPortals } = useUserProfileCustomPages(props.children, { allowForAnyChildren: !!props.__experimental_asProvider });
719
+ const userProfileProps = {
720
+ ...props.userProfileProps,
721
+ customPages
722
+ };
723
+ const { customMenuItems, customMenuItemsPortals } = useUserButtonCustomMenuItems(props.children, { allowForAnyChildren: !!props.__experimental_asProvider });
724
+ const sanitizedChildren = useSanitizedChildren(props.children);
725
+ const passableProps = {
726
+ mount: clerk.mountUserButton,
727
+ unmount: clerk.unmountUserButton,
728
+ updateProps: clerk.__internal_updateProps,
729
+ props: {
730
+ ...props,
731
+ userProfileProps,
732
+ customMenuItems
733
+ }
734
+ };
735
+ const portalProps = {
736
+ customPagesPortals,
737
+ customMenuItemsPortals
738
+ };
739
+ return /* @__PURE__ */ React.createElement(UserButtonContext.Provider, { value: passableProps }, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
740
+ component,
741
+ ...passableProps,
742
+ hideRootHtmlElement: !!props.__experimental_asProvider,
743
+ rootProps: rendererRootProps
744
+ }, props.__experimental_asProvider ? sanitizedChildren : null, /* @__PURE__ */ React.createElement(CustomPortalsRenderer, portalProps)));
745
+ }, {
746
+ component: "UserButton",
747
+ renderWhileLoading: true
748
+ });
749
+ function MenuItems({ children }) {
750
+ logErrorInDevMode(userButtonMenuItemsRenderedError);
751
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, children);
752
+ }
753
+ function MenuAction({ children }) {
754
+ logErrorInDevMode(userButtonMenuActionRenderedError);
755
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, children);
756
+ }
757
+ function MenuLink({ children }) {
758
+ logErrorInDevMode(userButtonMenuLinkRenderedError);
759
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, children);
760
+ }
761
+ function UserButtonOutlet(outletProps) {
762
+ const providerProps = useContext(UserButtonContext);
763
+ const portalProps = {
764
+ ...providerProps,
765
+ props: {
766
+ ...providerProps.props,
767
+ ...outletProps
768
+ }
769
+ };
770
+ return /* @__PURE__ */ React.createElement(ClerkHostRenderer, portalProps);
771
+ }
772
+ const UserButton = Object.assign(_UserButton, {
773
+ UserProfilePage,
774
+ UserProfileLink,
775
+ MenuItems,
776
+ Action: MenuAction,
777
+ Link: MenuLink,
778
+ __experimental_Outlet: UserButtonOutlet
779
+ });
780
+ function OrganizationProfilePage({ children }) {
781
+ logErrorInDevMode(organizationProfilePageRenderedError);
782
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, children);
783
+ }
784
+ function OrganizationProfileLink({ children }) {
785
+ logErrorInDevMode(organizationProfileLinkRenderedError);
786
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, children);
787
+ }
788
+ const _OrganizationProfile = withClerk(({ clerk, component, fallback, ...props }) => {
789
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
790
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
791
+ const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(props.children);
792
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
793
+ component,
794
+ mount: clerk.mountOrganizationProfile,
795
+ unmount: clerk.unmountOrganizationProfile,
796
+ updateProps: clerk.__internal_updateProps,
797
+ props: {
798
+ ...props,
799
+ customPages
800
+ },
801
+ rootProps: rendererRootProps
802
+ }, /* @__PURE__ */ React.createElement(CustomPortalsRenderer, { customPagesPortals })));
803
+ }, {
804
+ component: "OrganizationProfile",
805
+ renderWhileLoading: true
806
+ });
807
+ const OrganizationProfile = Object.assign(_OrganizationProfile, {
808
+ Page: OrganizationProfilePage,
809
+ Link: OrganizationProfileLink
810
+ });
811
+ const CreateOrganization = withClerk(({ clerk, component, fallback, ...props }) => {
812
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
813
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
814
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
815
+ component,
816
+ mount: clerk.mountCreateOrganization,
817
+ unmount: clerk.unmountCreateOrganization,
818
+ updateProps: clerk.__internal_updateProps,
819
+ props,
820
+ rootProps: rendererRootProps
821
+ }));
822
+ }, {
823
+ component: "CreateOrganization",
824
+ renderWhileLoading: true
825
+ });
826
+ const OrganizationSwitcherContext = createContext({
827
+ mount: () => {},
828
+ unmount: () => {},
829
+ updateProps: () => {}
830
+ });
831
+ const _OrganizationSwitcher = withClerk(({ clerk, component, fallback, ...props }) => {
832
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
833
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
834
+ const { customPages, customPagesPortals } = useOrganizationProfileCustomPages(props.children, { allowForAnyChildren: !!props.__experimental_asProvider });
835
+ const organizationProfileProps = {
836
+ ...props.organizationProfileProps,
837
+ customPages
838
+ };
839
+ const sanitizedChildren = useSanitizedChildren(props.children);
840
+ const passableProps = {
841
+ mount: clerk.mountOrganizationSwitcher,
842
+ unmount: clerk.unmountOrganizationSwitcher,
843
+ updateProps: clerk.__internal_updateProps,
844
+ props: {
845
+ ...props,
846
+ organizationProfileProps
847
+ },
848
+ rootProps: rendererRootProps,
849
+ component
850
+ };
851
+ /**
852
+ * Prefetch organization list
853
+ */
854
+ clerk.__experimental_prefetchOrganizationSwitcher();
855
+ return /* @__PURE__ */ React.createElement(OrganizationSwitcherContext.Provider, { value: passableProps }, /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
856
+ ...passableProps,
857
+ hideRootHtmlElement: !!props.__experimental_asProvider
858
+ }, props.__experimental_asProvider ? sanitizedChildren : null, /* @__PURE__ */ React.createElement(CustomPortalsRenderer, { customPagesPortals }))));
859
+ }, {
860
+ component: "OrganizationSwitcher",
861
+ renderWhileLoading: true
862
+ });
863
+ function OrganizationSwitcherOutlet(outletProps) {
864
+ const providerProps = useContext(OrganizationSwitcherContext);
865
+ const portalProps = {
866
+ ...providerProps,
867
+ props: {
868
+ ...providerProps.props,
869
+ ...outletProps
870
+ }
871
+ };
872
+ return /* @__PURE__ */ React.createElement(ClerkHostRenderer, portalProps);
873
+ }
874
+ const OrganizationSwitcher = Object.assign(_OrganizationSwitcher, {
875
+ OrganizationProfilePage,
876
+ OrganizationProfileLink,
877
+ __experimental_Outlet: OrganizationSwitcherOutlet
878
+ });
879
+ const OrganizationList = withClerk(({ clerk, component, fallback, ...props }) => {
880
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
881
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
882
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
883
+ component,
884
+ mount: clerk.mountOrganizationList,
885
+ unmount: clerk.unmountOrganizationList,
886
+ updateProps: clerk.__internal_updateProps,
887
+ props,
888
+ rootProps: rendererRootProps
889
+ }));
890
+ }, {
891
+ component: "OrganizationList",
892
+ renderWhileLoading: true
893
+ });
894
+ const GoogleOneTap = withClerk(({ clerk, component, fallback, ...props }) => {
895
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
896
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
897
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
898
+ component,
899
+ open: clerk.openGoogleOneTap,
900
+ close: clerk.closeGoogleOneTap,
901
+ updateProps: clerk.__internal_updateProps,
902
+ props,
903
+ rootProps: rendererRootProps
904
+ }));
905
+ }, {
906
+ component: "GoogleOneTap",
907
+ renderWhileLoading: true
908
+ });
909
+ const Waitlist = withClerk(({ clerk, component, fallback, ...props }) => {
910
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
911
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
912
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
913
+ component,
914
+ mount: clerk.mountWaitlist,
915
+ unmount: clerk.unmountWaitlist,
916
+ updateProps: clerk.__internal_updateProps,
917
+ props,
918
+ rootProps: rendererRootProps
919
+ }));
920
+ }, {
921
+ component: "Waitlist",
922
+ renderWhileLoading: true
923
+ });
924
+ const PricingTable = withClerk(({ clerk, component, fallback, ...props }) => {
925
+ const shouldShowFallback = useWaitForComponentMount(component, { selector: "[data-component-status=\"ready\"]" }) === "rendering" || !clerk.loaded;
926
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
927
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
928
+ component,
929
+ mount: clerk.mountPricingTable,
930
+ unmount: clerk.unmountPricingTable,
931
+ updateProps: clerk.__internal_updateProps,
932
+ props,
933
+ rootProps: rendererRootProps
934
+ }));
935
+ }, {
936
+ component: "PricingTable",
937
+ renderWhileLoading: true
938
+ });
939
+ /**
940
+ * @experimental This component is in early access and may change in future releases.
941
+ */
942
+ const APIKeys = withClerk(({ clerk, component, fallback, ...props }) => {
943
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
944
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
945
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
946
+ component,
947
+ mount: clerk.mountAPIKeys,
948
+ unmount: clerk.unmountAPIKeys,
949
+ updateProps: clerk.__internal_updateProps,
950
+ props,
951
+ rootProps: rendererRootProps
952
+ }));
953
+ }, {
954
+ component: "ApiKeys",
955
+ renderWhileLoading: true
956
+ });
957
+ const OAuthConsent = withClerk(({ clerk, component, fallback, ...props }) => {
958
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
959
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
960
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
961
+ component,
962
+ mount: clerk.__internal_mountOAuthConsent,
963
+ unmount: clerk.__internal_unmountOAuthConsent,
964
+ updateProps: clerk.__internal_updateProps,
965
+ props,
966
+ rootProps: rendererRootProps
967
+ }));
968
+ }, {
969
+ component: "OAuthConsent",
970
+ renderWhileLoading: true
971
+ });
972
+ const UserAvatar = withClerk(({ clerk, component, fallback, ...props }) => {
973
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
974
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
975
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
976
+ component,
977
+ mount: clerk.mountUserAvatar,
978
+ unmount: clerk.unmountUserAvatar,
979
+ updateProps: clerk.__internal_updateProps,
980
+ props,
981
+ rootProps: rendererRootProps
982
+ }));
983
+ }, {
984
+ component: "UserAvatar",
985
+ renderWhileLoading: true
986
+ });
987
+ const TaskChooseOrganization = withClerk(({ clerk, component, fallback, ...props }) => {
988
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
989
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
990
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
991
+ component,
992
+ mount: clerk.mountTaskChooseOrganization,
993
+ unmount: clerk.unmountTaskChooseOrganization,
994
+ updateProps: clerk.__internal_updateProps,
995
+ props,
996
+ rootProps: rendererRootProps
997
+ }));
998
+ }, {
999
+ component: "TaskChooseOrganization",
1000
+ renderWhileLoading: true
1001
+ });
1002
+ const TaskResetPassword = withClerk(({ clerk, component, fallback, ...props }) => {
1003
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
1004
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
1005
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
1006
+ component,
1007
+ mount: clerk.mountTaskResetPassword,
1008
+ unmount: clerk.unmountTaskResetPassword,
1009
+ updateProps: clerk.__internal_updateProps,
1010
+ props,
1011
+ rootProps: rendererRootProps
1012
+ }));
1013
+ }, {
1014
+ component: "TaskResetPassword",
1015
+ renderWhileLoading: true
1016
+ });
1017
+ const TaskSetupMFA = withClerk(({ clerk, component, fallback, ...props }) => {
1018
+ const shouldShowFallback = useWaitForComponentMount(component) === "rendering" || !clerk.loaded;
1019
+ const rendererRootProps = { ...shouldShowFallback && fallback && { style: { display: "none" } } };
1020
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, shouldShowFallback && fallback, clerk.loaded && /* @__PURE__ */ React.createElement(ClerkHostRenderer, {
1021
+ component,
1022
+ mount: clerk.mountTaskSetupMFA,
1023
+ unmount: clerk.unmountTaskSetupMFA,
1024
+ updateProps: clerk.__internal_updateProps,
1025
+ props,
1026
+ rootProps: rendererRootProps
1027
+ }));
1028
+ }, {
1029
+ component: "TaskSetupMFA",
1030
+ renderWhileLoading: true
1031
+ });
1032
+
1033
+ //#endregion
1034
+ //#region src/hooks/useAuthBase.tsx
1035
+ const defaultDerivedInitialState = {
1036
+ actor: void 0,
1037
+ factorVerificationAge: null,
1038
+ orgId: void 0,
1039
+ orgPermissions: void 0,
1040
+ orgRole: void 0,
1041
+ orgSlug: void 0,
1042
+ sessionClaims: void 0,
1043
+ sessionId: void 0,
1044
+ sessionStatus: void 0,
1045
+ userId: void 0
1046
+ };
1047
+ function useAuthBase() {
1048
+ const clerk = useClerkInstanceContext();
1049
+ const initialState = useInitialStateContext();
1050
+ const getInitialState = useCallback(() => initialState, [initialState]);
1051
+ const state = useSyncExternalStore(useCallback((callback) => clerk.addListener(callback, { skipInitialEmit: true }), [clerk]), useCallback(() => {
1052
+ if (!clerk.loaded || !clerk.__internal_lastEmittedResources) return getInitialState();
1053
+ return clerk.__internal_lastEmittedResources;
1054
+ }, [clerk, getInitialState]), getInitialState);
1055
+ return useMemo(() => {
1056
+ if (!state) return defaultDerivedInitialState;
1057
+ return authStateFromFull(isInitialState(state) ? deriveState(false, {}, state) : deriveState(true, state, void 0));
1058
+ }, [state]);
1059
+ }
1060
+ function authStateFromFull(derivedState) {
1061
+ return {
1062
+ sessionId: derivedState.sessionId,
1063
+ sessionStatus: derivedState.sessionStatus,
1064
+ sessionClaims: derivedState.sessionClaims,
1065
+ userId: derivedState.userId,
1066
+ actor: derivedState.actor,
1067
+ orgId: derivedState.orgId,
1068
+ orgRole: derivedState.orgRole,
1069
+ orgSlug: derivedState.orgSlug,
1070
+ orgPermissions: derivedState.orgPermissions,
1071
+ factorVerificationAge: derivedState.factorVerificationAge
1072
+ };
1073
+ }
1074
+ function isInitialState(state) {
1075
+ return !("client" in state);
1076
+ }
1077
+
1078
+ //#endregion
1079
+ //#region src/hooks/utils.ts
1080
+ /**
1081
+ * @internal
1082
+ */
1083
+ const clerkLoaded = (isomorphicClerk) => {
1084
+ return new Promise((resolve) => {
1085
+ const handler = (status) => {
1086
+ if (["ready", "degraded"].includes(status)) {
1087
+ resolve();
1088
+ isomorphicClerk.off("status", handler);
1089
+ }
1090
+ };
1091
+ isomorphicClerk.on("status", handler, { notify: true });
1092
+ });
1093
+ };
1094
+ /**
1095
+ * @internal
1096
+ */
1097
+ const createGetToken = (isomorphicClerk) => {
1098
+ return async (options) => {
1099
+ if (!inBrowser()) throw new ClerkRuntimeError("useAuth().getToken() can only be used in browser environments. To access auth data server-side, see the Auth object reference doc: https://clerk.com/docs/reference/backend/types/auth-object", { code: "clerk_runtime_not_browser" });
1100
+ await clerkLoaded(isomorphicClerk);
1101
+ if (!isomorphicClerk.session) return null;
1102
+ return isomorphicClerk.session.getToken(options);
1103
+ };
1104
+ };
1105
+ /**
1106
+ * @internal
1107
+ */
1108
+ const createSignOut = (isomorphicClerk) => {
1109
+ return async (...args) => {
1110
+ await clerkLoaded(isomorphicClerk);
1111
+ return isomorphicClerk.signOut(...args);
1112
+ };
1113
+ };
1114
+
1115
+ //#endregion
1116
+ //#region src/hooks/useAuth.ts
1117
+ /**
1118
+ * The `useAuth()` hook provides access to the current user's authentication state and methods to manage the active session.
1119
+ *
1120
+ * > [!NOTE]
1121
+ * > To access auth data server-side, see the [`Auth` object reference doc](https://clerk.com/docs/reference/backend/types/auth-object).
1122
+ *
1123
+ * <If sdk="nextjs">
1124
+ * By default, Next.js opts all routes into static rendering. If you need to opt a route or routes into dynamic rendering because you need to access the authentication data at request time, you can create a boundary by passing the `dynamic` prop to `<ClerkProvider>`. See the [guide on rendering modes](https://clerk.com/docs/guides/development/rendering-modes) for more information, including code examples.
1125
+ * </If>
1126
+ *
1127
+ * @unionReturnHeadings
1128
+ * ["Loading", "Signed out", "Signed in (no active organization)", "Signed in (with active organization)"]
1129
+ *
1130
+ * @param [options] - An object containing options for the `useAuth()` hook. `treatPendingAsSignedOut` indicates whether pending sessions are considered as signed out or not. Defaults to `true`.
1131
+ *
1132
+ * @function
1133
+ *
1134
+ * @example
1135
+ *
1136
+ * The following example demonstrates how to use the `useAuth()` hook to access the current auth state, like whether the user is signed in or not. It also includes a basic example for using the `getToken()` method to retrieve a session token for fetching data from an external resource.
1137
+ *
1138
+ * <Tabs items='React,Next.js'>
1139
+ * <Tab>
1140
+ *
1141
+ * ```tsx {{ filename: 'src/pages/ExternalDataPage.tsx' }}
1142
+ * import { useAuth } from '@clerk/react'
1143
+ *
1144
+ * export default function ExternalDataPage() {
1145
+ * const { userId, sessionId, getToken, isLoaded, isSignedIn } = useAuth()
1146
+ *
1147
+ * const fetchExternalData = async () => {
1148
+ * const token = await getToken()
1149
+ *
1150
+ * // Fetch data from an external API
1151
+ * const response = await fetch('https://api.example.com/data', {
1152
+ * headers: {
1153
+ * Authorization: `Bearer ${token}`,
1154
+ * },
1155
+ * })
1156
+ *
1157
+ * return response.json()
1158
+ * }
1159
+ *
1160
+ * if (!isLoaded) {
1161
+ * return <div>Loading...</div>
1162
+ * }
1163
+ *
1164
+ * if (!isSignedIn) {
1165
+ * return <div>Sign in to view this page</div>
1166
+ * }
1167
+ *
1168
+ * return (
1169
+ * <div>
1170
+ * <p>
1171
+ * Hello, {userId}! Your current active session is {sessionId}.
1172
+ * </p>
1173
+ * <button onClick={fetchExternalData}>Fetch Data</button>
1174
+ * </div>
1175
+ * )
1176
+ * }
1177
+ * ```
1178
+ *
1179
+ * </Tab>
1180
+ * <Tab>
1181
+ *
1182
+ * {@include ../../docs/use-auth.md#nextjs-01}
1183
+ *
1184
+ * </Tab>
1185
+ * </Tabs>
1186
+ */
1187
+ const useAuth = (options = {}) => {
1188
+ useAssertWrappedByClerkProvider$1("useAuth");
1189
+ const { treatPendingAsSignedOut } = options ?? {};
1190
+ const authState = useAuthBase();
1191
+ const isomorphicClerk = useIsomorphicClerkContext();
1192
+ const getToken = useCallback(createGetToken(isomorphicClerk), [isomorphicClerk]);
1193
+ const signOut = useCallback(createSignOut(isomorphicClerk), [isomorphicClerk]);
1194
+ isomorphicClerk.telemetry?.record(eventMethodCalled("useAuth", { treatPendingAsSignedOut }));
1195
+ return useDerivedAuth({
1196
+ ...authState,
1197
+ getToken,
1198
+ signOut
1199
+ }, { treatPendingAsSignedOut });
1200
+ };
1201
+ /**
1202
+ * A hook that derives and returns authentication state and utility functions based on the provided auth object.
1203
+ *
1204
+ * @param authObject - An object containing authentication-related properties and functions.
1205
+ *
1206
+ * @returns A derived authentication state with helper methods. If the authentication state is invalid, an error is thrown.
1207
+ *
1208
+ * @remarks
1209
+ * This hook inspects session, user, and organization information to determine the current authentication state.
1210
+ * It returns an object that includes various properties such as whether the state is loaded, if a user is signed in,
1211
+ * session and user identifiers, Organization Roles, and a `has` function for authorization checks.
1212
+ * Additionally, it provides `signOut` and `getToken` functions if applicable.
1213
+ *
1214
+ * @example
1215
+ * ```tsx
1216
+ * const {
1217
+ * isLoaded,
1218
+ * isSignedIn,
1219
+ * userId,
1220
+ * orgId,
1221
+ * has,
1222
+ * signOut,
1223
+ * getToken
1224
+ * } = useDerivedAuth(authObject);
1225
+ * ```
1226
+ */
1227
+ function useDerivedAuth(authObject, { treatPendingAsSignedOut = true } = {}) {
1228
+ const { userId, orgId, orgRole, has, signOut, getToken, orgPermissions, factorVerificationAge, sessionClaims } = authObject ?? {};
1229
+ const derivedHas = useCallback((params) => {
1230
+ if (has) return has(params);
1231
+ return createCheckAuthorization({
1232
+ userId,
1233
+ orgId,
1234
+ orgRole,
1235
+ orgPermissions,
1236
+ factorVerificationAge,
1237
+ features: sessionClaims?.fea || "",
1238
+ plans: sessionClaims?.pla || ""
1239
+ })(params);
1240
+ }, [
1241
+ has,
1242
+ userId,
1243
+ orgId,
1244
+ orgRole,
1245
+ orgPermissions,
1246
+ factorVerificationAge,
1247
+ sessionClaims
1248
+ ]);
1249
+ const payload = resolveAuthState({
1250
+ authObject: {
1251
+ ...authObject,
1252
+ getToken,
1253
+ signOut,
1254
+ has: derivedHas
1255
+ },
1256
+ options: { treatPendingAsSignedOut }
1257
+ });
1258
+ if (!payload) return errorThrower.throw(invalidStateError);
1259
+ return payload;
1260
+ }
1261
+
1262
+ //#endregion
1263
+ //#region src/hooks/useEmailLink.ts
1264
+ function useEmailLink(resource) {
1265
+ const { startEmailLinkFlow, cancelEmailLinkFlow } = React.useMemo(() => resource.createEmailLinkFlow(), [resource]);
1266
+ React.useEffect(() => {
1267
+ return cancelEmailLinkFlow;
1268
+ }, []);
1269
+ return {
1270
+ startEmailLinkFlow,
1271
+ cancelEmailLinkFlow
1272
+ };
1273
+ }
1274
+
1275
+ //#endregion
1276
+ //#region src/hooks/useClerkSignal.ts
1277
+ function useClerkSignal(signal) {
1278
+ useAssertWrappedByClerkProvider$1("useClerkSignal");
1279
+ const clerk = useIsomorphicClerkContext();
1280
+ switch (signal) {
1281
+ case "signIn":
1282
+ clerk.telemetry?.record(eventMethodCalled("useSignIn", { apiVersion: "2025-11" }));
1283
+ break;
1284
+ case "signUp":
1285
+ clerk.telemetry?.record(eventMethodCalled("useSignUp", { apiVersion: "2025-11" }));
1286
+ break;
1287
+ case "waitlist":
1288
+ clerk.telemetry?.record(eventMethodCalled("useWaitlist", { apiVersion: "2025-11" }));
1289
+ break;
1290
+ default: break;
1291
+ }
1292
+ const subscribe = useCallback((callback) => {
1293
+ if (!clerk.loaded) return () => {};
1294
+ return clerk.__internal_state.__internal_effect(() => {
1295
+ switch (signal) {
1296
+ case "signIn":
1297
+ clerk.__internal_state.signInSignal();
1298
+ break;
1299
+ case "signUp":
1300
+ clerk.__internal_state.signUpSignal();
1301
+ break;
1302
+ case "waitlist":
1303
+ clerk.__internal_state.waitlistSignal();
1304
+ break;
1305
+ default: throw new Error(`Unknown signal: ${signal}`);
1306
+ }
1307
+ callback();
1308
+ });
1309
+ }, [
1310
+ clerk,
1311
+ clerk.loaded,
1312
+ clerk.__internal_state
1313
+ ]);
1314
+ const getSnapshot = useCallback(() => {
1315
+ switch (signal) {
1316
+ case "signIn": return clerk.__internal_state.signInSignal();
1317
+ case "signUp": return clerk.__internal_state.signUpSignal();
1318
+ case "waitlist": return clerk.__internal_state.waitlistSignal();
1319
+ default: throw new Error(`Unknown signal: ${signal}`);
1320
+ }
1321
+ }, [clerk.__internal_state]);
1322
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
1323
+ }
1324
+ /**
1325
+ * This hook allows you to access the Signal-based `SignIn` resource.
1326
+ *
1327
+ * @example
1328
+ * import { useSignIn } from "@clerk/react";
1329
+ *
1330
+ * function SignInForm() {
1331
+ * const { signIn, errors, fetchStatus } = useSignIn();
1332
+ * //
1333
+ * }
1334
+ */
1335
+ const useSignIn = () => {
1336
+ return useClerkSignal("signIn");
1337
+ };
1338
+ /**
1339
+ * This hook allows you to access the Signal-based `SignUp` resource.
1340
+ *
1341
+ * @example
1342
+ * import { useSignUp } from "@clerk/react";
1343
+ *
1344
+ * function SignUpForm() {
1345
+ * const { signUp, errors, fetchStatus } = useSignUp();
1346
+ * //
1347
+ * }
1348
+ */
1349
+ const useSignUp = () => {
1350
+ return useClerkSignal("signUp");
1351
+ };
1352
+ /**
1353
+ * This hook allows you to access the Signal-based `Waitlist` resource.
1354
+ *
1355
+ * @example
1356
+ * import { useWaitlist } from "@clerk/react";
1357
+ *
1358
+ * function WaitlistForm() {
1359
+ * const { waitlist, errors, fetchStatus } = useWaitlist();
1360
+ * //
1361
+ * }
1362
+ */
1363
+ function useWaitlist() {
1364
+ return useClerkSignal("waitlist");
1365
+ }
1366
+
1367
+ //#endregion
1368
+ export { SignIn as A, withMaxAllowedInstancesGuard as B, CreateOrganization as C, OrganizationProfile as D, OrganizationList as E, UserAvatar as F, safeExecute as G, mergeWithEnv as H, UserButton as I, noPathProvidedError as J, incompatibleRoutingWithPathProvidedError as K, UserProfile as L, TaskChooseOrganization as M, TaskResetPassword as N, OrganizationSwitcher as O, TaskSetupMFA as P, Waitlist as R, APIKeys as S, OAuthConsent as T, assertSingleChild as U, isConstructor as V, normalizeWithDefaultValue as W, unsupportedNonBrowserDomainOrProxyUrlFunction as Y, useSignUp as _, __experimental_usePaymentElement as a, useAuth as b, useOAuthConsent$1 as c, useOrganizationList as d, useReverification as f, useSignIn as g, useUser as h, __experimental_useCheckout as i, SignUp as j, PricingTable as k, useOrganization as l, useSessionList as m, __experimental_PaymentElement as n, useAPIKeys as o, useSession as p, multipleClerkProvidersError as q, __experimental_PaymentElementProvider as r, useClerk as s, __experimental_CheckoutProvider as t, useOrganizationCreationDefaults as u, useWaitlist as v, GoogleOneTap as w, useDerivedAuth as x, useEmailLink as y, withClerk as z };
1369
+ //# sourceMappingURL=hooks-BiY5Zgpp.mjs.map