@clerk/shared 4.34.0 → 4.34.1-canary.v20260923141849

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 (95) hide show
  1. package/dist/alternativePhoneCode.js +1 -2
  2. package/dist/apiUrlFromPublishableKey.js +1 -2
  3. package/dist/authorization-errors.js +1 -2
  4. package/dist/authorization.js +1 -2
  5. package/dist/browser.js +1 -2
  6. package/dist/buildAccountsBaseUrl.js +1 -2
  7. package/dist/clerkEventBus.js +1 -2
  8. package/dist/color.js +1 -2
  9. package/dist/constants.js +1 -2
  10. package/dist/cookie.js +3 -4
  11. package/dist/date.js +1 -2
  12. package/dist/deprecated.js +2 -3
  13. package/dist/deriveState.js +1 -2
  14. package/dist/devBrowser.js +1 -2
  15. package/dist/dom/waitForElement.js +1 -2
  16. package/dist/error.js +42 -32
  17. package/dist/eventBus.js +1 -2
  18. package/dist/file.js +1 -2
  19. package/dist/getEnvVariable.js +1 -2
  20. package/dist/getToken.js +2 -3
  21. package/dist/globs.js +3 -4
  22. package/dist/handleValueOrFn.js +2 -3
  23. package/dist/htmlSafeJson.js +1 -2
  24. package/dist/index.js +1 -2
  25. package/dist/inert.js +1 -2
  26. package/dist/internal/clerk-js/completeSignUpFlow.js +1 -2
  27. package/dist/internal/clerk-js/componentGuards.js +1 -2
  28. package/dist/internal/clerk-js/constants.js +1 -2
  29. package/dist/internal/clerk-js/email.js +1 -2
  30. package/dist/internal/clerk-js/encoders.js +1 -2
  31. package/dist/internal/clerk-js/errors.js +1 -2
  32. package/dist/internal/clerk-js/hex.js +1 -2
  33. package/dist/internal/clerk-js/injectedWeb3EthProviders.js +1 -2
  34. package/dist/internal/clerk-js/injectedWeb3SolanaProviders.js +2 -3
  35. package/dist/internal/clerk-js/navigateToNextStepSignUp.js +1 -2
  36. package/dist/internal/clerk-js/organization.js +1 -2
  37. package/dist/internal/clerk-js/passkeys.js +10 -10
  38. package/dist/internal/clerk-js/passwords/complexity.js +1 -2
  39. package/dist/internal/clerk-js/passwords/loadZxcvbn.js +1 -2
  40. package/dist/internal/clerk-js/passwords/password.js +2 -3
  41. package/dist/internal/clerk-js/passwords/strength.js +1 -2
  42. package/dist/internal/clerk-js/path.js +1 -2
  43. package/dist/internal/clerk-js/protectCheck.js +3 -4
  44. package/dist/internal/clerk-js/queryParams.js +1 -2
  45. package/dist/internal/clerk-js/queryStateParams.js +1 -2
  46. package/dist/internal/clerk-js/querystring.js +1 -2
  47. package/dist/internal/clerk-js/redirectUrls.js +1 -2
  48. package/dist/internal/clerk-js/runtime.js +1 -2
  49. package/dist/internal/clerk-js/sessionTasks.js +1 -2
  50. package/dist/internal/clerk-js/thirdPartyDomains.js +1 -2
  51. package/dist/internal/clerk-js/url.js +1 -2
  52. package/dist/internal/clerk-js/user.js +1 -2
  53. package/dist/internal/clerk-js/warnings.js +1 -2
  54. package/dist/internal/clerk-js/web3.js +5 -5
  55. package/dist/internal/clerk-js/windowNavigate.js +1 -2
  56. package/dist/isomorphicAtob.js +1 -2
  57. package/dist/isomorphicBtoa.js +1 -2
  58. package/dist/jwtPayloadParser.js +1 -2
  59. package/dist/keyless/index.js +12 -369
  60. package/dist/keys.js +1 -2
  61. package/dist/loadClerkJsScript.js +6 -6
  62. package/dist/loadClerkJsScript.js.map +1 -1
  63. package/dist/loadClerkJsScript.mjs +1 -1
  64. package/dist/loadClerkJsScript.mjs.map +1 -1
  65. package/dist/loadScript.js +1 -2
  66. package/dist/localStorageBroadcastChannel.js +1 -2
  67. package/dist/logger.js +1 -2
  68. package/dist/netlifyCacheHandler.js +1 -2
  69. package/dist/oauth.js +1 -2
  70. package/dist/object.js +1 -2
  71. package/dist/organization.js +1 -2
  72. package/dist/patchRequest.js +1 -2
  73. package/dist/pathMatcher.js +2 -3
  74. package/dist/pathToRegexp.js +23 -3
  75. package/dist/phone/index.js +14 -1649
  76. package/dist/poller.js +3 -4
  77. package/dist/proxy.js +1 -2
  78. package/dist/react/index.js +101 -4174
  79. package/dist/retry.js +1 -2
  80. package/dist/router.js +9 -150
  81. package/dist/safeImport.js +1 -2
  82. package/dist/saml.js +1 -2
  83. package/dist/telemetry.js +16 -11
  84. package/dist/underscore.js +1 -2
  85. package/dist/url.js +2 -3
  86. package/dist/utils/index.js +16 -12
  87. package/dist/versionCheck.js +1 -2
  88. package/dist/versionSelector.js +2 -3
  89. package/dist/versionSelector.js.map +1 -1
  90. package/dist/versionSelector.mjs +1 -1
  91. package/dist/versionSelector.mjs.map +1 -1
  92. package/dist/web3.js +1 -2
  93. package/dist/webauthn.js +1 -2
  94. package/dist/workerTimers/index.js +2 -2
  95. package/package.json +1 -1
@@ -1,4175 +1,102 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_chunk = require('../_chunks/chunk-C_NdSu1c.js');
3
- const require_authorization_errors = require('../authorization-errors.js');
4
- const require_authorization = require('../authorization.js');
5
- const require_deriveState = require('../deriveState.js');
6
- const require_clerkRuntimeError = require('../_chunks/clerkRuntimeError-CYZdTZ_x.js');
7
- const require_error = require('../_chunks/error-CdWUgmMd.js');
8
- const require_logger = require('../logger.js');
9
- const require_organization = require('../organization.js');
10
- const require_telemetry = require('../_chunks/telemetry-DZp9OI1j.js');
11
- const require_createDeferredPromise = require('../_chunks/createDeferredPromise-BXa3LUQE.js');
12
- const require_internal_clerk_js_errors = require('../internal/clerk-js/errors.js');
13
- let react = require("react");
14
- react = require_chunk.__toESM(react);
15
- let _tanstack_query_core = require("@tanstack/query-core");
16
- let dequal = require("dequal");
17
-
18
- //#region src/react/hooks/createContextAndHook.ts
19
- /**
20
- * Assert that the context value exists, otherwise throw an error.
21
- *
22
- * @internal
23
- */
24
- function assertContextExists(contextVal, msgOrCtx) {
25
- if (!contextVal) throw typeof msgOrCtx === "string" ? new Error(msgOrCtx) : /* @__PURE__ */ new Error(`${msgOrCtx.displayName} not found`);
26
- }
27
- /**
28
- * Create and return a Context and two hooks that return the context value.
29
- * The Context type is derived from the type passed in by the user.
30
- *
31
- * The first hook returned guarantees that the context exists so the returned value is always `CtxValue`
32
- * The second hook makes no guarantees, so the returned value can be `CtxValue | undefined`
33
- *
34
- * @internal
35
- */
36
- const createContextAndHook = (displayName, options) => {
37
- const { assertCtxFn = assertContextExists } = options || {};
38
- const Ctx = react.default.createContext(void 0);
39
- Ctx.displayName = displayName;
40
- const useCtx = () => {
41
- const ctx = react.default.useContext(Ctx);
42
- assertCtxFn(ctx, `${displayName} not found`);
43
- return ctx.value;
44
- };
45
- const useCtxWithoutGuarantee = () => {
46
- const ctx = react.default.useContext(Ctx);
47
- return ctx ? ctx.value : {};
48
- };
49
- return [
50
- Ctx,
51
- useCtx,
52
- useCtxWithoutGuarantee
53
- ];
54
- };
55
-
56
- //#endregion
57
- //#region src/react/contexts.tsx
58
- const [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook("ClerkInstanceContext");
59
- const [InitialStateContext, _useInitialStateContext] = createContextAndHook("InitialStateContext");
60
- /**
61
- * Provides initial Clerk state (session, user, organization data) from server-side rendering
62
- * to child components via React context.
63
- *
64
- * Passing in a promise is only supported for React >= 19.
65
- *
66
- * The initialState is snapshotted on mount and cannot change during the component lifecycle.
67
- *
68
- * Note that different parts of the React tree can use separate InitialStateProvider instances
69
- * with different initialState values if needed.
70
- */
71
- function InitialStateProvider({ children, initialState }) {
72
- const [initialStateSnapshot] = (0, react.useState)(initialState);
73
- const initialStateCtx = react.default.useMemo(() => ({ value: initialStateSnapshot }), [initialStateSnapshot]);
74
- return /* @__PURE__ */ react.default.createElement(InitialStateContext.Provider, { value: initialStateCtx }, children);
75
- }
76
- function useInitialStateContext() {
77
- const initialState = _useInitialStateContext();
78
- if (initialState instanceof Promise) if ("use" in react.default && typeof react.default.use === "function") return react.default.use(initialState);
79
- else throw new Error("initialState cannot be a promise if React version is less than 19");
80
- return initialState;
81
- }
82
- const OptionsContext = react.default.createContext({});
83
- const [CheckoutContext, useCheckoutContext] = createContextAndHook("CheckoutContext");
84
- const __experimental_CheckoutProvider = ({ children, ...rest }) => {
85
- return /* @__PURE__ */ react.default.createElement(CheckoutContext.Provider, { value: { value: rest } }, children);
86
- };
87
- /**
88
- * @internal
89
- */
90
- function useOptionsContext() {
91
- const context = react.default.useContext(OptionsContext);
92
- if (context === void 0) throw new Error("useOptions must be used within an OptionsContext");
93
- return context;
94
- }
95
- /**
96
- * @internal
97
- */
98
- function useAssertWrappedByClerkProvider(displayNameOrFn) {
99
- if (!react.default.useContext(ClerkInstanceContext)) {
100
- if (typeof displayNameOrFn === "function") {
101
- displayNameOrFn();
102
- return;
103
- }
104
- throw new Error(`${displayNameOrFn} can only be used within the <ClerkProvider /> component.
105
-
106
- Possible fixes:
107
- 1. Ensure that the <ClerkProvider /> is correctly wrapping your application where this component is used.
108
- 2. Check for multiple versions of the \`@clerk/shared\` package in your project. Use a tool like \`npm ls @clerk/shared\` to identify multiple versions, and update your dependencies to only rely on one.
109
-
110
- Learn more: https://clerk.com/docs/components/clerk-provider`.trim());
111
- }
112
- }
113
-
114
- //#endregion
115
- //#region src/react/stable-keys.ts
116
- const USER_MEMBERSHIPS_KEY = "userMemberships";
117
- const USER_INVITATIONS_KEY = "userInvitations";
118
- const USER_SUGGESTIONS_KEY = "userSuggestions";
119
- const DOMAINS_KEY = "domains";
120
- const MEMBERSHIP_REQUESTS_KEY = "membershipRequests";
121
- const MEMBERSHIPS_KEY = "memberships";
122
- const INVITATIONS_KEY = "invitations";
123
- const API_KEYS_KEY = "apiKeys";
124
- const ORGANIZATION_CREATION_DEFAULTS_KEY = "organizationCreationDefaults";
125
- const OAUTH_CONSENT_INFO_KEY = "oauthConsentInfo";
126
- const PLANS_KEY = "billing-plans";
127
- const SUBSCRIPTION_KEY = "billing-subscription";
128
- const PAYMENT_METHODS_KEY = "billing-payment-methods";
129
- const PAYMENT_ATTEMPTS_KEY = "billing-payment-attempts";
130
- const STATEMENTS_KEY = "billing-statements";
131
- const CREDIT_BALANCE_KEY = "billing-credit-balance";
132
- const STABLE_KEYS = {
133
- USER_MEMBERSHIPS_KEY,
134
- USER_INVITATIONS_KEY,
135
- USER_SUGGESTIONS_KEY,
136
- DOMAINS_KEY,
137
- MEMBERSHIP_REQUESTS_KEY,
138
- MEMBERSHIPS_KEY,
139
- INVITATIONS_KEY,
140
- PLANS_KEY,
141
- SUBSCRIPTION_KEY,
142
- PAYMENT_METHODS_KEY,
143
- PAYMENT_ATTEMPTS_KEY,
144
- STATEMENTS_KEY,
145
- API_KEYS_KEY,
146
- ORGANIZATION_CREATION_DEFAULTS_KEY,
147
- OAUTH_CONSENT_INFO_KEY,
148
- CREDIT_BALANCE_KEY
149
- };
150
- /**
151
- * Internal stable keys for queries only used by our UI components.
152
- * These keys are not used by the hooks themselves.
153
- */
154
- const PAYMENT_ATTEMPT_KEY = "billing-payment-attempt";
155
- const BILLING_PLANS_KEY = "billing-plan";
156
- const BILLING_STATEMENTS_KEY = "billing-statement";
157
- const USER_ENTERPRISE_CONNECTIONS_KEY = "userEnterpriseConnections";
158
- const ENTERPRISE_CONNECTION_TEST_RUNS_KEY = "enterpriseConnectionTestRuns";
159
- const ORGANIZATION_ENTERPRISE_CONNECTIONS_KEY = "organizationEnterpriseConnections";
160
- const ORGANIZATION_ENTERPRISE_CONNECTION_TEST_RUNS_KEY = "organizationEnterpriseConnectionTestRuns";
161
- const ORGANIZATION_DOMAINS_KEY = "organizationDomains";
162
- const ORGANIZATION_DIRECTORY_SYNC_KEY = "organizationDirectorySync";
163
- const ORGANIZATION_DIRECTORY_SYNC_USERS_KEY = "organizationDirectorySyncUsers";
164
- const ORGANIZATION_SSO_BYPASS_ALLOWLIST_KEY = "organizationSSOBypassAllowlist";
165
- const CREDIT_HISTORY_KEY = "billing-credit-history";
166
- const INTERNAL_STABLE_KEYS = {
167
- PAYMENT_ATTEMPT_KEY,
168
- BILLING_PLANS_KEY,
169
- BILLING_STATEMENTS_KEY,
170
- CREDIT_HISTORY_KEY,
171
- USER_ENTERPRISE_CONNECTIONS_KEY,
172
- ENTERPRISE_CONNECTION_TEST_RUNS_KEY,
173
- ORGANIZATION_ENTERPRISE_CONNECTIONS_KEY,
174
- ORGANIZATION_ENTERPRISE_CONNECTION_TEST_RUNS_KEY,
175
- ORGANIZATION_DOMAINS_KEY,
176
- ORGANIZATION_DIRECTORY_SYNC_KEY,
177
- ORGANIZATION_DIRECTORY_SYNC_USERS_KEY,
178
- ORGANIZATION_SSO_BYPASS_ALLOWLIST_KEY
179
- };
180
-
181
- //#endregion
182
- //#region src/react/hooks/createCacheKeys.ts
183
- /**
184
- * @internal
185
- */
186
- function createCacheKeys(params) {
187
- return {
188
- queryKey: [
189
- params.stablePrefix,
190
- params.authenticated,
191
- params.tracked,
192
- params.untracked
193
- ],
194
- invalidationKey: [
195
- params.stablePrefix,
196
- params.authenticated,
197
- params.tracked
198
- ],
199
- stableKey: params.stablePrefix,
200
- authenticated: params.authenticated
201
- };
202
- }
203
-
204
- //#endregion
205
- //#region src/react/query/keep-previous-data.ts
206
- /**
207
- * @internal
208
- */
209
- function defineKeepPreviousDataFn(enabled) {
210
- if (enabled) return function KeepPreviousDataFn(previousData) {
211
- return previousData;
212
- };
213
- }
214
-
215
- //#endregion
216
- //#region src/react/query/clerk-query-client.ts
217
- /**
218
- * The QueryClient backing every clerk-query hook. Owned by `@clerk/shared` so the
219
- * `QueryObserver` that observes it and the `Query` objects inside it always
220
- * resolve to the same `@tanstack/query-core` (no cross-bundle drift between
221
- * the consumer-side `@clerk/shared` and the production CDN `clerk-js` bundle).
222
- *
223
- * Lazily instantiated on the client only. Server-side renders return
224
- * `undefined` so per-request renders never share a cache across requests.
225
- */
226
- let clerkQueryClient;
227
- let initialized = false;
228
- function getClerkQueryClient() {
229
- if (typeof window === "undefined") return;
230
- if (!initialized) {
231
- clerkQueryClient = new _tanstack_query_core.QueryClient();
232
- initialized = true;
233
- }
234
- return clerkQueryClient;
235
- }
236
- /**
237
- * Test-only: install a custom client (for deterministic defaults like
238
- * `staleTime: Infinity`) or pass `undefined` to simulate the "no client"
239
- * state without triggering lazy creation on subsequent reads.
240
- */
241
- function __setClerkQueryClientForTest(client) {
242
- clerkQueryClient = client;
243
- initialized = true;
244
- }
245
- /**
246
- * Test-only: build and install a fresh `QueryClient` with deterministic
247
- * defaults (no retries, infinite stale time, no refetching). Returns the
248
- * client so the spec can read/write its cache directly.
249
- *
250
- * Avoids forcing every test consumer to depend on `@tanstack/query-core`.
251
- */
252
- function __createClerkTestQueryClient() {
253
- const client = new _tanstack_query_core.QueryClient({ defaultOptions: { queries: {
254
- retry: false,
255
- staleTime: Infinity,
256
- refetchOnWindowFocus: false,
257
- refetchOnReconnect: false,
258
- refetchOnMount: false
259
- } } });
260
- __setClerkQueryClientForTest(client);
261
- return client;
262
- }
263
- /**
264
- * Test-only: clear both the override and the initialization flag so the
265
- * next read lazy-creates a fresh client.
266
- */
267
- function __resetClerkQueryClientForTest() {
268
- clerkQueryClient = void 0;
269
- initialized = false;
270
- }
271
-
272
- //#endregion
273
- //#region src/react/query/use-clerk-query-client.ts
274
- /**
275
- * Creates a recursively self-referential Proxy that safely handles:
276
- * - Arbitrary property access (e.g., obj.any.prop.path)
277
- * - Function calls at any level (e.g., obj.a().b.c())
278
- * - Construction (e.g., new obj.a.b())
279
- *
280
- * Always returns itself to allow infinite chaining without throwing.
281
- */
282
- function createRecursiveProxy(label) {
283
- const callableTarget = function noop() {};
284
- let self;
285
- self = new Proxy(callableTarget, {
286
- get(_target, prop) {
287
- if (prop === "then") return;
288
- if (prop === "toString") return () => `[${label}]`;
289
- if (prop === Symbol.toPrimitive) return () => 0;
290
- return self;
291
- },
292
- apply() {
293
- return self;
294
- },
295
- construct() {
296
- return self;
297
- },
298
- has() {
299
- return false;
300
- },
301
- set() {
302
- return false;
303
- }
304
- });
305
- return self;
306
- }
307
- const mockQueryClient = createRecursiveProxy("ClerkMockQueryClient");
308
- /**
309
- * Returns `[client, isLoaded]`. The real client is owned by `@clerk/shared`
310
- * and lazily instantiated on the browser only — SSR returns the proxy mock
311
- * + `isLoaded: false` so per-request renders never share a query cache.
312
- */
313
- const useClerkQueryClient = () => {
314
- const client = getClerkQueryClient();
315
- return [client ?? mockQueryClient, Boolean(client)];
316
- };
317
-
318
- //#endregion
319
- //#region src/react/query/useBaseQuery.ts
320
- /**
321
- * Stripped down version of useBaseQuery from @tanstack/query-core.
322
- * This implementation allows for an observer to be created every time a query client changes.
323
- */
324
- /**
325
- * An alternative `useBaseQuery` implementation that allows for an observer to be created every time a query client changes.
326
- *
327
- * @internal
328
- */
329
- function useBaseQuery(options, Observer) {
330
- const [client, isQueryClientLoaded] = useClerkQueryClient();
331
- const defaultedOptions = isQueryClientLoaded ? client.defaultQueryOptions(options) : options;
332
- defaultedOptions._optimisticResults = "optimistic";
333
- const observer = react.useMemo(() => {
334
- return new Observer(client, defaultedOptions);
335
- }, [client]);
336
- const result = observer.getOptimisticResult(defaultedOptions);
337
- const shouldSubscribe = options.subscribed !== false;
338
- react.useSyncExternalStore(react.useCallback((onStoreChange) => {
339
- const unsubscribe = shouldSubscribe ? observer.subscribe(_tanstack_query_core.notifyManager.batchCalls(onStoreChange)) : _tanstack_query_core.noop;
340
- observer.updateResult();
341
- return unsubscribe;
342
- }, [observer, shouldSubscribe]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
343
- react.useEffect(() => {
344
- observer.setOptions(defaultedOptions);
345
- }, [defaultedOptions, observer]);
346
- if (!isQueryClientLoaded) return {
347
- data: void 0,
348
- error: null,
349
- isLoading: options.enabled !== false,
350
- isFetching: false,
351
- status: "pending"
352
- };
353
- return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
354
- }
355
-
356
- //#endregion
357
- //#region src/react/query/useInfiniteQuery.ts
358
- /**
359
- *
360
- */
361
- function useClerkInfiniteQuery(options) {
362
- return useBaseQuery(options, _tanstack_query_core.InfiniteQueryObserver);
363
- }
364
-
365
- //#endregion
366
- //#region src/react/query/useQuery.ts
367
- /**
368
- *
369
- */
370
- function useClerkQuery(options) {
371
- return useBaseQuery(options, _tanstack_query_core.QueryObserver);
372
- }
373
-
374
- //#endregion
375
- //#region src/react/hooks/usePreviousValue.ts
376
- /**
377
- * A hook that retains the previous value of a primitive type.
378
- * It uses a ref to prevent causing unnecessary re-renders.
379
- *
380
- * @internal
381
- *
382
- * @example
383
- * ```
384
- * Render 1: value = 'A' → returns null
385
- * Render 2: value = 'B' → returns 'A'
386
- * Render 3: value = 'B' → returns 'A'
387
- * Render 4: value = 'B' → returns 'A'
388
- * Render 5: value = 'C' → returns 'B'
389
- * ```
390
- */
391
- function usePreviousValue(value) {
392
- const currentRef = (0, react.useRef)(value);
393
- const previousRef = (0, react.useRef)(null);
394
- if (currentRef.current !== value) {
395
- previousRef.current = currentRef.current;
396
- currentRef.current = value;
397
- }
398
- return previousRef.current;
399
- }
400
-
401
- //#endregion
402
- //#region src/react/hooks/useClearQueriesOnSignOut.ts
403
- const withInfiniteKey = (key) => [key, `${key}-inf`];
404
- /**
405
- * Clears React Query caches associated with the given stable prefixes when
406
- * the authenticated state transitions from signed-in to signed-out.
407
- *
408
- * @internal
409
- */
410
- function useClearQueriesOnSignOut(options) {
411
- const { isSignedOut, stableKeys, authenticated = true, onCleanup } = options;
412
- const stableKeysRef = (0, react.useRef)(stableKeys);
413
- const [queryClient] = useClerkQueryClient();
414
- const previousIsSignedIn = usePreviousValue(!isSignedOut);
415
- (0, react.useEffect)(() => {
416
- if (authenticated !== true) return;
417
- if (previousIsSignedIn && isSignedOut === true) {
418
- queryClient.removeQueries({ predicate: (query) => {
419
- const [cachedStableKey, queryAuthenticated] = query.queryKey;
420
- return queryAuthenticated === true && typeof cachedStableKey === "string" && (Array.isArray(stableKeysRef.current) ? stableKeysRef.current.includes(cachedStableKey) : stableKeysRef.current === cachedStableKey);
421
- } });
422
- onCleanup?.();
423
- }
424
- }, [
425
- authenticated,
426
- isSignedOut,
427
- previousIsSignedIn,
428
- queryClient
429
- ]);
430
- }
431
-
432
- //#endregion
433
- //#region src/react/hooks/usePagesOrInfinite.shared.ts
434
- /**
435
- * A hook that safely merges user-provided pagination options with default values.
436
- * It caches initial pagination values (page and size) until component unmount to prevent unwanted rerenders.
437
- *
438
- * @internal
439
- *
440
- * @example
441
- * ```typescript
442
- * // Example 1: With user-provided options
443
- * const userOptions = { initialPage: 2, pageSize: 20, infinite: true };
444
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
445
- * useWithSafeValues(userOptions, defaults);
446
- * // Returns { initialPage: 2, pageSize: 20, infinite: true }
447
- *
448
- * // Example 2: With boolean true (use defaults)
449
- * const params = true;
450
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
451
- * useWithSafeValues(params, defaults);
452
- * // Returns { initialPage: 1, pageSize: 10, infinite: false }
453
- *
454
- * // Example 3: With undefined options (fallback to defaults)
455
- * const params = undefined;
456
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
457
- * useWithSafeValues(params, defaults);
458
- * // Returns { initialPage: 1, pageSize: 10, infinite: false }
459
- * ```
460
- */
461
- const useWithSafeValues = (params, defaultValues) => {
462
- const shouldUseDefaults = typeof params === "boolean" && params;
463
- const initialPageRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.initialPage : params?.initialPage ?? defaultValues.initialPage);
464
- const pageSizeRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.pageSize : params?.pageSize ?? defaultValues.pageSize);
465
- const newObj = {};
466
- for (const key of Object.keys(defaultValues)) newObj[key] = shouldUseDefaults ? defaultValues[key] : params?.[key] ?? defaultValues[key];
467
- return {
468
- ...newObj,
469
- initialPage: initialPageRef.current,
470
- pageSize: pageSizeRef.current
471
- };
472
- };
473
- /**
474
- * Calculates the offset count for pagination based on initial page and page size.
475
- * This represents the number of items to skip before the first page.
476
- *
477
- * @param initialPage - The starting page number (1-based)
478
- * @param pageSize - The number of items per page
479
- * @returns The number of items to offset
480
- *
481
- * @example
482
- * ```typescript
483
- * calculateOffsetCount(1, 10); // Returns 0 (no offset for first page)
484
- * calculateOffsetCount(2, 10); // Returns 10 (skip first 10 items)
485
- * calculateOffsetCount(3, 20); // Returns 40 (skip first 40 items)
486
- * ```
487
- */
488
- function calculateOffsetCount(initialPage, pageSize) {
489
- return (initialPage - 1) * pageSize;
490
- }
491
- /**
492
- * Calculates the total number of pages based on total count, offset, and page size.
493
- *
494
- * @param totalCount - The total number of items
495
- * @param offsetCount - The number of items to offset (from calculateOffsetCount)
496
- * @param pageSize - The number of items per page
497
- * @returns The total number of pages
498
- *
499
- * @example
500
- * ```typescript
501
- * calculatePageCount(100, 0, 10); // Returns 10
502
- * calculatePageCount(95, 0, 10); // Returns 10 (rounds up)
503
- * calculatePageCount(100, 20, 10); // Returns 8 (100 - 20 = 80 items, 8 pages)
504
- * ```
505
- */
506
- function calculatePageCount(totalCount, offsetCount, pageSize) {
507
- return Math.ceil((totalCount - offsetCount) / pageSize);
508
- }
509
- /**
510
- * Determines if there is a next page available in non-infinite pagination mode.
511
- *
512
- * @param totalCount - The total number of items
513
- * @param offsetCount - The number of items to offset
514
- * @param currentPage - The current page number (1-based)
515
- * @param pageSize - The number of items per page
516
- * @returns True if there are more items beyond the current page
517
- *
518
- * @example
519
- * ```typescript
520
- * calculateHasNextPage(100, 0, 1, 10); // Returns true (page 1 of 10)
521
- * calculateHasNextPage(100, 0, 10, 10); // Returns false (last page)
522
- * calculateHasNextPage(25, 0, 2, 10); // Returns true (page 2, 5 more items)
523
- * calculateHasNextPage(20, 0, 2, 10); // Returns false (exactly 2 pages)
524
- * ```
525
- */
526
- function calculateHasNextPage(totalCount, offsetCount, currentPage, pageSize) {
527
- return totalCount - offsetCount > currentPage * pageSize;
528
- }
529
- /**
530
- * Determines if there is a previous page available in non-infinite pagination mode.
531
- *
532
- * @param currentPage - The current page number (1-based)
533
- * @param pageSize - The number of items per page
534
- * @param offsetCount - The number of items to offset
535
- * @returns True if there are pages before the current page
536
- *
537
- * @example
538
- * ```typescript
539
- * calculateHasPreviousPage(1, 10, 0); // Returns false (first page)
540
- * calculateHasPreviousPage(2, 10, 0); // Returns true (can go back to page 1)
541
- * calculateHasPreviousPage(1, 10, 10); // Returns false (first page with offset)
542
- * ```
543
- */
544
- function calculateHasPreviousPage(currentPage, pageSize, offsetCount) {
545
- return (currentPage - 1) * pageSize > offsetCount;
546
- }
547
-
548
- //#endregion
549
- //#region src/react/hooks/usePagesOrInfinite.tsx
550
- const usePagesOrInfinite = (params) => {
551
- const { fetcher, config, keys } = params;
552
- const [paginatedPage, setPaginatedPage] = (0, react.useState)(config.initialPage ?? 1);
553
- const initialPageRef = (0, react.useRef)(config.initialPage ?? 1);
554
- const pageSizeRef = (0, react.useRef)(config.pageSize ?? 10);
555
- const enabled = config.enabled ?? true;
556
- const isSignedIn = config.isSignedIn;
557
- const triggerInfinite = config.infinite ?? false;
558
- const cacheMode = config.__experimental_mode === "cache";
559
- const keepPreviousData = config.keepPreviousData ?? false;
560
- const [queryClient] = useClerkQueryClient();
561
- const queriesEnabled = enabled && Boolean(fetcher) && !cacheMode && isSignedIn !== false;
562
- const [forceUpdateCounter, setForceUpdateCounter] = (0, react.useState)(0);
563
- const forceUpdate = (0, react.useCallback)((updater) => {
564
- setForceUpdateCounter(updater);
565
- }, []);
566
- const pagesQueryKey = (0, react.useMemo)(() => {
567
- const [stablePrefix, authenticated, tracked, untracked] = keys.queryKey;
568
- return [
569
- stablePrefix,
570
- authenticated,
571
- tracked,
572
- {
573
- ...untracked,
574
- args: {
575
- ...untracked.args,
576
- initialPage: paginatedPage,
577
- pageSize: pageSizeRef.current
578
- }
579
- }
580
- ];
581
- }, [keys.queryKey, paginatedPage]);
582
- const singlePageQuery = useClerkQuery({
583
- queryKey: pagesQueryKey,
584
- queryFn: ({ queryKey }) => {
585
- const { args } = queryKey[3];
586
- if (!fetcher) return;
587
- return fetcher(args);
588
- },
589
- staleTime: 6e4,
590
- enabled: queriesEnabled && !triggerInfinite,
591
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
592
- });
593
- const infiniteQueryKey = (0, react.useMemo)(() => {
594
- const [stablePrefix, authenticated, tracked, untracked] = keys.queryKey;
595
- return [
596
- stablePrefix + "-inf",
597
- authenticated,
598
- tracked,
599
- untracked
600
- ];
601
- }, [keys.queryKey]);
602
- const infiniteQuery = useClerkInfiniteQuery({
603
- queryKey: infiniteQueryKey,
604
- initialPageParam: config.initialPage ?? 1,
605
- getNextPageParam: (lastPage, allPages, lastPageParam) => {
606
- const total = lastPage?.total_count ?? 0;
607
- return (allPages.length + (config.initialPage ? config.initialPage - 1 : 0)) * (config.pageSize ?? 10) < total ? lastPageParam + 1 : void 0;
608
- },
609
- queryFn: ({ pageParam, queryKey }) => {
610
- const { args } = queryKey[3];
611
- if (!fetcher) return;
612
- return fetcher({
613
- ...args,
614
- initialPage: pageParam,
615
- pageSize: pageSizeRef.current
616
- });
617
- },
618
- staleTime: 6e4,
619
- enabled: queriesEnabled && triggerInfinite
620
- });
621
- useClearQueriesOnSignOut({
622
- isSignedOut: isSignedIn === false,
623
- authenticated: keys.authenticated,
624
- stableKeys: withInfiniteKey(keys.stableKey),
625
- onCleanup: () => {
626
- setPaginatedPage(initialPageRef.current);
627
- Promise.resolve().then(() => forceUpdate((n) => n + 1));
628
- }
629
- });
630
- const { data, count, page } = (0, react.useMemo)(() => {
631
- if (triggerInfinite) {
632
- const cachedData = queryClient.getQueryData(infiniteQueryKey);
633
- const pages = queriesEnabled ? infiniteQuery.data?.pages ?? cachedData?.pages ?? [] : cachedData?.pages ?? [];
634
- const validPages = Array.isArray(pages) ? pages.filter(Boolean) : [];
635
- return {
636
- data: validPages.map((a) => a?.data).flat().filter(Boolean) ?? [],
637
- count: validPages[validPages.length - 1]?.total_count ?? 0,
638
- page: validPages.length > 0 ? validPages.length : initialPageRef.current
639
- };
640
- }
641
- const pageData = queriesEnabled ? singlePageQuery.data ?? queryClient.getQueryData(pagesQueryKey) : queryClient.getQueryData(pagesQueryKey);
642
- return {
643
- data: Array.isArray(pageData?.data) ? pageData.data : [],
644
- count: typeof pageData?.total_count === "number" ? pageData.total_count : 0,
645
- page: paginatedPage
646
- };
647
- }, [
648
- queriesEnabled,
649
- forceUpdateCounter,
650
- triggerInfinite,
651
- infiniteQuery.data?.pages,
652
- singlePageQuery.data,
653
- queryClient,
654
- infiniteQueryKey,
655
- pagesQueryKey,
656
- paginatedPage
657
- ]);
658
- const fetchPage = (0, react.useCallback)((numberOrgFn) => {
659
- if (triggerInfinite) {
660
- const next = typeof numberOrgFn === "function" ? numberOrgFn(page) : numberOrgFn;
661
- const targetCount = Math.max(0, next);
662
- const cachedData = queryClient.getQueryData(infiniteQueryKey);
663
- if (targetCount - (infiniteQuery.data?.pages ?? cachedData?.pages ?? []).length > 0) infiniteQuery.fetchNextPage({ cancelRefetch: false });
664
- return;
665
- }
666
- return setPaginatedPage(numberOrgFn);
667
- }, [
668
- infiniteQuery,
669
- page,
670
- triggerInfinite,
671
- queryClient,
672
- infiniteQueryKey
673
- ]);
674
- const isLoading = triggerInfinite ? infiniteQuery.isLoading : singlePageQuery.isLoading;
675
- const isFetching = triggerInfinite ? infiniteQuery.isFetching : singlePageQuery.isFetching;
676
- const error = (triggerInfinite ? infiniteQuery.error : singlePageQuery.error) ?? null;
677
- const isError = !!error;
678
- const fetchNext = (0, react.useCallback)(() => {
679
- if (triggerInfinite) {
680
- infiniteQuery.fetchNextPage({ cancelRefetch: false });
681
- return;
682
- }
683
- setPaginatedPage((n) => Math.max(0, n + 1));
684
- }, [infiniteQuery, triggerInfinite]);
685
- const fetchPrevious = (0, react.useCallback)(() => {
686
- if (triggerInfinite) return;
687
- setPaginatedPage((n) => Math.max(0, n - 1));
688
- }, [triggerInfinite]);
689
- const offsetCount = calculateOffsetCount(initialPageRef.current, pageSizeRef.current);
690
- const pageCount = calculatePageCount(count, offsetCount, pageSizeRef.current);
691
- const hasNextPage = triggerInfinite ? Boolean(infiniteQuery.hasNextPage) : calculateHasNextPage(count, offsetCount, page, pageSizeRef.current);
692
- const hasPreviousPage = triggerInfinite ? Boolean(infiniteQuery.hasPreviousPage) : calculateHasPreviousPage(page, pageSizeRef.current, offsetCount);
693
- const setData = (value) => {
694
- if (triggerInfinite) {
695
- queryClient.setQueryData(infiniteQueryKey, (prevValue = {}) => {
696
- const prevPages = Array.isArray(prevValue?.pages) ? prevValue.pages : [];
697
- const nextPages = typeof value === "function" ? value(prevPages) : value;
698
- return {
699
- ...prevValue,
700
- pages: nextPages
701
- };
702
- });
703
- forceUpdate((n) => n + 1);
704
- return Promise.resolve();
705
- }
706
- queryClient.setQueryData(pagesQueryKey, (prevValue = {
707
- data: [],
708
- total_count: 0
709
- }) => {
710
- return typeof value === "function" ? value(prevValue) : value;
711
- });
712
- forceUpdate((n) => n + 1);
713
- return Promise.resolve();
714
- };
715
- const revalidate = async () => {
716
- await queryClient.invalidateQueries({ queryKey: keys.invalidationKey });
717
- const [stablePrefix, ...rest] = keys.invalidationKey;
718
- return queryClient.invalidateQueries({ queryKey: [stablePrefix + "-inf", ...rest] });
719
- };
720
- return {
721
- data,
722
- count,
723
- error,
724
- isLoading,
725
- isFetching,
726
- isError,
727
- page,
728
- pageCount,
729
- fetchPage,
730
- fetchNext,
731
- fetchPrevious,
732
- hasNextPage,
733
- hasPreviousPage,
734
- revalidate,
735
- setData
736
- };
737
- };
738
-
739
- //#endregion
740
- //#region src/react/hooks/useAPIKeys.tsx
741
- /**
742
- * The `useAPIKeys()` hook provides access to paginated API keys for the current user or organization.
743
- *
744
- * @example
745
- * ### Basic usage with default pagination
746
- *
747
- * ```tsx
748
- * const { data, isLoading, page, pageCount, fetchNext, fetchPrevious } = useAPIKeys({
749
- * subject: 'user_123',
750
- * pageSize: 10,
751
- * initialPage: 1,
752
- * });
753
- * ```
754
- *
755
- * @example
756
- * ### With search query
757
- *
758
- * ```tsx
759
- * const [searchValue, setSearchValue] = useState('');
760
- * const debouncedSearch = useDebounce(searchValue, 500);
761
- *
762
- * const { data, isLoading } = useAPIKeys({
763
- * subject: 'user_123',
764
- * query: debouncedSearch.trim(),
765
- * pageSize: 10,
766
- * });
767
- * ```
768
- *
769
- * @example
770
- * ### Infinite scroll
771
- *
772
- * ```tsx
773
- * const { data, isLoading, fetchNext, hasNextPage } = useAPIKeys({
774
- * subject: 'user_123',
775
- * infinite: true,
776
- * });
777
- * ```
778
- */
779
- function useAPIKeys(params) {
780
- useAssertWrappedByClerkProvider("useAPIKeys");
781
- const safeValues = useWithSafeValues(params, {
782
- initialPage: 1,
783
- pageSize: 10,
784
- keepPreviousData: false,
785
- infinite: false,
786
- subject: "",
787
- query: "",
788
- enabled: true
789
- });
790
- const clerk = useClerkInstanceContext();
791
- clerk.telemetry?.record(require_telemetry.eventMethodCalled("useAPIKeys"));
792
- const hookParams = {
793
- initialPage: safeValues.initialPage,
794
- pageSize: safeValues.pageSize,
795
- ...safeValues.subject ? { subject: safeValues.subject } : {},
796
- ...safeValues.query ? { query: safeValues.query } : {}
797
- };
798
- const isEnabled = (safeValues.enabled ?? true) && clerk.loaded;
799
- return usePagesOrInfinite({
800
- fetcher: clerk.apiKeys?.getAll ? (params) => clerk.apiKeys.getAll({
801
- ...params,
802
- subject: safeValues.subject
803
- }) : void 0,
804
- config: {
805
- keepPreviousData: safeValues.keepPreviousData,
806
- infinite: safeValues.infinite,
807
- enabled: isEnabled,
808
- isSignedIn: clerk.user !== null,
809
- initialPage: safeValues.initialPage,
810
- pageSize: safeValues.pageSize
811
- },
812
- keys: createCacheKeys({
813
- stablePrefix: STABLE_KEYS.API_KEYS_KEY,
814
- authenticated: true,
815
- tracked: { subject: safeValues.subject },
816
- untracked: { args: hookParams }
817
- })
818
- });
819
- }
820
-
821
- //#endregion
822
- //#region src/react/hooks/base/useUserBase.ts
823
- function useUserBase() {
824
- const clerk = useClerkInstanceContext();
825
- const initialState = useInitialStateContext();
826
- const getInitialState = (0, react.useCallback)(() => initialState?.user, [initialState?.user]);
827
- return (0, react.useSyncExternalStore)((0, react.useCallback)((callback) => {
828
- return clerk.addListener(callback, { skipInitialEmit: true });
829
- }, [clerk]), (0, react.useCallback)(() => {
830
- if (!clerk.loaded || !clerk.__internal_lastEmittedResources) return getInitialState();
831
- return clerk.__internal_lastEmittedResources.user;
832
- }, [clerk, getInitialState]), getInitialState);
833
- }
834
-
835
- //#endregion
836
- //#region src/react/hooks/useOAuthConsent.shared.ts
837
- function useOAuthConsentCacheKeys(params) {
838
- const { userId, oauthClientId, scope, redirectUri } = params;
839
- return (0, react.useMemo)(() => {
840
- const args = {
841
- oauthClientId,
842
- ...scope !== void 0 && { scope },
843
- ...redirectUri !== void 0 && { redirectUri }
844
- };
845
- return createCacheKeys({
846
- stablePrefix: STABLE_KEYS.OAUTH_CONSENT_INFO_KEY,
847
- authenticated: true,
848
- tracked: { userId: userId ?? null },
849
- untracked: { args }
850
- });
851
- }, [
852
- userId,
853
- oauthClientId,
854
- scope,
855
- redirectUri
856
- ]);
857
- }
858
-
859
- //#endregion
860
- //#region src/react/hooks/useOAuthConsent.tsx
861
- const HOOK_NAME$5 = "useOAuthConsent";
862
- /**
863
- * The `useOAuthConsent()` hook loads OAuth application consent metadata for the **signed-in** user
864
- * (`GET /me/oauth/consent/{oauthClientId}`). Ensure the user is authenticated before relying on this hook
865
- * (e.g., redirect to sign-in on your custom consent route).
866
- *
867
- * @example
868
- * ```tsx
869
- * import { useOAuthConsent } from '@clerk/react/internal'
870
- *
871
- * const { data, isLoading, error } = useOAuthConsent({
872
- * oauthClientId: clientIdFromProps,
873
- * scope: scopeFromProps,
874
- * })
875
- * ```
876
- */
877
- function useOAuthConsent(params) {
878
- useAssertWrappedByClerkProvider(HOOK_NAME$5);
879
- const { oauthClientId: oauthClientIdParam, scope, redirectUri, keepPreviousData = true, enabled = true } = params;
880
- const clerk = useClerkInstanceContext();
881
- const user = useUserBase();
882
- const oauthClientId = (oauthClientIdParam ?? "").trim();
883
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(HOOK_NAME$5));
884
- const { queryKey } = useOAuthConsentCacheKeys({
885
- userId: user?.id ?? null,
886
- oauthClientId,
887
- scope,
888
- redirectUri
889
- });
890
- const hasClientId = oauthClientId.length > 0;
891
- const queryEnabled = Boolean(user) && hasClientId && enabled && clerk.loaded;
892
- const query = useClerkQuery({
893
- queryKey,
894
- queryFn: () => fetchConsentInfo(clerk, {
895
- oauthClientId,
896
- scope,
897
- redirectUri
898
- }),
899
- enabled: queryEnabled,
900
- placeholderData: defineKeepPreviousDataFn(keepPreviousData && queryEnabled)
901
- });
902
- return {
903
- data: query.data,
904
- error: query.error ?? null,
905
- isLoading: query.isLoading,
906
- isFetching: query.isFetching
907
- };
908
- }
909
- function fetchConsentInfo(clerk, params) {
910
- return clerk.oauthApplication.getConsentInfo(params);
911
- }
912
-
913
- //#endregion
914
- //#region src/react/hooks/useOAuthDeviceVerification.tsx
915
- const HOOK_NAME$4 = "useOAuthDeviceVerification";
916
- const normalizeUserCode = (userCode) => userCode.toUpperCase().replace(/[-\p{White_Space}]/gu, "");
917
- const createNotReadyError = () => new require_clerkRuntimeError.ClerkRuntimeError("Clerk must be loaded before using OAuth device verification.", { code: "oauth_device_verification_not_ready" });
918
- const createLookupInProgressError = () => new require_clerkRuntimeError.ClerkRuntimeError("An OAuth device verification lookup is already in progress for another code.", { code: "oauth_device_verification_lookup_in_progress" });
919
- const createSubmissionInProgressError = () => new require_clerkRuntimeError.ClerkRuntimeError("Another OAuth device verification decision is already in progress.", { code: "oauth_device_verification_submission_in_progress" });
920
- /**
921
- * Provides state and actions for building a custom OAuth device verification flow.
922
- *
923
- * @returns The current verification state and methods for looking up, approving, denying, or resetting a request.
924
- *
925
- * @example
926
- * ### Look up a device authorization request
927
- *
928
- * ```tsx
929
- * import { useOAuthDeviceVerification } from '@clerk/react';
930
- *
931
- * function CustomDeviceVerification({ userCode }: { userCode: string }) {
932
- * const { data, isLoading, lookup } = useOAuthDeviceVerification();
933
- *
934
- * const handleLookup = async () => {
935
- * await lookup({ userCode });
936
- * };
937
- *
938
- * return (
939
- * <>
940
- * <button disabled={isLoading} onClick={handleLookup}>Verify code</button>
941
- * {data && <p>Authorize {data.oauthApplicationName}?</p>}
942
- * </>
943
- * );
944
- * }
945
- * ```
946
- */
947
- function useOAuthDeviceVerification() {
948
- useAssertWrappedByClerkProvider(HOOK_NAME$4);
949
- const clerk = useClerkInstanceContext();
950
- const [data, setData] = (0, react.useState)();
951
- const [result, setResult] = (0, react.useState)();
952
- const [error, setError] = (0, react.useState)(null);
953
- const [isLoading, setIsLoading] = (0, react.useState)(false);
954
- const [isSubmitting, setIsSubmitting] = (0, react.useState)(false);
955
- const pendingLookup = (0, react.useRef)(null);
956
- const pendingSubmit = (0, react.useRef)(null);
957
- const generation = (0, react.useRef)(0);
958
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(HOOK_NAME$4));
959
- const lookup = (0, react.useCallback)((params) => {
960
- const oauthApplication = clerk.loaded ? clerk.oauthApplication : void 0;
961
- if (!oauthApplication) return Promise.reject(createNotReadyError());
962
- const key = normalizeUserCode(params.userCode);
963
- if (pendingLookup.current) {
964
- if (pendingLookup.current.key === key) return pendingLookup.current.promise;
965
- return Promise.reject(createLookupInProgressError());
966
- }
967
- const requestGeneration = generation.current;
968
- setError(null);
969
- setData(void 0);
970
- setResult(void 0);
971
- setIsLoading(true);
972
- const request = oauthApplication.lookupDeviceVerification({
973
- ...params,
974
- userCode: key
975
- }).then((info) => {
976
- if (generation.current === requestGeneration) setData(info);
977
- return info;
978
- }).catch((err) => {
979
- if (generation.current === requestGeneration) setError(err);
980
- throw err;
981
- }).finally(() => {
982
- if (pendingLookup.current?.promise === request) pendingLookup.current = null;
983
- if (generation.current === requestGeneration) setIsLoading(false);
984
- });
985
- pendingLookup.current = {
986
- key,
987
- promise: request
988
- };
989
- return request;
990
- }, [clerk]);
991
- const submit = (0, react.useCallback)((params, approved) => {
992
- const oauthApplication = clerk.loaded ? clerk.oauthApplication : void 0;
993
- if (!oauthApplication) return Promise.reject(createNotReadyError());
994
- const userCode = normalizeUserCode(params.userCode);
995
- const key = JSON.stringify([
996
- userCode,
997
- params.organizationId ?? null,
998
- approved
999
- ]);
1000
- if (pendingSubmit.current) {
1001
- if (pendingSubmit.current.key === key) return pendingSubmit.current.promise;
1002
- return Promise.reject(createSubmissionInProgressError());
1003
- }
1004
- const requestGeneration = generation.current;
1005
- setError(null);
1006
- setIsSubmitting(true);
1007
- const request = oauthApplication.submitDeviceVerification({
1008
- ...params,
1009
- userCode,
1010
- approved
1011
- }).then((decision) => {
1012
- if (generation.current === requestGeneration) setResult(decision);
1013
- return decision;
1014
- }).catch((err) => {
1015
- if (generation.current === requestGeneration) setError(err);
1016
- throw err;
1017
- }).finally(() => {
1018
- if (pendingSubmit.current?.promise === request) pendingSubmit.current = null;
1019
- if (generation.current === requestGeneration) setIsSubmitting(false);
1020
- });
1021
- pendingSubmit.current = {
1022
- key,
1023
- promise: request
1024
- };
1025
- return request;
1026
- }, [clerk]);
1027
- return {
1028
- data,
1029
- result,
1030
- error,
1031
- isLoading,
1032
- isSubmitting,
1033
- lookup,
1034
- approve: (0, react.useCallback)((params) => submit(params, true), [submit]),
1035
- deny: (0, react.useCallback)((params) => submit(params, false), [submit]),
1036
- reset: (0, react.useCallback)(() => {
1037
- generation.current += 1;
1038
- pendingLookup.current = null;
1039
- setData(void 0);
1040
- setResult(void 0);
1041
- setError(null);
1042
- setIsLoading(false);
1043
- setIsSubmitting(false);
1044
- }, [])
1045
- };
1046
- }
1047
-
1048
- //#endregion
1049
- //#region src/react/hooks/base/useOrganizationBase.ts
1050
- function useOrganizationBase() {
1051
- const clerk = useClerkInstanceContext();
1052
- const initialState = useInitialStateContext();
1053
- const getInitialState = (0, react.useCallback)(() => initialState?.organization, [initialState?.organization]);
1054
- return (0, react.useSyncExternalStore)((0, react.useCallback)((callback) => clerk.addListener(callback, { skipInitialEmit: true }), [clerk]), (0, react.useCallback)(() => {
1055
- if (!clerk.loaded || !clerk.__internal_lastEmittedResources) return getInitialState();
1056
- return clerk.__internal_lastEmittedResources.organization;
1057
- }, [clerk, getInitialState]), getInitialState);
1058
- }
1059
-
1060
- //#endregion
1061
- //#region src/react/hooks/base/useSessionBase.ts
1062
- function useSessionBase() {
1063
- const clerk = useClerkInstanceContext();
1064
- const initialState = useInitialStateContext();
1065
- const getInitialState = (0, react.useCallback)(() => {
1066
- return initialState ? require_deriveState.deriveFromSsrInitialState(initialState)?.session : void 0;
1067
- }, [initialState]);
1068
- return (0, react.useSyncExternalStore)((0, react.useCallback)((callback) => clerk.addListener(callback, { skipInitialEmit: true }), [clerk]), (0, react.useCallback)(() => {
1069
- if (!clerk.loaded || !clerk.__internal_lastEmittedResources) return getInitialState();
1070
- return clerk.__internal_lastEmittedResources.session;
1071
- }, [clerk, getInitialState]), getInitialState);
1072
- }
1073
-
1074
- //#endregion
1075
- //#region src/react/hooks/useClerk.ts
1076
- /**
1077
- * > [!WARNING]
1078
- * > This hook should only be used for advanced use cases, such as building a completely custom OAuth flow or as an escape hatch to access to the `Clerk` object.
1079
- *
1080
- * The `useClerk()` hook provides access to the [`Clerk`](https://clerk.com/docs/reference/objects/clerk) object, allowing you to build alternatives to any Clerk Component.
1081
- *
1082
- * @function
1083
- *
1084
- * @returns The `useClerk()` hook returns the `Clerk` object, which includes all the methods and properties listed in the [`Clerk` reference](https://clerk.com/docs/reference/objects/clerk).
1085
- *
1086
- * @example
1087
- *
1088
- * The following example uses the `useClerk()` hook to access the `clerk` object. The `clerk` object is used to call the [`openSignIn()`](https://clerk.com/docs/reference/objects/clerk#opensignin) method to open the sign-in modal.
1089
- *
1090
- * <Tabs items='React,Next.js'>
1091
- * <Tab>
1092
- *
1093
- * ```tsx {{ filename: 'src/Home.tsx' }}
1094
- * import { useClerk } from '@clerk/react'
1095
- *
1096
- * export default function Home() {
1097
- * const clerk = useClerk()
1098
- *
1099
- * return <button onClick={() => clerk.openSignIn({})}>Sign in</button>
1100
- * }
1101
- * ```
1102
- *
1103
- * </Tab>
1104
- * <Tab>
1105
- *
1106
- * ```tsx {{ filename: 'app/page.tsx' }}
1107
- * 'use client';
1108
- *
1109
- * import { useClerk } from '@clerk/nextjs';
1110
- *
1111
- * export default function HomePage() {
1112
- * const clerk = useClerk();
1113
- *
1114
- * return <button onClick={() => clerk.openSignIn({})}>Sign in</button>;
1115
- * }
1116
- * ```
1117
- *
1118
- * </Tab>
1119
- * </Tabs>
1120
- */
1121
- const useClerk = () => {
1122
- useAssertWrappedByClerkProvider("useClerk");
1123
- return useClerkInstanceContext();
1124
- };
1125
-
1126
- //#endregion
1127
- //#region src/react/hooks/useAttemptToEnableOrganizations.ts
1128
- /**
1129
- * Attempts to enable the organizations environment setting for a given caller
1130
- *
1131
- * @internal
1132
- */
1133
- function useAttemptToEnableOrganizations(caller, { enabled = true } = {}) {
1134
- const clerk = useClerk();
1135
- const hasAttempted = (0, react.useRef)(false);
1136
- (0, react.useEffect)(() => {
1137
- if (!enabled || hasAttempted.current) return;
1138
- hasAttempted.current = true;
1139
- clerk.__internal_attemptToEnableEnvironmentSetting?.({
1140
- for: "organizations",
1141
- caller
1142
- });
1143
- }, [
1144
- clerk,
1145
- caller,
1146
- enabled
1147
- ]);
1148
- }
1149
-
1150
- //#endregion
1151
- //#region src/react/hooks/useOrganization.tsx
1152
- const undefinedPaginatedResource$1 = {
1153
- data: void 0,
1154
- count: void 0,
1155
- error: void 0,
1156
- isLoading: false,
1157
- isFetching: false,
1158
- isError: false,
1159
- page: void 0,
1160
- pageCount: void 0,
1161
- fetchPage: void 0,
1162
- fetchNext: void 0,
1163
- fetchPrevious: void 0,
1164
- hasNextPage: false,
1165
- hasPreviousPage: false,
1166
- revalidate: void 0,
1167
- setData: void 0
1168
- };
1169
- /**
1170
- * The `useOrganization()` hook retrieves attributes of the currently Active Organization.
1171
- *
1172
- * @example
1173
- * ### Expand and paginate attributes
1174
- *
1175
- * To keep network usage to a minimum, developers are required to opt-in by specifying which resource they need to fetch and paginate through. By default, the `memberships`, `invitations`, `membershipRequests`, and `domains` attributes are not populated. You must pass `true` or an object with the desired properties to fetch and paginate the data.
1176
- *
1177
- * ```tsx
1178
- * // invitations.data will never be populated.
1179
- * const { invitations } = useOrganization()
1180
- *
1181
- * // Use default values to fetch invitations, such as initialPage = 1 and pageSize = 10
1182
- * const { invitations } = useOrganization({
1183
- * invitations: true,
1184
- * })
1185
- *
1186
- * // Pass your own values to fetch invitations
1187
- * const { invitations } = useOrganization({
1188
- * invitations: {
1189
- * pageSize: 20,
1190
- * initialPage: 2, // skips the first page
1191
- * },
1192
- * })
1193
- *
1194
- * // Aggregate pages in order to render an infinite list
1195
- * const { invitations } = useOrganization({
1196
- * invitations: {
1197
- * infinite: true,
1198
- * },
1199
- * })
1200
- * ```
1201
- *
1202
- * @example
1203
- * ### Infinite pagination
1204
- *
1205
- * The following example demonstrates how to use the `infinite` property to fetch and append new data to the existing list. The `memberships` attribute will be populated with the first page of the Organization's memberships. When the "Load more" button is clicked, the `fetchNext` helper function will be called to append the next page of memberships to the list.
1206
- *
1207
- * ```tsx
1208
- * import { useOrganization } from '@clerk/react'
1209
- *
1210
- * export default function MemberList() {
1211
- * const { memberships } = useOrganization({
1212
- * memberships: {
1213
- * infinite: true, // Append new data to the existing list
1214
- * keepPreviousData: true, // Persist the cached data until the new data has been fetched
1215
- * },
1216
- * })
1217
- *
1218
- * if (!memberships) {
1219
- * // Handle loading state
1220
- * return null
1221
- * }
1222
- *
1223
- * return (
1224
- * <div>
1225
- * <h2>Organization members</h2>
1226
- * <ul>
1227
- * {memberships.data?.map((membership) => (
1228
- * <li key={membership.id}>
1229
- * {membership.publicUserData.firstName} {membership.publicUserData.lastName} <
1230
- * {membership.publicUserData.identifier}> :: {membership.role}
1231
- * </li>
1232
- * ))}
1233
- * </ul>
1234
- *
1235
- * <button
1236
- * disabled={!memberships.hasNextPage} // Disable the button if there are no more available pages to be fetched
1237
- * onClick={memberships.fetchNext}
1238
- * >
1239
- * Load more
1240
- * </button>
1241
- * </div>
1242
- * )
1243
- * }
1244
- * ```
1245
- *
1246
- * @example
1247
- * ### Simple pagination
1248
- *
1249
- * The following example demonstrates how to use the `fetchPrevious` and `fetchNext` helper functions to paginate through the data. The `memberships` attribute will be populated with the first page of the Organization's memberships. When the "Previous page" or "Next page" button is clicked, the `fetchPrevious` or `fetchNext` helper function will be called to fetch the previous or next page of memberships.
1250
- *
1251
- * Notice the difference between this example's pagination and the infinite pagination example above.
1252
- *
1253
- * ```tsx
1254
- * import { useOrganization } from '@clerk/react'
1255
- *
1256
- * export default function MemberList() {
1257
- * const { memberships } = useOrganization({
1258
- * memberships: {
1259
- * keepPreviousData: true, // Persist the cached data until the new data has been fetched
1260
- * },
1261
- * })
1262
- *
1263
- * if (!memberships) {
1264
- * // Handle loading state
1265
- * return null
1266
- * }
1267
- *
1268
- * return (
1269
- * <div>
1270
- * <h2>Organization members</h2>
1271
- * <ul>
1272
- * {memberships.data?.map((membership) => (
1273
- * <li key={membership.id}>
1274
- * {membership.publicUserData.firstName} {membership.publicUserData.lastName} <
1275
- * {membership.publicUserData.identifier}> :: {membership.role}
1276
- * </li>
1277
- * ))}
1278
- * </ul>
1279
- *
1280
- * <button disabled={!memberships.hasPreviousPage} onClick={memberships.fetchPrevious}>
1281
- * Previous page
1282
- * </button>
1283
- *
1284
- * <button disabled={!memberships.hasNextPage} onClick={memberships.fetchNext}>
1285
- * Next page
1286
- * </button>
1287
- * </div>
1288
- * )
1289
- * }
1290
- * ```
1291
- */
1292
- function useOrganization(params) {
1293
- const { domains: domainListParams, membershipRequests: membershipRequestsListParams, memberships: membersListParams, invitations: invitationsListParams, __internal_skipAttemptToEnableOrganizations } = params || {};
1294
- useAssertWrappedByClerkProvider("useOrganization");
1295
- useAttemptToEnableOrganizations("useOrganization", { enabled: !__internal_skipAttemptToEnableOrganizations });
1296
- const organization = useOrganizationBase();
1297
- const session = useSessionBase();
1298
- const domainSafeValues = useWithSafeValues(domainListParams, {
1299
- initialPage: 1,
1300
- pageSize: 10,
1301
- keepPreviousData: false,
1302
- infinite: false,
1303
- enrollmentMode: void 0
1304
- });
1305
- const membershipRequestSafeValues = useWithSafeValues(membershipRequestsListParams, {
1306
- initialPage: 1,
1307
- pageSize: 10,
1308
- status: "pending",
1309
- keepPreviousData: false,
1310
- infinite: false
1311
- });
1312
- const membersSafeValues = useWithSafeValues(membersListParams, {
1313
- initialPage: 1,
1314
- pageSize: 10,
1315
- role: void 0,
1316
- keepPreviousData: false,
1317
- infinite: false,
1318
- query: void 0
1319
- });
1320
- const invitationsSafeValues = useWithSafeValues(invitationsListParams, {
1321
- initialPage: 1,
1322
- pageSize: 10,
1323
- status: ["pending"],
1324
- keepPreviousData: false,
1325
- infinite: false
1326
- });
1327
- const clerk = useClerkInstanceContext();
1328
- clerk.telemetry?.record(require_telemetry.eventMethodCalled("useOrganization"));
1329
- const domainParams = typeof domainListParams === "undefined" ? void 0 : {
1330
- initialPage: domainSafeValues.initialPage,
1331
- pageSize: domainSafeValues.pageSize,
1332
- enrollmentMode: domainSafeValues.enrollmentMode
1333
- };
1334
- const membershipRequestParams = typeof membershipRequestsListParams === "undefined" ? void 0 : {
1335
- initialPage: membershipRequestSafeValues.initialPage,
1336
- pageSize: membershipRequestSafeValues.pageSize,
1337
- status: membershipRequestSafeValues.status
1338
- };
1339
- const membersParams = typeof membersListParams === "undefined" ? void 0 : {
1340
- initialPage: membersSafeValues.initialPage,
1341
- pageSize: membersSafeValues.pageSize,
1342
- role: membersSafeValues.role,
1343
- query: membersSafeValues.query
1344
- };
1345
- const invitationsParams = typeof invitationsListParams === "undefined" ? void 0 : {
1346
- initialPage: invitationsSafeValues.initialPage,
1347
- pageSize: invitationsSafeValues.pageSize,
1348
- status: invitationsSafeValues.status
1349
- };
1350
- const domains = usePagesOrInfinite({
1351
- fetcher: organization?.getDomains,
1352
- config: {
1353
- keepPreviousData: domainSafeValues.keepPreviousData,
1354
- infinite: domainSafeValues.infinite,
1355
- enabled: !!domainParams,
1356
- isSignedIn: organization !== null,
1357
- initialPage: domainSafeValues.initialPage,
1358
- pageSize: domainSafeValues.pageSize
1359
- },
1360
- keys: createCacheKeys({
1361
- stablePrefix: STABLE_KEYS.DOMAINS_KEY,
1362
- authenticated: true,
1363
- tracked: { organizationId: organization?.id },
1364
- untracked: { args: domainParams }
1365
- })
1366
- });
1367
- const membershipRequests = usePagesOrInfinite({
1368
- fetcher: organization?.getMembershipRequests,
1369
- config: {
1370
- keepPreviousData: membershipRequestSafeValues.keepPreviousData,
1371
- infinite: membershipRequestSafeValues.infinite,
1372
- enabled: !!membershipRequestParams,
1373
- isSignedIn: organization !== null,
1374
- initialPage: membershipRequestSafeValues.initialPage,
1375
- pageSize: membershipRequestSafeValues.pageSize
1376
- },
1377
- keys: createCacheKeys({
1378
- stablePrefix: STABLE_KEYS.MEMBERSHIP_REQUESTS_KEY,
1379
- authenticated: true,
1380
- tracked: { organizationId: organization?.id },
1381
- untracked: { args: membershipRequestParams }
1382
- })
1383
- });
1384
- const memberships = usePagesOrInfinite({
1385
- fetcher: organization?.getMemberships,
1386
- config: {
1387
- keepPreviousData: membersSafeValues.keepPreviousData,
1388
- infinite: membersSafeValues.infinite,
1389
- enabled: !!membersParams,
1390
- isSignedIn: organization !== null,
1391
- initialPage: membersSafeValues.initialPage,
1392
- pageSize: membersSafeValues.pageSize
1393
- },
1394
- keys: createCacheKeys({
1395
- stablePrefix: STABLE_KEYS.MEMBERSHIPS_KEY,
1396
- authenticated: true,
1397
- tracked: { organizationId: organization?.id },
1398
- untracked: { args: membersParams }
1399
- })
1400
- });
1401
- const invitations = usePagesOrInfinite({
1402
- fetcher: organization?.getInvitations,
1403
- config: {
1404
- keepPreviousData: invitationsSafeValues.keepPreviousData,
1405
- infinite: invitationsSafeValues.infinite,
1406
- enabled: !!invitationsParams,
1407
- isSignedIn: organization !== null,
1408
- initialPage: invitationsSafeValues.initialPage,
1409
- pageSize: invitationsSafeValues.pageSize
1410
- },
1411
- keys: createCacheKeys({
1412
- stablePrefix: STABLE_KEYS.INVITATIONS_KEY,
1413
- authenticated: true,
1414
- tracked: { organizationId: organization?.id },
1415
- untracked: { args: invitationsParams }
1416
- })
1417
- });
1418
- if (organization === void 0) return {
1419
- isLoaded: false,
1420
- organization: void 0,
1421
- membership: void 0,
1422
- domains: undefinedPaginatedResource$1,
1423
- membershipRequests: undefinedPaginatedResource$1,
1424
- memberships: undefinedPaginatedResource$1,
1425
- invitations: undefinedPaginatedResource$1
1426
- };
1427
- if (organization === null) return {
1428
- isLoaded: true,
1429
- organization: null,
1430
- membership: null,
1431
- domains: null,
1432
- membershipRequests: null,
1433
- memberships: null,
1434
- invitations: null
1435
- };
1436
- /** In SSR context we include only the organization object when loadOrg is set to true. */
1437
- if (!clerk.loaded && organization) return {
1438
- isLoaded: true,
1439
- organization,
1440
- membership: void 0,
1441
- domains: undefinedPaginatedResource$1,
1442
- membershipRequests: undefinedPaginatedResource$1,
1443
- memberships: undefinedPaginatedResource$1,
1444
- invitations: undefinedPaginatedResource$1
1445
- };
1446
- return {
1447
- isLoaded: clerk.loaded,
1448
- organization,
1449
- membership: require_organization.getCurrentOrganizationMembership(session.user.organizationMemberships, organization.id),
1450
- domains,
1451
- membershipRequests,
1452
- memberships,
1453
- invitations
1454
- };
1455
- }
1456
-
1457
- //#endregion
1458
- //#region src/react/hooks/useOrganizationCreationDefaults.shared.ts
1459
- function useOrganizationCreationDefaultsCacheKeys(params) {
1460
- const { userId } = params;
1461
- return (0, react.useMemo)(() => {
1462
- return createCacheKeys({
1463
- stablePrefix: STABLE_KEYS.ORGANIZATION_CREATION_DEFAULTS_KEY,
1464
- authenticated: Boolean(userId),
1465
- tracked: { userId: userId ?? null },
1466
- untracked: { args: {} }
1467
- });
1468
- }, [userId]);
1469
- }
1470
-
1471
- //#endregion
1472
- //#region src/react/hooks/useOrganizationCreationDefaults.tsx
1473
- const HOOK_NAME$3 = "useOrganizationCreationDefaults";
1474
- /**
1475
- * The `useOrganizationCreationDefaults()` hook retrieves the organization creation defaults for the current user.
1476
- *
1477
- * @example
1478
- * ### Basic usage
1479
- *
1480
- * ```tsx
1481
- * import { useOrganizationCreationDefaults } from '@clerk/clerk-react'
1482
- *
1483
- * export default function CreateOrganizationForm() {
1484
- * const { data, isLoading } = useOrganizationCreationDefaults()
1485
- *
1486
- * if (isLoading) return <div>Loading...</div>
1487
- *
1488
- * return (
1489
- * <form>
1490
- * <input defaultValue={data?.form.name} placeholder="Organization name" />
1491
- * <input defaultValue={data?.form.slug} placeholder="Slug" />
1492
- * <button type="submit">Create</button>
1493
- * </form>
1494
- * )
1495
- * }
1496
- * ```
1497
- */
1498
- function useOrganizationCreationDefaults(params = {}) {
1499
- useAssertWrappedByClerkProvider(HOOK_NAME$3);
1500
- const { keepPreviousData = true, enabled = true } = params;
1501
- const clerk = useClerkInstanceContext();
1502
- const user = useUserBase();
1503
- const featureEnabled = clerk.__internal_environment?.organizationSettings?.organizationCreationDefaults?.enabled ?? false;
1504
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(HOOK_NAME$3));
1505
- const { queryKey } = useOrganizationCreationDefaultsCacheKeys({ userId: user?.id ?? null });
1506
- const queryEnabled = Boolean(user) && enabled && featureEnabled && clerk.loaded;
1507
- const query = useClerkQuery({
1508
- queryKey,
1509
- queryFn: user?.getOrganizationCreationDefaults,
1510
- enabled: queryEnabled,
1511
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
1512
- });
1513
- return {
1514
- data: query.data,
1515
- error: query.error ?? null,
1516
- isLoading: query.isLoading,
1517
- isFetching: query.isFetching
1518
- };
1519
- }
1520
-
1521
- //#endregion
1522
- //#region src/react/hooks/useOrganizationList.tsx
1523
- const undefinedPaginatedResource = {
1524
- data: void 0,
1525
- count: void 0,
1526
- error: void 0,
1527
- isLoading: false,
1528
- isFetching: false,
1529
- isError: false,
1530
- page: void 0,
1531
- pageCount: void 0,
1532
- fetchPage: void 0,
1533
- fetchNext: void 0,
1534
- fetchPrevious: void 0,
1535
- hasNextPage: false,
1536
- hasPreviousPage: false,
1537
- revalidate: void 0,
1538
- setData: void 0
1539
- };
1540
- /**
1541
- * The `useOrganizationList()` hook provides access to the current user's organization memberships, invitations, and suggestions. It also includes methods for creating new organizations and managing the active organization.
1542
- *
1543
- * @example
1544
- * ### Expanding and paginating attributes
1545
- *
1546
- * To keep network usage to a minimum, developers are required to opt-in by specifying which resource they need to fetch and paginate through. So by default, the `userMemberships`, `userInvitations`, and `userSuggestions` attributes are not populated. You must pass true or an object with the desired properties to fetch and paginate the data.
1547
- *
1548
- * ```tsx
1549
- * // userMemberships.data will never be populated
1550
- * const { userMemberships } = useOrganizationList()
1551
- *
1552
- * // Use default values to fetch userMemberships, such as initialPage = 1 and pageSize = 10
1553
- * const { userMemberships } = useOrganizationList({
1554
- * userMemberships: true,
1555
- * })
1556
- *
1557
- * // Pass your own values to fetch userMemberships
1558
- * const { userMemberships } = useOrganizationList({
1559
- * userMemberships: {
1560
- * pageSize: 20,
1561
- * initialPage: 2, // skips the first page
1562
- * },
1563
- * })
1564
- *
1565
- * // Aggregate pages in order to render an infinite list
1566
- * const { userMemberships } = useOrganizationList({
1567
- * userMemberships: {
1568
- * infinite: true,
1569
- * },
1570
- * })
1571
- * ```
1572
- *
1573
- * @example
1574
- * ### Infinite pagination
1575
- *
1576
- * The following example demonstrates how to use the `infinite` property to fetch and append new data to the existing list. The `userMemberships` attribute will be populated with the first page of the user's Organization memberships. When the "Load more" button is clicked, the `fetchNext` helper function will be called to append the next page of memberships to the list.
1577
- *
1578
- * ```tsx {{ filename: 'src/components/JoinedOrganizations.tsx' }}
1579
- * import { useOrganizationList } from '@clerk/react'
1580
- * import React from 'react'
1581
- *
1582
- * const JoinedOrganizations = () => {
1583
- * const { isLoaded, setActive, userMemberships } = useOrganizationList({
1584
- * userMemberships: {
1585
- * infinite: true,
1586
- * },
1587
- * })
1588
- *
1589
- * if (!isLoaded) {
1590
- * return <>Loading</>
1591
- * }
1592
- *
1593
- * return (
1594
- * <>
1595
- * <ul>
1596
- * {userMemberships.data?.map((mem) => (
1597
- * <li key={mem.id}>
1598
- * <span>{mem.organization.name}</span>
1599
- * <button onClick={() => setActive({ organization: mem.organization.id })}>Select</button>
1600
- * </li>
1601
- * ))}
1602
- * </ul>
1603
- *
1604
- * <button disabled={!userMemberships.hasNextPage} onClick={() => userMemberships.fetchNext()}>
1605
- * Load more
1606
- * </button>
1607
- * </>
1608
- * )
1609
- * }
1610
- *
1611
- * export default JoinedOrganizations
1612
- * ```
1613
- *
1614
- * @example
1615
- * ### Simple pagination
1616
- *
1617
- * The following example demonstrates how to use the `fetchPrevious` and `fetchNext` helper functions to paginate through the data. The `userInvitations` attribute will be populated with the first page of invitations. When the "Previous page" or "Next page" button is clicked, the `fetchPrevious` or `fetchNext` helper function will be called to fetch the previous or next page of invitations.
1618
- *
1619
- * Notice the difference between this example's pagination and the infinite pagination example above.
1620
- *
1621
- * ```tsx {{ filename: 'src/components/UserInvitationsTable.tsx' }}
1622
- * import { useOrganizationList } from '@clerk/react'
1623
- * import React from 'react'
1624
- *
1625
- * const UserInvitationsTable = () => {
1626
- * const { isLoaded, userInvitations } = useOrganizationList({
1627
- * userInvitations: {
1628
- * infinite: true,
1629
- * keepPreviousData: true,
1630
- * },
1631
- * })
1632
- *
1633
- * if (!isLoaded || userInvitations.isLoading) {
1634
- * return <>Loading</>
1635
- * }
1636
- *
1637
- * return (
1638
- * <>
1639
- * <table>
1640
- * <thead>
1641
- * <tr>
1642
- * <th>Email</th>
1643
- * <th>Org name</th>
1644
- * </tr>
1645
- * </thead>
1646
- *
1647
- * <tbody>
1648
- * {userInvitations.data?.map((inv) => (
1649
- * <tr key={inv.id}>
1650
- * <th>{inv.emailAddress}</th>
1651
- * <th>{inv.publicOrganizationData.name}</th>
1652
- * </tr>
1653
- * ))}
1654
- * </tbody>
1655
- * </table>
1656
- *
1657
- * <button disabled={!userInvitations.hasPreviousPage} onClick={userInvitations.fetchPrevious}>
1658
- * Prev
1659
- * </button>
1660
- * <button disabled={!userInvitations.hasNextPage} onClick={userInvitations.fetchNext}>
1661
- * Next
1662
- * </button>
1663
- * </>
1664
- * )
1665
- * }
1666
- *
1667
- * export default UserInvitationsTable
1668
- * ```
1669
- */
1670
- function useOrganizationList(params) {
1671
- const { userMemberships, userInvitations, userSuggestions } = params || {};
1672
- useAssertWrappedByClerkProvider("useOrganizationList");
1673
- useAttemptToEnableOrganizations("useOrganizationList", { enabled: userMemberships !== void 0 || userInvitations !== void 0 || userSuggestions !== void 0 });
1674
- const userMembershipsSafeValues = useWithSafeValues(userMemberships, {
1675
- initialPage: 1,
1676
- pageSize: 10,
1677
- keepPreviousData: false,
1678
- infinite: false
1679
- });
1680
- const userInvitationsSafeValues = useWithSafeValues(userInvitations, {
1681
- initialPage: 1,
1682
- pageSize: 10,
1683
- status: "pending",
1684
- keepPreviousData: false,
1685
- infinite: false
1686
- });
1687
- const userSuggestionsSafeValues = useWithSafeValues(userSuggestions, {
1688
- initialPage: 1,
1689
- pageSize: 10,
1690
- status: "pending",
1691
- keepPreviousData: false,
1692
- infinite: false
1693
- });
1694
- const clerk = useClerkInstanceContext();
1695
- const user = useUserBase();
1696
- clerk.telemetry?.record(require_telemetry.eventMethodCalled("useOrganizationList"));
1697
- const userMembershipsParams = typeof userMemberships === "undefined" ? void 0 : {
1698
- initialPage: userMembershipsSafeValues.initialPage,
1699
- pageSize: userMembershipsSafeValues.pageSize
1700
- };
1701
- const userInvitationsParams = typeof userInvitations === "undefined" ? void 0 : {
1702
- initialPage: userInvitationsSafeValues.initialPage,
1703
- pageSize: userInvitationsSafeValues.pageSize,
1704
- status: userInvitationsSafeValues.status
1705
- };
1706
- const userSuggestionsParams = typeof userSuggestions === "undefined" ? void 0 : {
1707
- initialPage: userSuggestionsSafeValues.initialPage,
1708
- pageSize: userSuggestionsSafeValues.pageSize,
1709
- status: userSuggestionsSafeValues.status
1710
- };
1711
- const isClerkLoaded = !!(clerk.loaded && user);
1712
- const memberships = usePagesOrInfinite({
1713
- fetcher: user?.getOrganizationMemberships,
1714
- config: {
1715
- keepPreviousData: userMembershipsSafeValues.keepPreviousData,
1716
- infinite: userMembershipsSafeValues.infinite,
1717
- enabled: !!userMembershipsParams,
1718
- isSignedIn: user !== null,
1719
- initialPage: userMembershipsSafeValues.initialPage,
1720
- pageSize: userMembershipsSafeValues.pageSize
1721
- },
1722
- keys: createCacheKeys({
1723
- stablePrefix: STABLE_KEYS.USER_MEMBERSHIPS_KEY,
1724
- authenticated: true,
1725
- tracked: { userId: user?.id },
1726
- untracked: { args: userMembershipsParams }
1727
- })
1728
- });
1729
- const invitations = usePagesOrInfinite({
1730
- fetcher: user?.getOrganizationInvitations,
1731
- config: {
1732
- keepPreviousData: userInvitationsSafeValues.keepPreviousData,
1733
- infinite: userInvitationsSafeValues.infinite,
1734
- enabled: !!userInvitationsParams,
1735
- isSignedIn: user !== null,
1736
- initialPage: userInvitationsSafeValues.initialPage,
1737
- pageSize: userInvitationsSafeValues.pageSize
1738
- },
1739
- keys: createCacheKeys({
1740
- stablePrefix: STABLE_KEYS.USER_INVITATIONS_KEY,
1741
- authenticated: true,
1742
- tracked: { userId: user?.id },
1743
- untracked: { args: userInvitationsParams }
1744
- })
1745
- });
1746
- const suggestions = usePagesOrInfinite({
1747
- fetcher: user?.getOrganizationSuggestions,
1748
- config: {
1749
- keepPreviousData: userSuggestionsSafeValues.keepPreviousData,
1750
- infinite: userSuggestionsSafeValues.infinite,
1751
- enabled: !!userSuggestionsParams,
1752
- isSignedIn: user !== null,
1753
- initialPage: userSuggestionsSafeValues.initialPage,
1754
- pageSize: userSuggestionsSafeValues.pageSize
1755
- },
1756
- keys: createCacheKeys({
1757
- stablePrefix: STABLE_KEYS.USER_SUGGESTIONS_KEY,
1758
- authenticated: true,
1759
- tracked: { userId: user?.id },
1760
- untracked: { args: userSuggestionsParams }
1761
- })
1762
- });
1763
- if (!isClerkLoaded) return {
1764
- isLoaded: false,
1765
- createOrganization: void 0,
1766
- setActive: void 0,
1767
- userMemberships: undefinedPaginatedResource,
1768
- userInvitations: undefinedPaginatedResource,
1769
- userSuggestions: undefinedPaginatedResource
1770
- };
1771
- return {
1772
- isLoaded: isClerkLoaded,
1773
- setActive: clerk.setActive,
1774
- createOrganization: clerk.createOrganization,
1775
- userMemberships: memberships,
1776
- userInvitations: invitations,
1777
- userSuggestions: suggestions
1778
- };
1779
- }
1780
-
1781
- //#endregion
1782
- //#region src/react/hooks/useSafeLayoutEffect.tsx
1783
- /**
1784
- * @internal
1785
- */
1786
- const useSafeLayoutEffect = typeof window !== "undefined" ? react.default.useLayoutEffect : react.default.useEffect;
1787
-
1788
- //#endregion
1789
- //#region src/react/hooks/useSession.ts
1790
- const hookName$2 = `useSession`;
1791
- /**
1792
- * The `useSession()` hook provides access to the current user's [`Session`](https://clerk.com/docs/reference/objects/session) object, as well as helpers for setting the active session.
1793
- *
1794
- * @unionReturnHeadings
1795
- * ["Loading", "Signed out", "Signed in"]
1796
- *
1797
- * @function
1798
- *
1799
- * @param [options] - An object containing options for the `useSession()` hook.
1800
- * @example
1801
- * ### Access the `Session` object
1802
- *
1803
- * The following example uses the `useSession()` hook to access the `Session` object, which has the `lastActiveAt` property. The `lastActiveAt` property is a `Date` object used to show the time the session was last active.
1804
- *
1805
- * <Tabs items='React,Next.js'>
1806
- * <Tab>
1807
- *
1808
- * ```tsx {{ filename: 'src/Home.tsx' }}
1809
- * import { useSession } from '@clerk/react'
1810
- *
1811
- * export default function Home() {
1812
- * const { isLoaded, session, isSignedIn } = useSession()
1813
- *
1814
- * if (!isLoaded) {
1815
- * // Handle loading state
1816
- * return null
1817
- * }
1818
- * if (!isSignedIn) {
1819
- * // Handle signed out state
1820
- * return null
1821
- * }
1822
- *
1823
- * return (
1824
- * <div>
1825
- * <p>This session has been active since {session.lastActiveAt.toLocaleString()}</p>
1826
- * </div>
1827
- * )
1828
- * }
1829
- * ```
1830
- *
1831
- * </Tab>
1832
- * <Tab>
1833
- *
1834
- * ```tsx {{ filename: 'app/page.tsx' }}
1835
- * 'use client';
1836
- *
1837
- * import { useSession } from '@clerk/nextjs';
1838
- *
1839
- * export default function HomePage() {
1840
- * const { isLoaded, session, isSignedIn } = useSession();
1841
- *
1842
- * if (!isLoaded) {
1843
- * // Handle loading state
1844
- * return null;
1845
- * }
1846
- * if (!isSignedIn) {
1847
- * // Handle signed out state
1848
- * return null;
1849
- * }
1850
- *
1851
- * return (
1852
- * <div>
1853
- * <p>This session has been active since {session.lastActiveAt.toLocaleString()}</p>
1854
- * </div>
1855
- * );
1856
- * }
1857
- * ```
1858
- *
1859
- * </Tab>
1860
- * </Tabs>
1861
- */
1862
- const useSession = () => {
1863
- useAssertWrappedByClerkProvider(hookName$2);
1864
- const session = useSessionBase();
1865
- const clerk = useClerkInstanceContext();
1866
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName$2));
1867
- if (session === void 0) return {
1868
- isLoaded: false,
1869
- isSignedIn: void 0,
1870
- session: void 0
1871
- };
1872
- if (session === null) return {
1873
- isLoaded: true,
1874
- isSignedIn: false,
1875
- session: null
1876
- };
1877
- return {
1878
- isLoaded: true,
1879
- isSignedIn: clerk.isSignedIn,
1880
- session
1881
- };
1882
- };
1883
-
1884
- //#endregion
1885
- //#region src/react/hooks/base/useClientBase.ts
1886
- const initialSnapshot = void 0;
1887
- const getInitialSnapshot = () => initialSnapshot;
1888
- function useClientBase() {
1889
- const clerk = useClerkInstanceContext();
1890
- return (0, react.useSyncExternalStore)((0, react.useCallback)((callback) => clerk.addListener(callback, { skipInitialEmit: true }), [clerk]), (0, react.useCallback)(() => {
1891
- if (!clerk.loaded || !clerk.__internal_lastEmittedResources) return;
1892
- return clerk.__internal_lastEmittedResources.client;
1893
- }, [clerk]), getInitialSnapshot);
1894
- }
1895
-
1896
- //#endregion
1897
- //#region src/react/hooks/useSessionList.ts
1898
- const hookName$1 = "useSessionList";
1899
- /**
1900
- * The `useSessionList()` hook returns an array of [`Session`](https://clerk.com/docs/reference/objects/session) objects that have been registered on the client device.
1901
- *
1902
- * @unionReturnHeadings
1903
- * ["Initialization", "Loaded"]
1904
- *
1905
- * @function
1906
- *
1907
- * @example
1908
- * ### Get a list of sessions
1909
- *
1910
- * The following example uses `useSessionList()` to get a list of sessions that have been registered on the client device. The `sessions` property is used to show the number of times the user has visited the page.
1911
- *
1912
- * <Tabs items='React,Next.js'>
1913
- * <Tab>
1914
- *
1915
- * ```tsx {{ filename: 'src/Home.tsx' }}
1916
- * import { useSessionList } from '@clerk/react'
1917
- *
1918
- * export default function Home() {
1919
- * const { isLoaded, sessions } = useSessionList()
1920
- *
1921
- * if (!isLoaded) {
1922
- * // Handle loading state
1923
- * return null
1924
- * }
1925
- *
1926
- * return (
1927
- * <div>
1928
- * <p>Welcome back. You've been here {sessions.length} times before.</p>
1929
- * </div>
1930
- * )
1931
- * }
1932
- * ```
1933
- *
1934
- * </Tab>
1935
- * <Tab>
1936
- *
1937
- * ```tsx {{ filename: 'app/page.tsx' }}
1938
- * 'use client';
1939
- *
1940
- * import { useSessionList } from '@clerk/nextjs';
1941
- *
1942
- * export default function HomePage() {
1943
- * const { isLoaded, sessions } = useSessionList();
1944
- *
1945
- * if (!isLoaded) {
1946
- * // Handle loading state
1947
- * return null;
1948
- * }
1949
- *
1950
- * return (
1951
- * <div>
1952
- * <p>Welcome back. You've been here {sessions.length} times before.</p>
1953
- * </div>
1954
- * );
1955
- * }
1956
- * ```
1957
- *
1958
- * </Tab>
1959
- * </Tabs>
1960
- */
1961
- const useSessionList = () => {
1962
- useAssertWrappedByClerkProvider(hookName$1);
1963
- const isomorphicClerk = useClerkInstanceContext();
1964
- const client = useClientBase();
1965
- useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName$1));
1966
- if (!client) return {
1967
- isLoaded: false,
1968
- sessions: void 0,
1969
- setActive: void 0
1970
- };
1971
- return {
1972
- isLoaded: true,
1973
- sessions: client.sessions,
1974
- setActive: isomorphicClerk.setActive
1975
- };
1976
- };
1977
-
1978
- //#endregion
1979
- //#region src/react/hooks/useUser.ts
1980
- const hookName = "useUser";
1981
- /**
1982
- * The `useUser()` hook provides access to the current user's [`User`](https://clerk.com/docs/reference/objects/user) object, which contains all the data for a single user in your application and provides methods to manage their account. This hook also allows you to check if the user is signed in and if Clerk has loaded.
1983
- *
1984
- * @unionReturnHeadings
1985
- * ["Loading", "Signed out", "Signed in"]
1986
- *
1987
- * @example
1988
- * ### Get the current user
1989
- *
1990
- * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/objects/user) object, which contains the current user's data such as their full name. The `isLoaded` and `isSignedIn` properties are used to handle the loading state and to check if the user is signed in, respectively.
1991
- *
1992
- * ```tsx {{ filename: 'src/Example.tsx' }}
1993
- * import { useUser } from '@clerk/react'
1994
- *
1995
- * export default function Example() {
1996
- * const { isSignedIn, user, isLoaded } = useUser()
1997
- *
1998
- * if (!isLoaded) {
1999
- * return <div>Loading...</div>
2000
- * }
2001
- *
2002
- * if (!isSignedIn) {
2003
- * return <div>Sign in to view this page</div>
2004
- * }
2005
- *
2006
- * return <div>Hello {user.firstName}!</div>
2007
- * }
2008
- * ```
2009
- *
2010
- * @example
2011
- * ### Update user data
2012
- *
2013
- * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/objects/user) object, which calls the [`update()`](https://clerk.com/docs/reference/objects/user#update) method to update the current user's information.
2014
- *
2015
- * <Tabs items='React,Next.js'>
2016
- * <Tab>
2017
- *
2018
- * ```tsx {{ filename: 'src/Home.tsx' }}
2019
- * import { useUser } from '@clerk/react'
2020
- *
2021
- * export default function Home() {
2022
- * const { isSignedIn, isLoaded, user } = useUser()
2023
- *
2024
- * if (!isLoaded) {
2025
- * // Handle loading state
2026
- * return null
2027
- * }
2028
- *
2029
- * if (!isSignedIn) return null
2030
- *
2031
- * const updateUser = async () => {
2032
- * await user.update({
2033
- * firstName: 'John',
2034
- * lastName: 'Doe',
2035
- * })
2036
- * }
2037
- *
2038
- * return (
2039
- * <>
2040
- * <button onClick={updateUser}>Update your name</button>
2041
- * <p>user.firstName: {user.firstName}</p>
2042
- * <p>user.lastName: {user.lastName}</p>
2043
- * </>
2044
- * )
2045
- * }
2046
- * ```
2047
- * </Tab>
2048
- * <Tab>
2049
- *
2050
- * ```tsx {{ filename: 'app/page.tsx' }}
2051
- * 'use client';
2052
- *
2053
- * import { useUser } from '@clerk/nextjs';
2054
- *
2055
- * export default function HomePage() {
2056
- * const { isSignedIn, isLoaded, user } = useUser();
2057
- *
2058
- * if (!isLoaded) {
2059
- * // Handle loading state
2060
- * return null;
2061
- * }
2062
- *
2063
- * if (!isSignedIn) return null;
2064
- *
2065
- * const updateUser = async () => {
2066
- * await user.update({
2067
- * firstName: 'John',
2068
- * lastName: 'Doe',
2069
- * });
2070
- * };
2071
- *
2072
- * return (
2073
- * <>
2074
- * <button onClick={updateUser}>Update your name</button>
2075
- * <p>user.firstName: {user.firstName}</p>
2076
- * <p>user.lastName: {user.lastName}</p>
2077
- * </>
2078
- * );
2079
- * }
2080
- * ```
2081
- *
2082
- * </Tab>
2083
- * </Tabs>
2084
- *
2085
- * @example
2086
- * ### Reload user data
2087
- *
2088
- * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/objects/user) object, which calls the [`reload()`](https://clerk.com/docs/reference/objects/user#reload) method to get the latest user's information.
2089
- *
2090
- * <Tabs items='React,Next.js'>
2091
- * <Tab>
2092
- *
2093
- * ```tsx {{ filename: 'src/Home.tsx' }}
2094
- * import { useUser } from '@clerk/react'
2095
- *
2096
- * export default function Home() {
2097
- * const { isSignedIn, isLoaded, user } = useUser();
2098
- *
2099
- * if (!isLoaded) {
2100
- * // Handle loading state
2101
- * return null;
2102
- * }
2103
- *
2104
- * if (!isSignedIn) return null;
2105
- *
2106
- * const updateUser = async () => {
2107
- * // Update data via an API endpoint
2108
- * const updateMetadata = await fetch('/api/updateMetadata', {
2109
- * method: 'POST',
2110
- * body: JSON.stringify({
2111
- * role: 'admin'
2112
- * })
2113
- * });
2114
- *
2115
- * // Check if the update was successful
2116
- * if ((await updateMetadata.json()).message !== 'success') {
2117
- * throw new Error('Error updating');
2118
- * }
2119
- *
2120
- * // If the update was successful, reload the user data
2121
- * await user.reload();
2122
- * };
2123
- *
2124
- * return (
2125
- * <>
2126
- * <button onClick={updateUser}>Update your metadata</button>
2127
- * <p>user role: {user.publicMetadata.role}</p>
2128
- * </>
2129
- * );
2130
- * }
2131
- * ```
2132
- *
2133
- * </Tab>
2134
- * <Tab>
2135
- *
2136
- * ```tsx {{ filename: 'app/page.tsx' }}
2137
- * 'use client';
2138
- *
2139
- * import { useUser } from '@clerk/nextjs';
2140
- *
2141
- * export default function HomePage() {
2142
- * const { isSignedIn, isLoaded, user } = useUser();
2143
- *
2144
- * if (!isLoaded) {
2145
- * // Handle loading state
2146
- * return null;
2147
- * }
2148
- *
2149
- * if (!isSignedIn) return null;
2150
- *
2151
- * const updateUser = async () => {
2152
- * // Update data via an API endpoint
2153
- * const updateMetadata = await fetch('/api/updateMetadata', {
2154
- * method: 'POST',
2155
- * body: JSON.stringify({
2156
- * role: 'admin',
2157
- * }),
2158
- * });
2159
- *
2160
- * // Check if the update was successful
2161
- * if ((await updateMetadata.json()).message !== 'success') {
2162
- * throw new Error('Error updating');
2163
- * }
2164
- *
2165
- * // If the update was successful, reload the user data
2166
- * await user.reload();
2167
- * };
2168
- *
2169
- * return (
2170
- * <>
2171
- * <button onClick={updateUser}>Update your metadata</button>
2172
- * <p>user role: {user.publicMetadata.role}</p>
2173
- * </>
2174
- * );
2175
- * }
2176
- * ```
2177
- *
2178
- * </Tab>
2179
- * </Tabs>
2180
- */
2181
- function useUser() {
2182
- useAssertWrappedByClerkProvider(hookName);
2183
- const user = useUserBase();
2184
- useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName));
2185
- if (user === void 0) return {
2186
- isLoaded: false,
2187
- isSignedIn: void 0,
2188
- user: void 0
2189
- };
2190
- if (user === null) return {
2191
- isLoaded: true,
2192
- isSignedIn: false,
2193
- user: null
2194
- };
2195
- return {
2196
- isLoaded: true,
2197
- isSignedIn: true,
2198
- user
2199
- };
2200
- }
2201
-
2202
- //#endregion
2203
- //#region src/react/hooks/useDeepEqualMemo.ts
2204
- const useDeepEqualMemoize = (value) => {
2205
- const ref = react.default.useRef(value);
2206
- if (!(0, dequal.dequal)(value, ref.current)) ref.current = value;
2207
- return react.default.useMemo(() => ref.current, [ref.current]);
2208
- };
2209
- /**
2210
- * @internal
2211
- */
2212
- const useDeepEqualMemo = (factory, dependencyArray) => {
2213
- return react.default.useMemo(factory, useDeepEqualMemoize(dependencyArray));
2214
- };
2215
- /**
2216
- * @internal
2217
- */
2218
- const isDeeplyEqual = dequal.dequal;
2219
-
2220
- //#endregion
2221
- //#region src/react/hooks/useReverification.ts
2222
- const CLERK_API_REVERIFICATION_ERROR_CODE = "session_reverification_required";
2223
- /**
2224
- *
2225
- */
2226
- async function resolveResult(result) {
2227
- try {
2228
- const r = await result;
2229
- if (r instanceof Response) return r.json();
2230
- return r;
2231
- } catch (e) {
2232
- if (require_error.isClerkAPIResponseError(e) && e.errors.find(({ code }) => code === CLERK_API_REVERIFICATION_ERROR_CODE)) return require_authorization_errors.reverificationError();
2233
- throw e;
2234
- }
2235
- }
2236
- /**
2237
- *
2238
- */
2239
- function createReverificationHandler(params) {
2240
- /**
2241
- *
2242
- */
2243
- function assertReverification(fetcher) {
2244
- return (async (...args) => {
2245
- let result = await resolveResult(fetcher(...args));
2246
- if (require_authorization_errors.isReverificationHint(result)) {
2247
- /**
2248
- * Create a promise
2249
- */
2250
- const resolvers = require_createDeferredPromise.createDeferredPromise();
2251
- const isValidMetadata = require_authorization.validateReverificationConfig(result.clerk_error.metadata?.reverification);
2252
- const level = isValidMetadata ? isValidMetadata().level : void 0;
2253
- const cancel = () => {
2254
- resolvers.reject(new require_clerkRuntimeError.ClerkRuntimeError("User cancelled attempted verification", { code: "reverification_cancelled" }));
2255
- };
2256
- const complete = () => {
2257
- resolvers.resolve(true);
2258
- };
2259
- if (params.onNeedsReverification === void 0)
2260
- /**
2261
- * On success resolve the pending promise
2262
- * On cancel reject the pending promise
2263
- */
2264
- params.openUIComponent?.({
2265
- level,
2266
- afterVerification: complete,
2267
- afterVerificationCancelled: cancel
2268
- });
2269
- else params.onNeedsReverification({
2270
- cancel,
2271
- complete,
2272
- level
2273
- });
2274
- /**
2275
- * Wait until the promise from above have been resolved or rejected
2276
- */
2277
- await resolvers.promise;
2278
- /**
2279
- * After the promise resolved successfully try the original request one more time
2280
- */
2281
- result = await resolveResult(fetcher(...args));
2282
- }
2283
- return result;
2284
- });
2285
- }
2286
- return assertReverification;
2287
- }
2288
- /**
2289
- * > [!WARNING]
2290
- * >
2291
- * > Depending on the SDK you're using, this feature requires `@clerk/nextjs@6.12.7` or later, `@clerk/react@5.25.1` or later, and `@clerk/clerk-js@5.57.1` or later.
2292
- *
2293
- * The `useReverification()` hook is used to handle a session's reverification flow. If a request requires reverification, a modal will display, prompting the user to verify their credentials. Upon successful verification, the original request will automatically retry.
2294
- *
2295
- * @function
2296
- *
2297
- * @returns The `useReverification()` hook returns an array with the "enhanced" fetcher.
2298
- *
2299
- * @example
2300
- * ### Handle cancellation of the reverification process
2301
- *
2302
- * The following example demonstrates how to handle scenarios where a user cancels the reverification flow, such as closing the modal, which might result in `myData` being `null`.
2303
- *
2304
- * In the following example, `myFetcher` would be a function in your backend that fetches data from the route that requires reverification. See the [guide on how to require reverification](https://clerk.com/docs/guides/secure/reverification) for more information.
2305
- *
2306
- * ```tsx {{ filename: 'src/components/MyButton.tsx' }}
2307
- * import { useReverification } from '@clerk/react'
2308
- * import { isReverificationCancelledError } from '@clerk/react/error'
2309
- *
2310
- * type MyData = {
2311
- * balance: number
2312
- * }
2313
- *
2314
- * export function MyButton() {
2315
- * const fetchMyData = () => fetch('/api/balance').then(res=> res.json() as Promise<MyData>)
2316
- * const enhancedFetcher = useReverification(fetchMyData);
2317
- *
2318
- * const handleClick = async () => {
2319
- * try {
2320
- * const myData = await enhancedFetcher()
2321
- * // ^ is types as `MyData`
2322
- * } catch (e) {
2323
- * // Handle error returned from the fetcher here
2324
- *
2325
- * // You can also handle cancellation with the following
2326
- * if (isReverificationCancelledError(err)) {
2327
- * // Handle the cancellation error here
2328
- * }
2329
- * }
2330
- * }
2331
- *
2332
- * return <button onClick={handleClick}>Update User</button>
2333
- * }
2334
- * ```
2335
- */
2336
- const useReverification = (fetcher, options) => {
2337
- const { __internal_openReverification, telemetry } = useClerk();
2338
- const fetcherRef = (0, react.useRef)(fetcher);
2339
- const optionsRef = (0, react.useRef)(options);
2340
- telemetry?.record(require_telemetry.eventMethodCalled("useReverification", { onNeedsReverification: Boolean(options?.onNeedsReverification) }));
2341
- useSafeLayoutEffect(() => {
2342
- fetcherRef.current = fetcher;
2343
- optionsRef.current = options;
2344
- });
2345
- return (0, react.useCallback)((...args) => {
2346
- return createReverificationHandler({
2347
- openUIComponent: __internal_openReverification,
2348
- telemetry,
2349
- ...optionsRef.current
2350
- })(fetcherRef.current)(...args);
2351
- }, [__internal_openReverification, telemetry]);
2352
- };
2353
-
2354
- //#endregion
2355
- //#region src/react/hooks/useBillingIsEnabled.ts
2356
- /**
2357
- * @internal
2358
- */
2359
- function useBillingIsEnabled(params) {
2360
- const clerk = useClerkInstanceContext();
2361
- const enabledFromParam = params?.enabled ?? true;
2362
- const environment = clerk.__internal_environment;
2363
- const user = useUserBase();
2364
- const organization = useOrganizationBase();
2365
- const userBillingEnabled = environment?.commerceSettings.billing.user.enabled;
2366
- const orgBillingEnabled = environment?.commerceSettings.billing.organization.enabled;
2367
- const billingEnabled = params?.for === "organization" ? orgBillingEnabled : params?.for === "user" ? userBillingEnabled : userBillingEnabled || orgBillingEnabled;
2368
- const isOrganization = params?.for === "organization";
2369
- const requireUserAndOrganizationWhenAuthenticated = params?.authenticated ?? true ? (isOrganization ? Boolean(organization?.id) : true) && Boolean(user?.id) : true;
2370
- return billingEnabled && enabledFromParam && clerk.loaded && requireUserAndOrganizationWhenAuthenticated;
2371
- }
2372
-
2373
- //#endregion
2374
- //#region src/react/hooks/createBillingPaginatedHook.tsx
2375
- /**
2376
- * A hook factory that creates paginated data fetching hooks for commerce-related resources.
2377
- * It provides a standardized way to create hooks that can fetch either user or Organization resources
2378
- * with built-in pagination support.
2379
- *
2380
- * The generated hooks handle:
2381
- * - Clerk authentication context
2382
- * - Resource-specific data fetching
2383
- * - Pagination (both traditional and infinite scroll)
2384
- * - Telemetry tracking
2385
- * - Type safety for the specific resource.
2386
- *
2387
- * @internal
2388
- */
2389
- function createBillingPaginatedHook({ hookName, resourceType, useFetcher, options }) {
2390
- return function useBillingHook(params) {
2391
- const { for: _for, enabled: externalEnabled, ...paginationParams } = params || {};
2392
- const safeFor = _for || "user";
2393
- useAssertWrappedByClerkProvider(hookName);
2394
- const fetchFn = useFetcher(safeFor);
2395
- const safeValues = useWithSafeValues(paginationParams, {
2396
- initialPage: 1,
2397
- pageSize: 10,
2398
- keepPreviousData: false,
2399
- infinite: false,
2400
- __experimental_mode: void 0
2401
- });
2402
- const clerk = useClerkInstanceContext();
2403
- const user = useUserBase();
2404
- const organization = useOrganizationBase();
2405
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName));
2406
- const isForOrganization = safeFor === "organization";
2407
- const billingEnabled = useBillingIsEnabled({
2408
- for: safeFor,
2409
- enabled: externalEnabled,
2410
- authenticated: !options?.unauthenticated
2411
- });
2412
- const hookParams = typeof paginationParams === "undefined" ? void 0 : {
2413
- initialPage: safeValues.initialPage,
2414
- pageSize: safeValues.pageSize,
2415
- ...options?.unauthenticated ? {} : isForOrganization ? { orgId: organization?.id } : {}
2416
- };
2417
- const isEnabled = !!hookParams && clerk.loaded && !!billingEnabled;
2418
- return usePagesOrInfinite({
2419
- fetcher: fetchFn,
2420
- config: {
2421
- keepPreviousData: safeValues.keepPreviousData,
2422
- infinite: safeValues.infinite,
2423
- enabled: isEnabled,
2424
- ...options?.unauthenticated ? {} : { isSignedIn: user !== null },
2425
- __experimental_mode: safeValues.__experimental_mode,
2426
- initialPage: safeValues.initialPage,
2427
- pageSize: safeValues.pageSize
2428
- },
2429
- keys: createCacheKeys({
2430
- stablePrefix: resourceType,
2431
- authenticated: !options?.unauthenticated,
2432
- tracked: options?.unauthenticated ? { for: safeFor } : {
2433
- userId: user?.id,
2434
- ...isForOrganization ? { orgId: organization?.id } : {}
2435
- },
2436
- untracked: { args: hookParams }
2437
- })
2438
- });
2439
- };
2440
- }
2441
-
2442
- //#endregion
2443
- //#region src/react/hooks/useStatements.tsx
2444
- /**
2445
- * @internal
2446
- */
2447
- const useStatements = createBillingPaginatedHook({
2448
- hookName: "useStatements",
2449
- resourceType: STABLE_KEYS.STATEMENTS_KEY,
2450
- useFetcher: () => {
2451
- const clerk = useClerkInstanceContext();
2452
- if (clerk.loaded) return clerk.billing.getStatements;
2453
- }
2454
- });
2455
-
2456
- //#endregion
2457
- //#region src/react/hooks/usePaymentAttempts.tsx
2458
- /**
2459
- * @internal
2460
- */
2461
- const usePaymentAttempts = createBillingPaginatedHook({
2462
- hookName: "usePaymentAttempts",
2463
- resourceType: STABLE_KEYS.PAYMENT_ATTEMPTS_KEY,
2464
- useFetcher: () => {
2465
- const clerk = useClerkInstanceContext();
2466
- if (clerk.loaded) return clerk.billing.getPaymentAttempts;
2467
- }
2468
- });
2469
-
2470
- //#endregion
2471
- //#region src/react/hooks/usePaymentMethods.tsx
2472
- /**
2473
- * @internal
2474
- */
2475
- const usePaymentMethods = createBillingPaginatedHook({
2476
- hookName: "usePaymentMethods",
2477
- resourceType: STABLE_KEYS.PAYMENT_METHODS_KEY,
2478
- useFetcher: (resource) => {
2479
- const organization = useOrganizationBase();
2480
- const user = useUserBase();
2481
- if (resource === "organization") return organization?.getPaymentMethods;
2482
- return user?.getPaymentMethods;
2483
- }
2484
- });
2485
-
2486
- //#endregion
2487
- //#region src/react/hooks/usePlans.tsx
2488
- /**
2489
- * @internal
2490
- */
2491
- const usePlans = createBillingPaginatedHook({
2492
- hookName: "usePlans",
2493
- resourceType: STABLE_KEYS.PLANS_KEY,
2494
- useFetcher: (_for) => {
2495
- const clerk = useClerkInstanceContext();
2496
- if (!clerk.loaded) return;
2497
- return (params) => clerk.billing.getPlans({
2498
- ...params,
2499
- for: _for
2500
- });
2501
- },
2502
- options: { unauthenticated: true }
2503
- });
2504
-
2505
- //#endregion
2506
- //#region src/react/hooks/useSubscription.shared.ts
2507
- function useSubscriptionCacheKeys(params) {
2508
- const { userId, orgId, for: forType } = params;
2509
- return (0, react.useMemo)(() => {
2510
- const safeOrgId = forType === "organization" ? orgId : void 0;
2511
- return createCacheKeys({
2512
- stablePrefix: STABLE_KEYS.SUBSCRIPTION_KEY,
2513
- authenticated: true,
2514
- tracked: {
2515
- userId,
2516
- orgId: safeOrgId
2517
- },
2518
- untracked: { args: { orgId: safeOrgId } }
2519
- });
2520
- }, [
2521
- userId,
2522
- orgId,
2523
- forType
2524
- ]);
2525
- }
2526
-
2527
- //#endregion
2528
- //#region src/react/hooks/useSubscription.tsx
2529
- const HOOK_NAME$2 = "useSubscription";
2530
- /**
2531
- * @internal
2532
- */
2533
- function useSubscription(params) {
2534
- useAssertWrappedByClerkProvider(HOOK_NAME$2);
2535
- const clerk = useClerkInstanceContext();
2536
- const user = useUserBase();
2537
- const organization = useOrganizationBase();
2538
- const billingEnabled = useBillingIsEnabled(params);
2539
- const recordedRef = (0, react.useRef)(false);
2540
- (0, react.useEffect)(() => {
2541
- if (!recordedRef.current && clerk?.telemetry) {
2542
- clerk.telemetry.record(require_telemetry.eventMethodCalled(HOOK_NAME$2));
2543
- recordedRef.current = true;
2544
- }
2545
- }, [clerk]);
2546
- const keepPreviousData = params?.keepPreviousData ?? false;
2547
- const [queryClient] = useClerkQueryClient();
2548
- const { queryKey, invalidationKey, stableKey, authenticated } = useSubscriptionCacheKeys({
2549
- userId: user?.id,
2550
- orgId: organization?.id,
2551
- for: params?.for
2552
- });
2553
- const queriesEnabled = Boolean(user?.id && billingEnabled);
2554
- useClearQueriesOnSignOut({
2555
- isSignedOut: user === null,
2556
- authenticated,
2557
- stableKeys: stableKey
2558
- });
2559
- const query = useClerkQuery({
2560
- queryKey,
2561
- queryFn: ({ queryKey }) => {
2562
- const obj = queryKey[3];
2563
- return clerk.billing.getSubscription(obj.args);
2564
- },
2565
- staleTime: 1e3 * 60,
2566
- enabled: queriesEnabled,
2567
- placeholderData: defineKeepPreviousDataFn(keepPreviousData && queriesEnabled)
2568
- });
2569
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: invalidationKey }), [queryClient, invalidationKey]);
2570
- return {
2571
- data: query.data,
2572
- error: query.error ?? void 0,
2573
- isLoading: query.isLoading,
2574
- isFetching: query.isFetching,
2575
- revalidate
2576
- };
2577
- }
2578
-
2579
- //#endregion
2580
- //#region src/react/hooks/useCheckout.ts
2581
- /**
2582
- * @function
2583
- *
2584
- * @param [options] - An object containing the configuration for the checkout flow.
2585
- *
2586
- * **Required** if the hook is used without a `<CheckoutProvider />` wrapping the component tree.
2587
- */
2588
- const useCheckout = (options) => {
2589
- const contextOptions = useCheckoutContext();
2590
- const { for: forOrganization, planId, planPeriod, seatsQuantity, priceId } = options || contextOptions;
2591
- const organization = useOrganizationBase();
2592
- const { isLoaded, user } = useUser();
2593
- const clerk = useClerkInstanceContext();
2594
- if (user === null && isLoaded) throw new Error("Clerk: Ensure that `useCheckout` is inside a component wrapped with `<Show when=\"signed-in\" />`.");
2595
- if (isLoaded && forOrganization === "organization" && organization === null) throw new Error("Clerk: Ensure your flow checks for an active organization. Retrieve `orgId` from `useAuth()` and confirm it is defined. For SSR, see: https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object");
2596
- const signal = (0, react.useCallback)(() => {
2597
- return clerk.__experimental_checkout({
2598
- planId,
2599
- planPeriod,
2600
- for: forOrganization,
2601
- seatsQuantity,
2602
- priceId
2603
- });
2604
- }, [
2605
- user?.id,
2606
- organization?.id,
2607
- planId,
2608
- planPeriod,
2609
- forOrganization,
2610
- seatsQuantity,
2611
- priceId
2612
- ]);
2613
- const subscribe = (0, react.useCallback)((callback) => {
2614
- if (!clerk.loaded) return () => {};
2615
- return clerk.__internal_state.__internal_effect(() => {
2616
- signal();
2617
- callback();
2618
- });
2619
- }, [
2620
- signal,
2621
- clerk.loaded,
2622
- clerk.__internal_state
2623
- ]);
2624
- const getSnapshot = (0, react.useCallback)(() => {
2625
- return signal();
2626
- }, [signal]);
2627
- return (0, react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
2628
- };
2629
-
2630
- //#endregion
2631
- //#region src/react/hooks/useCreditBalance.tsx
2632
- const HOOK_NAME$1 = "useCreditBalance";
2633
- /**
2634
- * @internal
2635
- */
2636
- function __internal_useCreditBalanceQuery(params) {
2637
- useAssertWrappedByClerkProvider(HOOK_NAME$1);
2638
- const clerk = useClerkInstanceContext();
2639
- const user = useUserBase();
2640
- const organization = useOrganizationBase();
2641
- const billingEnabled = useBillingIsEnabled(params);
2642
- const recordedRef = (0, react.useRef)(false);
2643
- (0, react.useEffect)(() => {
2644
- if (!recordedRef.current && clerk?.telemetry) {
2645
- clerk.telemetry.record(require_telemetry.eventMethodCalled(HOOK_NAME$1));
2646
- recordedRef.current = true;
2647
- }
2648
- }, [clerk]);
2649
- const keepPreviousData = params?.keepPreviousData ?? false;
2650
- const [queryClient] = useClerkQueryClient();
2651
- const { queryKey, invalidationKey, stableKey, authenticated } = (0, react.useMemo)(() => {
2652
- const safeOrgId = params?.for === "organization" ? organization?.id : void 0;
2653
- return createCacheKeys({
2654
- stablePrefix: STABLE_KEYS.CREDIT_BALANCE_KEY,
2655
- authenticated: true,
2656
- tracked: {
2657
- userId: user?.id,
2658
- orgId: safeOrgId
2659
- },
2660
- untracked: { args: { orgId: safeOrgId } }
2661
- });
2662
- }, [
2663
- user?.id,
2664
- organization?.id,
2665
- params?.for
2666
- ]);
2667
- const queriesEnabled = Boolean(user?.id && billingEnabled && (params?.enabled ?? true));
2668
- useClearQueriesOnSignOut({
2669
- isSignedOut: user === null,
2670
- authenticated,
2671
- stableKeys: stableKey
2672
- });
2673
- const query = useClerkQuery({
2674
- queryKey,
2675
- queryFn: ({ queryKey }) => {
2676
- const obj = queryKey[3];
2677
- return clerk.billing.getCreditBalance(obj.args);
2678
- },
2679
- staleTime: 1e3 * 60,
2680
- enabled: queriesEnabled,
2681
- placeholderData: defineKeepPreviousDataFn(keepPreviousData && queriesEnabled)
2682
- });
2683
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: invalidationKey }), [queryClient, invalidationKey]);
2684
- return {
2685
- data: query.data,
2686
- error: query.error ?? void 0,
2687
- isLoading: query.isLoading,
2688
- isFetching: query.isFetching,
2689
- revalidate
2690
- };
2691
- }
2692
-
2693
- //#endregion
2694
- //#region src/react/hooks/useCreditHistory.tsx
2695
- const HOOK_NAME = "useCreditHistory";
2696
- /**
2697
- * @internal
2698
- */
2699
- function __internal_useCreditHistoryQuery(params) {
2700
- useAssertWrappedByClerkProvider(HOOK_NAME);
2701
- const clerk = useClerkInstanceContext();
2702
- const user = useUserBase();
2703
- const organization = useOrganizationBase();
2704
- const billingEnabled = useBillingIsEnabled(params);
2705
- const recordedRef = (0, react.useRef)(false);
2706
- (0, react.useEffect)(() => {
2707
- if (!recordedRef.current && clerk?.telemetry) {
2708
- clerk.telemetry.record(require_telemetry.eventMethodCalled(HOOK_NAME));
2709
- recordedRef.current = true;
2710
- }
2711
- }, [clerk]);
2712
- const [queryClient] = useClerkQueryClient();
2713
- const { queryKey, invalidationKey, stableKey, authenticated } = (0, react.useMemo)(() => {
2714
- const safeOrgId = params?.for === "organization" ? organization?.id : void 0;
2715
- return createCacheKeys({
2716
- stablePrefix: INTERNAL_STABLE_KEYS.CREDIT_HISTORY_KEY,
2717
- authenticated: true,
2718
- tracked: {
2719
- userId: user?.id,
2720
- orgId: safeOrgId
2721
- },
2722
- untracked: { args: { orgId: safeOrgId } }
2723
- });
2724
- }, [
2725
- user?.id,
2726
- organization?.id,
2727
- params?.for
2728
- ]);
2729
- const queriesEnabled = Boolean(user?.id && billingEnabled && (params?.enabled ?? true));
2730
- useClearQueriesOnSignOut({
2731
- isSignedOut: user === null,
2732
- authenticated,
2733
- stableKeys: stableKey
2734
- });
2735
- const query = useClerkQuery({
2736
- queryKey,
2737
- queryFn: ({ queryKey }) => {
2738
- const obj = queryKey[3];
2739
- return clerk.billing.getCreditHistory(obj.args);
2740
- },
2741
- staleTime: 1e3 * 60,
2742
- enabled: queriesEnabled
2743
- });
2744
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: invalidationKey }), [queryClient, invalidationKey]);
2745
- return {
2746
- data: query.data,
2747
- error: query.error ?? void 0,
2748
- isLoading: query.isLoading,
2749
- isFetching: query.isFetching,
2750
- revalidate
2751
- };
2752
- }
2753
-
2754
- //#endregion
2755
- //#region src/react/hooks/useStatementQuery.shared.ts
2756
- function useStatementQueryCacheKeys(params) {
2757
- const { statementId, userId, orgId, for: forType } = params;
2758
- return (0, react.useMemo)(() => {
2759
- return createCacheKeys({
2760
- stablePrefix: INTERNAL_STABLE_KEYS.BILLING_STATEMENTS_KEY,
2761
- authenticated: true,
2762
- tracked: {
2763
- statementId,
2764
- forType,
2765
- userId,
2766
- orgId
2767
- },
2768
- untracked: { args: {
2769
- id: statementId ?? void 0,
2770
- orgId: orgId ?? void 0
2771
- } }
2772
- });
2773
- }, [
2774
- statementId,
2775
- forType,
2776
- userId,
2777
- orgId
2778
- ]);
2779
- }
2780
-
2781
- //#endregion
2782
- //#region src/react/hooks/useStatementQuery.tsx
2783
- /**
2784
- * @internal
2785
- */
2786
- function useStatementQuery(params = {}) {
2787
- const { statementId = null, keepPreviousData = false, for: forType = "user" } = params;
2788
- const clerk = useClerkInstanceContext();
2789
- const user = useUserBase();
2790
- const organization = useOrganizationBase();
2791
- const organizationId = forType === "organization" ? organization?.id ?? null : null;
2792
- const { queryKey, stableKey, authenticated } = useStatementQueryCacheKeys({
2793
- statementId,
2794
- userId: user?.id ?? null,
2795
- orgId: organizationId,
2796
- for: forType
2797
- });
2798
- const billingEnabled = useBillingIsEnabled(params);
2799
- const queryEnabled = Boolean(statementId) && billingEnabled;
2800
- useClearQueriesOnSignOut({
2801
- isSignedOut: user === null,
2802
- authenticated,
2803
- stableKeys: stableKey
2804
- });
2805
- const query = useClerkQuery({
2806
- queryKey,
2807
- queryFn: () => {
2808
- if (!statementId) throw new Error("statementId is required to fetch a statement");
2809
- return clerk.billing.getStatement({
2810
- id: statementId,
2811
- orgId: organizationId ?? void 0
2812
- });
2813
- },
2814
- enabled: queryEnabled,
2815
- placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2816
- staleTime: 1e3 * 60
2817
- });
2818
- return {
2819
- data: query.data,
2820
- error: query.error ?? null,
2821
- isLoading: query.isLoading,
2822
- isFetching: query.isFetching
2823
- };
2824
- }
2825
-
2826
- //#endregion
2827
- //#region src/react/hooks/usePlanDetailsQuery.shared.ts
2828
- function usePlanDetailsQueryCacheKeys(params) {
2829
- const { planId } = params;
2830
- return (0, react.useMemo)(() => {
2831
- return createCacheKeys({
2832
- stablePrefix: INTERNAL_STABLE_KEYS.BILLING_PLANS_KEY,
2833
- authenticated: false,
2834
- tracked: { planId: planId ?? null },
2835
- untracked: { args: { id: planId ?? void 0 } }
2836
- });
2837
- }, [planId]);
2838
- }
2839
-
2840
- //#endregion
2841
- //#region src/react/hooks/usePlanDetailsQuery.tsx
2842
- /**
2843
- * @internal
2844
- */
2845
- function __internal_usePlanDetailsQuery(params = {}) {
2846
- const { planId, initialPlan = null, keepPreviousData = true } = params;
2847
- const clerk = useClerkInstanceContext();
2848
- const targetPlanId = planId ?? initialPlan?.id ?? null;
2849
- const { queryKey } = usePlanDetailsQueryCacheKeys({ planId: targetPlanId });
2850
- const billingEnabled = useBillingIsEnabled({ authenticated: false });
2851
- const query = useClerkQuery({
2852
- queryKey,
2853
- queryFn: () => {
2854
- if (!targetPlanId) throw new Error("planId is required to fetch plan details");
2855
- return clerk.billing.getPlan({ id: targetPlanId });
2856
- },
2857
- enabled: Boolean(targetPlanId) && billingEnabled,
2858
- initialData: initialPlan ?? void 0,
2859
- placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2860
- initialDataUpdatedAt: 0
2861
- });
2862
- return {
2863
- data: query.data,
2864
- error: query.error ?? null,
2865
- isLoading: query.isLoading,
2866
- isFetching: query.isFetching
2867
- };
2868
- }
2869
-
2870
- //#endregion
2871
- //#region src/react/hooks/usePaymentAttemptQuery.shared.ts
2872
- function usePaymentAttemptQueryCacheKeys(params) {
2873
- const { paymentAttemptId, userId, orgId, for: forType } = params;
2874
- return (0, react.useMemo)(() => {
2875
- return createCacheKeys({
2876
- stablePrefix: INTERNAL_STABLE_KEYS.PAYMENT_ATTEMPT_KEY,
2877
- authenticated: true,
2878
- tracked: {
2879
- paymentAttemptId,
2880
- forType,
2881
- userId,
2882
- orgId
2883
- },
2884
- untracked: { args: {
2885
- id: paymentAttemptId ?? void 0,
2886
- orgId: orgId ?? void 0
2887
- } }
2888
- });
2889
- }, [
2890
- paymentAttemptId,
2891
- forType,
2892
- userId,
2893
- orgId
2894
- ]);
2895
- }
2896
-
2897
- //#endregion
2898
- //#region src/react/hooks/usePaymentAttemptQuery.tsx
2899
- /**
2900
- * @internal
2901
- */
2902
- function usePaymentAttemptQuery(params) {
2903
- const { paymentAttemptId, keepPreviousData = false, for: forType = "user" } = params;
2904
- const clerk = useClerkInstanceContext();
2905
- const user = useUserBase();
2906
- const organization = useOrganizationBase();
2907
- const organizationId = forType === "organization" ? organization?.id ?? null : null;
2908
- const { queryKey, stableKey, authenticated } = usePaymentAttemptQueryCacheKeys({
2909
- paymentAttemptId,
2910
- userId: user?.id ?? null,
2911
- orgId: organizationId,
2912
- for: forType
2913
- });
2914
- const billingEnabled = useBillingIsEnabled(params);
2915
- const queryEnabled = Boolean(paymentAttemptId) && billingEnabled;
2916
- useClearQueriesOnSignOut({
2917
- isSignedOut: user === null,
2918
- authenticated,
2919
- stableKeys: stableKey
2920
- });
2921
- const query = useClerkQuery({
2922
- queryKey,
2923
- queryFn: ({ queryKey }) => {
2924
- const args = queryKey[3].args;
2925
- return clerk.billing.getPaymentAttempt(args);
2926
- },
2927
- enabled: queryEnabled,
2928
- placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2929
- staleTime: 1e3 * 60
2930
- });
2931
- return {
2932
- data: query.data,
2933
- error: query.error ?? null,
2934
- isLoading: query.isLoading,
2935
- isFetching: query.isFetching
2936
- };
2937
- }
2938
-
2939
- //#endregion
2940
- //#region src/react/hooks/useUserEnterpriseConnections.shared.ts
2941
- /**
2942
- * @internal
2943
- */
2944
- function useUserEnterpriseConnectionsCacheKeys(params) {
2945
- const { userId, withOrganizationAccountLinking = false } = params;
2946
- return (0, react.useMemo)(() => {
2947
- return createCacheKeys({
2948
- stablePrefix: INTERNAL_STABLE_KEYS.USER_ENTERPRISE_CONNECTIONS_KEY,
2949
- authenticated: Boolean(userId),
2950
- tracked: {
2951
- userId: userId ?? null,
2952
- withOrganizationAccountLinking
2953
- },
2954
- untracked: { args: {} }
2955
- });
2956
- }, [userId, withOrganizationAccountLinking]);
2957
- }
2958
-
2959
- //#endregion
2960
- //#region src/react/hooks/useUserEnterpriseConnections.tsx
2961
- /**
2962
- * Enterprise connections for the signed-in user
2963
- *
2964
- * @internal
2965
- */
2966
- function useUserEnterpriseConnections(params = {}) {
2967
- const { keepPreviousData = true, enabled = true, withOrganizationAccountLinking = false } = params;
2968
- const clerk = useClerkInstanceContext();
2969
- const user = useUserBase();
2970
- const [queryClient] = useClerkQueryClient();
2971
- const { queryKey, stableKey, authenticated } = useUserEnterpriseConnectionsCacheKeys({
2972
- userId: user?.id ?? null,
2973
- withOrganizationAccountLinking
2974
- });
2975
- const queryEnabled = enabled && clerk.loaded && Boolean(user);
2976
- useClearQueriesOnSignOut({
2977
- isSignedOut: user === null,
2978
- authenticated,
2979
- stableKeys: stableKey
2980
- });
2981
- const query = useClerkQuery({
2982
- queryKey,
2983
- queryFn: () => user?.getEnterpriseConnections({ withOrganizationAccountLinking }),
2984
- enabled: queryEnabled,
2985
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
2986
- });
2987
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: [stableKey] }), [queryClient, stableKey]);
2988
- return {
2989
- data: query.data,
2990
- error: query.error ?? null,
2991
- isLoading: query.isLoading,
2992
- isFetching: query.isFetching,
2993
- revalidate
2994
- };
2995
- }
2996
-
2997
- //#endregion
2998
- //#region src/react/hooks/useOrganizationEnterpriseConnections.shared.ts
2999
- /**
3000
- * @internal
3001
- */
3002
- function useOrganizationEnterpriseConnectionsCacheKeys(params) {
3003
- const { organizationId, withOrganizationAccountLinking = false } = params;
3004
- return (0, react.useMemo)(() => {
3005
- return createCacheKeys({
3006
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_ENTERPRISE_CONNECTIONS_KEY,
3007
- authenticated: Boolean(organizationId),
3008
- tracked: {
3009
- organizationId: organizationId ?? null,
3010
- withOrganizationAccountLinking
3011
- },
3012
- untracked: { args: {} }
3013
- });
3014
- }, [organizationId, withOrganizationAccountLinking]);
3015
- }
3016
-
3017
- //#endregion
3018
- //#region src/react/hooks/useOrganizationEnterpriseConnections.tsx
3019
- /**
3020
- * Enterprise connections for the active organization
3021
- *
3022
- * @internal
3023
- */
3024
- function useOrganizationEnterpriseConnections(params = {}) {
3025
- const { keepPreviousData = true, enabled = true, withOrganizationAccountLinking = false } = params;
3026
- const clerk = useClerkInstanceContext();
3027
- const organization = useOrganizationBase();
3028
- const [queryClient] = useClerkQueryClient();
3029
- const { queryKey, stableKey, authenticated } = useOrganizationEnterpriseConnectionsCacheKeys({
3030
- organizationId: organization?.id ?? null,
3031
- withOrganizationAccountLinking
3032
- });
3033
- const queryEnabled = enabled && clerk.loaded && Boolean(organization);
3034
- useClearQueriesOnSignOut({
3035
- isSignedOut: organization === null,
3036
- authenticated,
3037
- stableKeys: stableKey
3038
- });
3039
- const query = useClerkQuery({
3040
- queryKey,
3041
- queryFn: () => organization?.getEnterpriseConnections({ withOrganizationAccountLinking }),
3042
- enabled: queryEnabled,
3043
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
3044
- });
3045
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: [stableKey] }), [queryClient, stableKey]);
3046
- const createEnterpriseConnection = (0, react.useCallback)(async (createParams) => {
3047
- const created = await organization?.createEnterpriseConnection(createParams);
3048
- await revalidate();
3049
- return created;
3050
- }, [organization, revalidate]);
3051
- const updateEnterpriseConnection = (0, react.useCallback)(async (enterpriseConnectionId, updateParams) => {
3052
- const updated = await organization?.updateEnterpriseConnection(enterpriseConnectionId, updateParams);
3053
- await revalidate();
3054
- return updated;
3055
- }, [organization, revalidate]);
3056
- const deleteEnterpriseConnection = (0, react.useCallback)(async (enterpriseConnectionId) => {
3057
- const deleted = await organization?.deleteEnterpriseConnection(enterpriseConnectionId);
3058
- await revalidate();
3059
- return deleted;
3060
- }, [organization, revalidate]);
3061
- return {
3062
- data: query.data,
3063
- error: query.error ?? null,
3064
- isLoading: query.isLoading,
3065
- isFetching: query.isFetching,
3066
- createEnterpriseConnection,
3067
- updateEnterpriseConnection,
3068
- deleteEnterpriseConnection,
3069
- revalidate
3070
- };
3071
- }
3072
-
3073
- //#endregion
3074
- //#region src/react/hooks/useOrganizationDomains.shared.ts
3075
- /**
3076
- * @internal
3077
- */
3078
- function useOrganizationDomainsCacheKeys(params) {
3079
- const { organizationId, enrollmentMode } = params;
3080
- return (0, react.useMemo)(() => {
3081
- return createCacheKeys({
3082
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_DOMAINS_KEY,
3083
- authenticated: Boolean(organizationId),
3084
- tracked: {
3085
- organizationId: organizationId ?? null,
3086
- enrollmentMode: enrollmentMode ?? null
3087
- },
3088
- untracked: { args: {} }
3089
- });
3090
- }, [organizationId, enrollmentMode]);
3091
- }
3092
-
3093
- //#endregion
3094
- //#region src/react/hooks/useOrganizationDomains.tsx
3095
- const OWNERSHIP_VERIFICATION_POLL_INTERVAL_MS = 1e4;
3096
- /**
3097
- * Domains for the active organization.
3098
- *
3099
- * @internal
3100
- */
3101
- function useOrganizationDomains(params = {}) {
3102
- const { keepPreviousData = true, enabled = true, enrollmentMode, onOwnershipVerified } = params;
3103
- const clerk = useClerkInstanceContext();
3104
- const organization = useOrganizationBase();
3105
- const [queryClient] = useClerkQueryClient();
3106
- const onOwnershipVerifiedRef = (0, react.useRef)(onOwnershipVerified);
3107
- onOwnershipVerifiedRef.current = onOwnershipVerified;
3108
- const { queryKey, stableKey, authenticated } = useOrganizationDomainsCacheKeys({
3109
- organizationId: organization?.id ?? null,
3110
- enrollmentMode
3111
- });
3112
- const queryEnabled = enabled && clerk.loaded && Boolean(organization);
3113
- useClearQueriesOnSignOut({
3114
- isSignedOut: organization === null,
3115
- authenticated,
3116
- stableKeys: stableKey
3117
- });
3118
- const fetchParams = enrollmentMode ? { enrollmentMode } : void 0;
3119
- const query = useClerkQuery({
3120
- queryKey,
3121
- queryFn: () => organization?.getDomains(fetchParams),
3122
- enabled: queryEnabled,
3123
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
3124
- });
3125
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: [stableKey] }), [queryClient, stableKey]);
3126
- const createDomain = (0, react.useCallback)(async (name) => {
3127
- let created = await organization?.createDomain(name, enrollmentMode ? { enrollmentMode } : void 0);
3128
- if (created && enrollmentMode === "enterprise_sso") created = (await organization?.prepareOwnershipVerification([created.id]))?.data[0] ?? created;
3129
- await revalidate();
3130
- return created;
3131
- }, [
3132
- organization,
3133
- revalidate,
3134
- enrollmentMode
3135
- ]);
3136
- const prepareOwnershipVerification = (0, react.useCallback)(async (domains) => {
3137
- const prepared = await organization?.prepareOwnershipVerification(domains.map((domain) => domain.id));
3138
- await revalidate();
3139
- return prepared;
3140
- }, [organization, revalidate]);
3141
- const attemptOwnershipVerification = (0, react.useCallback)(async (domains) => {
3142
- const attempted = await organization?.attemptOwnershipVerification(domains.map((domain) => domain.id));
3143
- await revalidate();
3144
- return attempted;
3145
- }, [organization, revalidate]);
3146
- const response = query.data;
3147
- const unverifiedOwnershipKey = (0, react.useMemo)(() => (response?.data ?? []).filter((domain) => domain.ownershipVerification?.status === "unverified").map((domain) => domain.id), [response?.data]).join(",");
3148
- (0, react.useEffect)(() => {
3149
- if (!queryEnabled || !organization || !unverifiedOwnershipKey) return;
3150
- let cancelled = false;
3151
- let timeoutId;
3152
- const scheduleNext = () => {
3153
- timeoutId = setTimeout(() => void runAttempt(), OWNERSHIP_VERIFICATION_POLL_INTERVAL_MS);
3154
- };
3155
- const domainIds = unverifiedOwnershipKey.split(",");
3156
- const runAttempt = async () => {
3157
- const result = await organization.attemptOwnershipVerification(domainIds).catch((error) => {
3158
- require_logger.logger.warnOnce(`Clerk: failed to attempt organization domain ownership verification: ${error}`);
3159
- });
3160
- if (cancelled) return;
3161
- await revalidate();
3162
- if (cancelled) return;
3163
- const verifiedDomains = result?.data.filter((domain) => domain.ownershipVerification?.status === "verified") ?? [];
3164
- if (verifiedDomains.length) await onOwnershipVerifiedRef.current?.(verifiedDomains);
3165
- if (cancelled) return;
3166
- if (!!result?.data.length && result.data.every((domain) => domain.ownershipVerification?.status === "verified")) return;
3167
- scheduleNext();
3168
- };
3169
- scheduleNext();
3170
- return () => {
3171
- cancelled = true;
3172
- clearTimeout(timeoutId);
3173
- };
3174
- }, [unverifiedOwnershipKey, queryEnabled]);
3175
- return {
3176
- data: response?.data,
3177
- totalCount: response?.total_count,
3178
- error: query.error ?? null,
3179
- isLoading: query.isLoading,
3180
- isFetching: query.isFetching,
3181
- createDomain,
3182
- prepareOwnershipVerification,
3183
- attemptOwnershipVerification,
3184
- revalidate
3185
- };
3186
- }
3187
-
3188
- //#endregion
3189
- //#region src/react/hooks/useOrganizationDirectorySync.shared.ts
3190
- /**
3191
- * @internal
3192
- */
3193
- function useOrganizationDirectorySyncCacheKeys(params) {
3194
- const { organizationId, enterpriseConnectionId } = params;
3195
- return (0, react.useMemo)(() => {
3196
- return createCacheKeys({
3197
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_DIRECTORY_SYNC_KEY,
3198
- authenticated: Boolean(organizationId),
3199
- tracked: {
3200
- organizationId: organizationId ?? null,
3201
- enterpriseConnectionId: enterpriseConnectionId ?? null
3202
- },
3203
- untracked: { args: {} }
3204
- });
3205
- }, [organizationId, enterpriseConnectionId]);
3206
- }
3207
- /**
3208
- * @internal
3209
- */
3210
- function useOrganizationDirectorySyncUsersCacheKeys(params) {
3211
- const { organizationId, enterpriseConnectionId, directoryId, args } = params;
3212
- return (0, react.useMemo)(() => {
3213
- return createCacheKeys({
3214
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_DIRECTORY_SYNC_USERS_KEY,
3215
- authenticated: Boolean(organizationId),
3216
- tracked: {
3217
- organizationId: organizationId ?? null,
3218
- enterpriseConnectionId: enterpriseConnectionId ?? null,
3219
- directoryId: directoryId ?? null
3220
- },
3221
- untracked: { args }
3222
- });
3223
- }, [
3224
- organizationId,
3225
- enterpriseConnectionId,
3226
- directoryId,
3227
- JSON.stringify(args)
3228
- ]);
3229
- }
3230
-
3231
- //#endregion
3232
- //#region src/react/hooks/useOrganizationDirectorySync.tsx
3233
- /**
3234
- * The Directory Sync directory bound to an enterprise connection of the active organization.
3235
- *
3236
- * @internal
3237
- */
3238
- function useOrganizationDirectorySync(params) {
3239
- const { enterpriseConnectionId, enabled = true } = params;
3240
- const clerk = useClerkInstanceContext();
3241
- const organization = useOrganizationBase();
3242
- const [queryClient] = useClerkQueryClient();
3243
- const { queryKey, invalidationKey, stableKey, authenticated } = useOrganizationDirectorySyncCacheKeys({
3244
- organizationId: organization?.id ?? null,
3245
- enterpriseConnectionId
3246
- });
3247
- const queryEnabled = enabled && clerk.loaded && Boolean(organization) && Boolean(enterpriseConnectionId);
3248
- useClearQueriesOnSignOut({
3249
- isSignedOut: organization === null,
3250
- authenticated,
3251
- stableKeys: stableKey
3252
- });
3253
- const query = useClerkQuery({
3254
- queryKey,
3255
- queryFn: async () => {
3256
- if (!enterpriseConnectionId) throw new Error("enterpriseConnectionId is required to fetch the directory");
3257
- try {
3258
- return await organization?.getDirectorySync(enterpriseConnectionId) ?? null;
3259
- } catch (err) {
3260
- if (require_error.isClerkAPIResponseError(err) && err.status === 404) return null;
3261
- throw err;
3262
- }
3263
- },
3264
- enabled: queryEnabled
3265
- });
3266
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: invalidationKey }), [queryClient, invalidationKey]);
3267
- const createDirectorySync = (0, react.useCallback)(async (createParams) => {
3268
- if (!enterpriseConnectionId) return;
3269
- const created = await organization?.createDirectorySync(enterpriseConnectionId, createParams);
3270
- await revalidate();
3271
- return created;
3272
- }, [
3273
- organization,
3274
- enterpriseConnectionId,
3275
- revalidate
3276
- ]);
3277
- const directory = query.data;
3278
- const updateDirectorySync = (0, react.useCallback)(async (updateParams) => {
3279
- if (!directory) return;
3280
- const updated = await directory.update(updateParams);
3281
- await revalidate();
3282
- return updated;
3283
- }, [directory, revalidate]);
3284
- const rotateDirectorySyncToken = (0, react.useCallback)(async () => {
3285
- if (!directory) return;
3286
- const rotated = await directory.rotateToken();
3287
- await revalidate();
3288
- return rotated;
3289
- }, [directory, revalidate]);
3290
- const deleteDirectorySync = (0, react.useCallback)(async () => {
3291
- if (!directory) return;
3292
- const deleted = await directory.delete();
3293
- await revalidate();
3294
- return deleted;
3295
- }, [directory, revalidate]);
3296
- return {
3297
- data: query.data,
3298
- error: query.error ?? null,
3299
- isLoading: query.isLoading,
3300
- isFetching: query.isFetching,
3301
- createDirectorySync,
3302
- updateDirectorySync,
3303
- rotateDirectorySyncToken,
3304
- deleteDirectorySync,
3305
- revalidate
3306
- };
3307
- }
3308
-
3309
- //#endregion
3310
- //#region src/react/hooks/useOrganizationDirectorySyncUsers.tsx
3311
- const DEFAULT_POLL_INTERVAL_MS$1 = 2e3;
3312
- /**
3313
- * The users provisioned into an enterprise connection's Directory Sync
3314
- * directory, most recently touched first. Polling is opt-in via `poll`, which
3315
- * lets the setup flow use the list as a live activity feed.
3316
- *
3317
- * @internal
3318
- */
3319
- function useOrganizationDirectorySyncUsers(params) {
3320
- const { directory, params: fetchParams = {
3321
- initialPage: 1,
3322
- pageSize: 10
3323
- }, poll = false, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS$1, enabled = true, keepPreviousData = true } = params;
3324
- const clerk = useClerkInstanceContext();
3325
- const organization = useOrganizationBase();
3326
- const [queryClient] = useClerkQueryClient();
3327
- const enterpriseConnectionId = directory?.enterpriseConnectionId ?? null;
3328
- const directoryId = directory?.id ?? null;
3329
- const { queryKey, invalidationKey, stableKey, authenticated } = useOrganizationDirectorySyncUsersCacheKeys({
3330
- organizationId: organization?.id ?? null,
3331
- enterpriseConnectionId,
3332
- directoryId,
3333
- args: fetchParams
3334
- });
3335
- useClearQueriesOnSignOut({
3336
- isSignedOut: organization === null,
3337
- authenticated,
3338
- stableKeys: stableKey
3339
- });
3340
- const queryEnabled = enabled && clerk.loaded && Boolean(organization) && Boolean(directory);
3341
- const currentTracked = queryKey[2];
3342
- const query = useClerkQuery({
3343
- queryKey,
3344
- queryFn: () => {
3345
- if (!directory) throw new Error("directory is required to fetch directory users");
3346
- return directory.getUsers(fetchParams);
3347
- },
3348
- refetchInterval: () => poll ? pollIntervalMs : false,
3349
- enabled: queryEnabled,
3350
- refetchIntervalInBackground: false,
3351
- placeholderData: keepPreviousData ? (previousData, previousQuery) => {
3352
- const previousTracked = previousQuery?.queryKey[2];
3353
- return Boolean(currentTracked.organizationId) && Boolean(currentTracked.directoryId) && previousTracked?.organizationId === currentTracked.organizationId && previousTracked?.directoryId === currentTracked.directoryId ? previousData : void 0;
3354
- } : void 0
3355
- });
3356
- const revalidate = (0, react.useCallback)(async () => {
3357
- await queryClient.invalidateQueries({ queryKey: invalidationKey });
3358
- }, [queryClient, invalidationKey]);
3359
- const isPolling = queryEnabled && poll;
3360
- return {
3361
- data: queryEnabled ? query.data?.data : void 0,
3362
- totalCount: queryEnabled ? query.data?.total_count : void 0,
3363
- error: query.error ?? null,
3364
- isLoading: query.isLoading,
3365
- isFetching: query.isFetching,
3366
- isPolling,
3367
- revalidate
3368
- };
3369
- }
3370
-
3371
- //#endregion
3372
- //#region src/react/hooks/useOrganizationEnterpriseConnectionTestRuns.shared.ts
3373
- /**
3374
- * @internal
3375
- */
3376
- function useOrganizationEnterpriseConnectionTestRunsCacheKeys(params) {
3377
- const { organizationId, enterpriseConnectionId, args } = params;
3378
- return (0, react.useMemo)(() => {
3379
- return createCacheKeys({
3380
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_ENTERPRISE_CONNECTION_TEST_RUNS_KEY,
3381
- authenticated: Boolean(organizationId),
3382
- tracked: {
3383
- organizationId: organizationId ?? null,
3384
- enterpriseConnectionId: enterpriseConnectionId ?? null
3385
- },
3386
- untracked: { args }
3387
- });
3388
- }, [
3389
- organizationId,
3390
- enterpriseConnectionId,
3391
- JSON.stringify(args)
3392
- ]);
3393
- }
3394
-
3395
- //#endregion
3396
- //#region src/react/hooks/useOrganizationEnterpriseConnectionTestRuns.tsx
3397
- const DEFAULT_POLL_INTERVAL_MS = 2e3;
3398
- /**
3399
- * Subscribes to the list of enterprise-connection test runs for the active organization
3400
- *
3401
- * @internal
3402
- */
3403
- function useOrganizationEnterpriseConnectionTestRuns(params) {
3404
- const { enterpriseConnectionId, params: fetchParams = {
3405
- initialPage: 1,
3406
- pageSize: 10
3407
- }, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, enabled = true, keepPreviousData = false } = params;
3408
- const clerk = useClerkInstanceContext();
3409
- const organization = useOrganizationBase();
3410
- const [queryClient] = useClerkQueryClient();
3411
- const { queryKey, invalidationKey, stableKey, authenticated } = useOrganizationEnterpriseConnectionTestRunsCacheKeys({
3412
- organizationId: organization?.id ?? null,
3413
- enterpriseConnectionId,
3414
- args: fetchParams
3415
- });
3416
- useClearQueriesOnSignOut({
3417
- isSignedOut: organization === null,
3418
- authenticated,
3419
- stableKeys: stableKey
3420
- });
3421
- const queryEnabled = enabled && clerk.loaded && Boolean(organization) && Boolean(enterpriseConnectionId);
3422
- const [pollingConnectionId, setPollingConnectionId] = (0, react.useState)(null);
3423
- const shouldPoll = pollingConnectionId !== null && pollingConnectionId === enterpriseConnectionId;
3424
- (0, react.useEffect)(() => {
3425
- setPollingConnectionId((current) => current !== null && current !== enterpriseConnectionId ? null : current);
3426
- }, [enterpriseConnectionId]);
3427
- const query = useClerkQuery({
3428
- queryKey,
3429
- queryFn: () => {
3430
- if (!enterpriseConnectionId) throw new Error("enterpriseConnectionId is required to fetch test runs");
3431
- return organization?.getEnterpriseConnectionTestRuns(enterpriseConnectionId, fetchParams);
3432
- },
3433
- refetchInterval: (q) => {
3434
- if (!shouldPoll) return false;
3435
- return (q.state.data?.data?.length ?? 0) > 0 ? false : pollIntervalMs;
3436
- },
3437
- enabled: queryEnabled,
3438
- refetchIntervalInBackground: false,
3439
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
3440
- });
3441
- const hasRows = (query.data?.data?.length ?? 0) > 0;
3442
- (0, react.useEffect)(() => {
3443
- if (shouldPoll && hasRows) setPollingConnectionId(null);
3444
- }, [shouldPoll, hasRows]);
3445
- const revalidate = (0, react.useCallback)(async (options) => {
3446
- if ((options?.armPolling ?? true) && !hasRows) setPollingConnectionId(enterpriseConnectionId);
3447
- if (options?.exact) await queryClient.invalidateQueries({
3448
- queryKey,
3449
- exact: true
3450
- });
3451
- else await queryClient.invalidateQueries({ queryKey: invalidationKey });
3452
- const fresh = queryClient.getQueryData(queryKey);
3453
- return {
3454
- data: fresh?.data,
3455
- totalCount: fresh?.total_count
3456
- };
3457
- }, [
3458
- queryClient,
3459
- invalidationKey,
3460
- queryKey,
3461
- hasRows,
3462
- enterpriseConnectionId
3463
- ]);
3464
- const isPolling = queryEnabled && shouldPoll && !hasRows;
3465
- return {
3466
- data: query.data?.data,
3467
- totalCount: query.data?.total_count,
3468
- error: query.error ?? null,
3469
- isLoading: query.isLoading,
3470
- isFetching: query.isFetching,
3471
- isPolling,
3472
- revalidate
3473
- };
3474
- }
3475
-
3476
- //#endregion
3477
- //#region src/react/hooks/useOrganizationSSOBypassAllowlist.shared.ts
3478
- /**
3479
- * @internal
3480
- */
3481
- function useOrganizationSSOBypassAllowlistCacheKeys(params) {
3482
- const { organizationId } = params;
3483
- return (0, react.useMemo)(() => {
3484
- return createCacheKeys({
3485
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_SSO_BYPASS_ALLOWLIST_KEY,
3486
- authenticated: Boolean(organizationId),
3487
- tracked: { organizationId: organizationId ?? null },
3488
- untracked: { args: {} }
3489
- });
3490
- }, [organizationId]);
3491
- }
3492
-
3493
- //#endregion
3494
- //#region src/react/hooks/useOrganizationSSOBypassAllowlist.tsx
3495
- /**
3496
- * The SSO bypass allowlist of the active organization
3497
- *
3498
- * @internal
3499
- */
3500
- function useOrganizationSSOBypassAllowlist(params = {}) {
3501
- const { keepPreviousData = false, enabled = true } = params;
3502
- const clerk = useClerkInstanceContext();
3503
- const organization = useOrganizationBase();
3504
- const [queryClient] = useClerkQueryClient();
3505
- const { queryKey, stableKey, authenticated } = useOrganizationSSOBypassAllowlistCacheKeys({ organizationId: organization?.id ?? null });
3506
- const queryEnabled = enabled && clerk.loaded && Boolean(organization);
3507
- useClearQueriesOnSignOut({
3508
- isSignedOut: organization === null,
3509
- authenticated,
3510
- stableKeys: stableKey
3511
- });
3512
- const query = useClerkQuery({
3513
- queryKey,
3514
- queryFn: () => organization?.ssoBypassAllowlist.getUsers(),
3515
- enabled: queryEnabled,
3516
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
3517
- });
3518
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: [stableKey] }), [queryClient, stableKey]);
3519
- const addUser = (0, react.useCallback)(async (addParams) => {
3520
- const added = await organization?.ssoBypassAllowlist.addUser(addParams);
3521
- await revalidate();
3522
- return added;
3523
- }, [organization, revalidate]);
3524
- const removeUser = (0, react.useCallback)(async (userId) => {
3525
- const removed = await organization?.ssoBypassAllowlist.removeUser(userId);
3526
- await revalidate();
3527
- return removed;
3528
- }, [organization, revalidate]);
3529
- return {
3530
- data: query.data,
3531
- error: query.error ?? null,
3532
- isLoading: query.isLoading,
3533
- isFetching: query.isFetching,
3534
- addUser,
3535
- removeUser,
3536
- revalidate
3537
- };
3538
- }
3539
-
3540
- //#endregion
3541
- //#region src/react/utils.ts
3542
- function assertClerkSingletonExists(clerk) {
3543
- if (!clerk) require_internal_clerk_js_errors.clerkCoreErrorNoClerkSingleton();
3544
- }
3545
-
3546
- //#endregion
3547
- //#region src/react/ClerkContextProvider.tsx
3548
- function ClerkContextProvider(props) {
3549
- const clerk = props.clerk;
3550
- assertClerkSingletonExists(clerk);
3551
- if (props.initialState instanceof Promise && !("use" in react.default && typeof react.default.use === "function")) throw new Error("initialState cannot be a promise if React version is less than 19");
3552
- const clerkCtx = react.default.useMemo(() => ({ value: clerk }), [props.clerkStatus]);
3553
- return /* @__PURE__ */ react.default.createElement(InitialStateProvider, { initialState: props.initialState }, /* @__PURE__ */ react.default.createElement(ClerkInstanceContext.Provider, { value: clerkCtx }, /* @__PURE__ */ react.default.createElement(__experimental_CheckoutProvider, { value: void 0 }, props.children)));
3554
- }
3555
-
3556
- //#endregion
3557
- //#region src/react/stripe-react/utils.ts
3558
- const usePrevious = (value) => {
3559
- const ref = (0, react.useRef)(value);
3560
- (0, react.useEffect)(() => {
3561
- ref.current = value;
3562
- }, [value]);
3563
- return ref.current;
3564
- };
3565
- const useAttachEvent = (element, event, cb) => {
3566
- const cbDefined = !!cb;
3567
- const cbRef = (0, react.useRef)(cb);
3568
- (0, react.useEffect)(() => {
3569
- cbRef.current = cb;
3570
- }, [cb]);
3571
- (0, react.useEffect)(() => {
3572
- if (!cbDefined || !element) return () => {};
3573
- const decoratedCb = (...args) => {
3574
- if (cbRef.current) cbRef.current(...args);
3575
- };
3576
- element.on(event, decoratedCb);
3577
- return () => {
3578
- element.off(event, decoratedCb);
3579
- };
3580
- }, [
3581
- cbDefined,
3582
- event,
3583
- element,
3584
- cbRef
3585
- ]);
3586
- };
3587
-
3588
- //#endregion
3589
- //#region src/react/stripe-react/index.tsx
3590
- const ElementsContext = react.default.createContext(null);
3591
- ElementsContext.displayName = "ElementsContext";
3592
- const parseElementsContext = (ctx, useCase) => {
3593
- if (!ctx) throw new Error(`Could not find Elements context; You need to wrap the part of your app that ${useCase} in an <Elements> provider.`);
3594
- return ctx;
3595
- };
3596
- /**
3597
- * The `Elements` provider allows you to use [Element components](https://stripe.com/docs/stripe-js/react#element-components) and access the [Stripe object](https://stripe.com/docs/js/initializing) in any nested component.
3598
- * Render an `Elements` provider at the root of your React app so that it is available everywhere you need it.
3599
- *
3600
- * To use the `Elements` provider, call `loadStripe` from `@stripe/stripe-js` with your publishable key.
3601
- * The `loadStripe` function will asynchronously load the Stripe.js script and initialize a `Stripe` object.
3602
- * Pass the returned `Promise` to `Elements`.
3603
- *
3604
- * @docs https://stripe.com/docs/stripe-js/react#elements-provider
3605
- */
3606
- const Elements = (({ stripe: rawStripeProp, options, children }) => {
3607
- const parsed = react.default.useMemo(() => parseStripeProp(rawStripeProp), [rawStripeProp]);
3608
- const [ctx, setContext] = react.default.useState(() => ({
3609
- stripe: parsed.tag === "sync" ? parsed.stripe : null,
3610
- elements: parsed.tag === "sync" ? parsed.stripe.elements(options) : null
3611
- }));
3612
- react.default.useEffect(() => {
3613
- let isMounted = true;
3614
- const safeSetContext = (stripe) => {
3615
- setContext((ctx) => {
3616
- if (ctx.stripe) return ctx;
3617
- return {
3618
- stripe,
3619
- elements: stripe.elements(options)
3620
- };
3621
- });
3622
- };
3623
- if (parsed.tag === "async" && !ctx.stripe) parsed.stripePromise.then((stripe) => {
3624
- if (stripe && isMounted) safeSetContext(stripe);
3625
- });
3626
- else if (parsed.tag === "sync" && !ctx.stripe) safeSetContext(parsed.stripe);
3627
- return () => {
3628
- isMounted = false;
3629
- };
3630
- }, [
3631
- parsed,
3632
- ctx,
3633
- options
3634
- ]);
3635
- const prevStripe = usePrevious(rawStripeProp);
3636
- react.default.useEffect(() => {
3637
- if (prevStripe !== null && prevStripe !== rawStripeProp) console.warn("Unsupported prop change on Elements: You cannot change the `stripe` prop after setting it.");
3638
- }, [prevStripe, rawStripeProp]);
3639
- const prevOptions = usePrevious(options);
3640
- react.default.useEffect(() => {
3641
- if (!ctx.elements) return;
3642
- const updates = extractAllowedOptionsUpdates(options, prevOptions, ["clientSecret", "fonts"]);
3643
- if (updates) ctx.elements.update(updates);
3644
- }, [
3645
- options,
3646
- prevOptions,
3647
- ctx.elements
3648
- ]);
3649
- return /* @__PURE__ */ react.default.createElement(ElementsContext.Provider, { value: ctx }, children);
3650
- });
3651
- const useElementsContextWithUseCase = (useCaseMessage) => {
3652
- return parseElementsContext(react.default.useContext(ElementsContext), useCaseMessage);
3653
- };
3654
- const useElements = () => {
3655
- const { elements } = useElementsContextWithUseCase("calls useElements()");
3656
- return elements;
3657
- };
3658
- const INVALID_STRIPE_ERROR = "Invalid prop `stripe` supplied to `Elements`. We recommend using the `loadStripe` utility from `@stripe/stripe-js`. See https://stripe.com/docs/stripe-js/react#elements-props-stripe for details.";
3659
- const validateStripe = (maybeStripe, errorMsg = INVALID_STRIPE_ERROR) => {
3660
- if (maybeStripe === null || isStripe(maybeStripe)) return maybeStripe;
3661
- throw new Error(errorMsg);
3662
- };
3663
- const parseStripeProp = (raw, errorMsg = INVALID_STRIPE_ERROR) => {
3664
- if (isPromise(raw)) return {
3665
- tag: "async",
3666
- stripePromise: Promise.resolve(raw).then((result) => validateStripe(result, errorMsg))
3667
- };
3668
- const stripe = validateStripe(raw, errorMsg);
3669
- if (stripe === null) return { tag: "empty" };
3670
- return {
3671
- tag: "sync",
3672
- stripe
3673
- };
3674
- };
3675
- const isUnknownObject = (raw) => {
3676
- return raw !== null && typeof raw === "object";
3677
- };
3678
- const isPromise = (raw) => {
3679
- return isUnknownObject(raw) && typeof raw.then === "function";
3680
- };
3681
- const isStripe = (raw) => {
3682
- return isUnknownObject(raw) && typeof raw.elements === "function" && typeof raw.createToken === "function" && typeof raw.createPaymentMethod === "function" && typeof raw.confirmCardPayment === "function";
3683
- };
3684
- const extractAllowedOptionsUpdates = (options, prevOptions, immutableKeys) => {
3685
- if (!isUnknownObject(options)) return null;
3686
- return Object.keys(options).reduce((newOptions, key) => {
3687
- const isUpdated = !isUnknownObject(prevOptions) || !isEqual(options[key], prevOptions[key]);
3688
- if (immutableKeys.includes(key)) {
3689
- if (isUpdated) console.warn(`Unsupported prop change: options.${key} is not a mutable property.`);
3690
- return newOptions;
3691
- }
3692
- if (!isUpdated) return newOptions;
3693
- return {
3694
- ...newOptions || {},
3695
- [key]: options[key]
3696
- };
3697
- }, null);
3698
- };
3699
- const PLAIN_OBJECT_STR = "[object Object]";
3700
- const isEqual = (left, right) => {
3701
- if (!isUnknownObject(left) || !isUnknownObject(right)) return left === right;
3702
- const leftArray = Array.isArray(left);
3703
- if (leftArray !== Array.isArray(right)) return false;
3704
- const leftPlainObject = Object.prototype.toString.call(left) === PLAIN_OBJECT_STR;
3705
- if (leftPlainObject !== (Object.prototype.toString.call(right) === PLAIN_OBJECT_STR)) return false;
3706
- if (!leftPlainObject && !leftArray) return left === right;
3707
- const leftKeys = Object.keys(left);
3708
- const rightKeys = Object.keys(right);
3709
- if (leftKeys.length !== rightKeys.length) return false;
3710
- const keySet = {};
3711
- for (let i = 0; i < leftKeys.length; i += 1) keySet[leftKeys[i]] = true;
3712
- for (let i = 0; i < rightKeys.length; i += 1) keySet[rightKeys[i]] = true;
3713
- const allKeys = Object.keys(keySet);
3714
- if (allKeys.length !== leftKeys.length) return false;
3715
- const l = left;
3716
- const r = right;
3717
- const pred = (key) => {
3718
- return isEqual(l[key], r[key]);
3719
- };
3720
- return allKeys.every(pred);
3721
- };
3722
- const useStripe = () => {
3723
- const { stripe } = useElementsOrCheckoutSdkContextWithUseCase("calls useStripe()");
3724
- return stripe;
3725
- };
3726
- const useElementsOrCheckoutSdkContextWithUseCase = (useCaseString) => {
3727
- return parseElementsContext(react.default.useContext(ElementsContext), useCaseString);
3728
- };
3729
- const capitalized = (str) => str.charAt(0).toUpperCase() + str.slice(1);
3730
- const createElementComponent = (type, isServer) => {
3731
- const displayName = `${capitalized(type)}Element`;
3732
- const ClientElement = ({ id, className, fallback, options = {}, onBlur, onFocus, onReady, onChange, onEscape, onClick, onLoadError, onLoaderStart, onNetworksChange, onConfirm, onCancel, onShippingAddressChange, onShippingRateChange }) => {
3733
- const ctx = useElementsOrCheckoutSdkContextWithUseCase(`mounts <${displayName}>`);
3734
- const elements = "elements" in ctx ? ctx.elements : null;
3735
- const [element, setElement] = react.default.useState(null);
3736
- const elementRef = react.default.useRef(null);
3737
- const domNode = react.default.useRef(null);
3738
- const [isReady, setReady] = (0, react.useState)(false);
3739
- useAttachEvent(element, "blur", onBlur);
3740
- useAttachEvent(element, "focus", onFocus);
3741
- useAttachEvent(element, "escape", onEscape);
3742
- useAttachEvent(element, "click", onClick);
3743
- useAttachEvent(element, "loaderror", onLoadError);
3744
- useAttachEvent(element, "loaderstart", onLoaderStart);
3745
- useAttachEvent(element, "networkschange", onNetworksChange);
3746
- useAttachEvent(element, "confirm", onConfirm);
3747
- useAttachEvent(element, "cancel", onCancel);
3748
- useAttachEvent(element, "shippingaddresschange", onShippingAddressChange);
3749
- useAttachEvent(element, "shippingratechange", onShippingRateChange);
3750
- useAttachEvent(element, "change", onChange);
3751
- let readyCallback;
3752
- if (onReady) readyCallback = () => {
3753
- setReady(true);
3754
- onReady(element);
3755
- };
3756
- useAttachEvent(element, "ready", readyCallback);
3757
- react.default.useLayoutEffect(() => {
3758
- if (elementRef.current === null && domNode.current !== null && elements) {
3759
- let newElement = null;
3760
- if (elements) newElement = elements.create(type, options);
3761
- elementRef.current = newElement;
3762
- setElement(newElement);
3763
- if (newElement) newElement.mount(domNode.current);
3764
- }
3765
- }, [elements, options]);
3766
- const prevOptions = usePrevious(options);
3767
- react.default.useEffect(() => {
3768
- if (!elementRef.current) return;
3769
- const updates = extractAllowedOptionsUpdates(options, prevOptions, ["paymentRequest"]);
3770
- if (updates && "update" in elementRef.current) elementRef.current.update(updates);
3771
- }, [options, prevOptions]);
3772
- react.default.useLayoutEffect(() => {
3773
- return () => {
3774
- if (elementRef.current && typeof elementRef.current.destroy === "function") try {
3775
- elementRef.current.destroy();
3776
- elementRef.current = null;
3777
- } catch {}
3778
- };
3779
- }, []);
3780
- return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, !isReady && fallback, /* @__PURE__ */ react.default.createElement("div", {
3781
- id,
3782
- style: {
3783
- height: isReady ? "unset" : "0px",
3784
- visibility: isReady ? "visible" : "hidden"
3785
- },
3786
- className,
3787
- ref: domNode
3788
- }));
3789
- };
3790
- const ServerElement = (props) => {
3791
- useElementsOrCheckoutSdkContextWithUseCase(`mounts <${displayName}>`);
3792
- const { id, className } = props;
3793
- return /* @__PURE__ */ react.default.createElement("div", {
3794
- id,
3795
- className
3796
- });
3797
- };
3798
- const Element = isServer ? ServerElement : ClientElement;
3799
- Element.displayName = displayName;
3800
- Element.__elementType = type;
3801
- return Element;
3802
- };
3803
- const PaymentElement$1 = createElementComponent("payment", typeof window === "undefined");
3804
-
3805
- //#endregion
3806
- //#region src/react/billing/useInitializePaymentMethod.tsx
3807
- /**
3808
- * @internal
3809
- */
3810
- function useInitializePaymentMethod(options) {
3811
- const { for: forType } = options ?? {};
3812
- const organization = useOrganizationBase();
3813
- const user = useUserBase();
3814
- const resource = forType === "organization" ? organization : user;
3815
- const billingEnabled = useBillingIsEnabled(options);
3816
- const stableKey = "billing-payment-method-initialize";
3817
- const authenticated = true;
3818
- const queryKey = (0, react.useMemo)(() => {
3819
- return [
3820
- stableKey,
3821
- authenticated,
3822
- { resourceId: resource?.id },
3823
- {}
3824
- ];
3825
- }, [resource?.id]);
3826
- const isEnabled = Boolean(resource?.id) && billingEnabled;
3827
- useClearQueriesOnSignOut({
3828
- isSignedOut: user === null,
3829
- authenticated,
3830
- stableKeys: stableKey
3831
- });
3832
- const query = useClerkQuery({
3833
- queryKey,
3834
- queryFn: async () => {
3835
- if (!resource) return;
3836
- return resource.initializePaymentMethod({ gateway: "stripe" });
3837
- },
3838
- enabled: isEnabled,
3839
- staleTime: 1e3 * 60,
3840
- refetchOnWindowFocus: false,
3841
- placeholderData: defineKeepPreviousDataFn(isEnabled)
3842
- });
3843
- const [queryClient] = useClerkQueryClient();
3844
- const initializePaymentMethod = (0, react.useCallback)(async () => {
3845
- if (!resource) return;
3846
- const result = await resource.initializePaymentMethod({ gateway: "stripe" });
3847
- queryClient.setQueryData(queryKey, result);
3848
- return result;
3849
- }, [
3850
- queryClient,
3851
- queryKey,
3852
- resource
3853
- ]);
3854
- return {
3855
- initializedPaymentMethod: query.data ?? void 0,
3856
- initializePaymentMethod
3857
- };
3858
- }
3859
-
3860
- //#endregion
3861
- //#region src/react/billing/useStripeClerkLibs.tsx
3862
- /**
3863
- * @internal
3864
- */
3865
- function useStripeClerkLibs() {
3866
- const clerk = useClerk();
3867
- return useClerkQuery({
3868
- queryKey: ["clerk-stripe-sdk"],
3869
- queryFn: async () => {
3870
- return { loadStripe: await clerk.__internal_loadStripeJs() };
3871
- },
3872
- staleTime: Infinity,
3873
- refetchOnWindowFocus: false,
3874
- placeholderData: defineKeepPreviousDataFn(true)
3875
- }).data ?? null;
3876
- }
3877
-
3878
- //#endregion
3879
- //#region src/react/billing/useStripeLoader.tsx
3880
- /**
3881
- * @internal
3882
- */
3883
- function useStripeLoader(options) {
3884
- const { stripeClerkLibs, externalGatewayId, stripePublishableKey } = options;
3885
- const queryKey = (0, react.useMemo)(() => {
3886
- return ["stripe-sdk", {
3887
- externalGatewayId,
3888
- stripePublishableKey
3889
- }];
3890
- }, [externalGatewayId, stripePublishableKey]);
3891
- const billingEnabled = useBillingIsEnabled({ authenticated: true });
3892
- return useClerkQuery({
3893
- queryKey,
3894
- queryFn: () => {
3895
- if (!stripeClerkLibs || !externalGatewayId || !stripePublishableKey) return null;
3896
- return stripeClerkLibs.loadStripe(stripePublishableKey, { stripeAccount: externalGatewayId });
3897
- },
3898
- enabled: Boolean(stripeClerkLibs && externalGatewayId && stripePublishableKey) && billingEnabled,
3899
- staleTime: 1e3 * 60,
3900
- refetchOnWindowFocus: false,
3901
- placeholderData: defineKeepPreviousDataFn(true)
3902
- }).data;
3903
- }
3904
-
3905
- //#endregion
3906
- //#region src/react/billing/payment-element.tsx
3907
- const useInternalEnvironment = () => {
3908
- return useClerk().__internal_environment;
3909
- };
3910
- const useLocalization = () => {
3911
- const clerk = useClerk();
3912
- let locale = "en";
3913
- try {
3914
- locale = clerk.__internal_getOption("localization")?.locale || "en";
3915
- } catch {}
3916
- return locale.split("-")[0];
3917
- };
3918
- const usePaymentSourceUtils = (forResource = "user") => {
3919
- const stripeClerkLibs = useStripeClerkLibs();
3920
- const environment = useInternalEnvironment();
3921
- const { initializedPaymentMethod, initializePaymentMethod } = useInitializePaymentMethod({ for: forResource });
3922
- const stripePublishableKey = environment?.commerceSettings.billing.stripePublishableKey ?? void 0;
3923
- return {
3924
- stripe: useStripeLoader({
3925
- stripeClerkLibs,
3926
- externalGatewayId: initializedPaymentMethod?.externalGatewayId,
3927
- stripePublishableKey
3928
- }),
3929
- initializePaymentMethod,
3930
- externalClientSecret: initializedPaymentMethod?.externalClientSecret,
3931
- paymentMethodOrder: initializedPaymentMethod?.paymentMethodOrder
3932
- };
3933
- };
3934
- const [PaymentElementContext, usePaymentElementContext] = createContextAndHook("PaymentElementContext");
3935
- const [StripeUtilsContext, useStripeUtilsContext] = createContextAndHook("StripeUtilsContext");
3936
- const ValidateStripeUtils = ({ children }) => {
3937
- const stripe = useStripe();
3938
- const elements = useElements();
3939
- return /* @__PURE__ */ react.default.createElement(StripeUtilsContext.Provider, { value: { value: {
3940
- stripe,
3941
- elements
3942
- } } }, children);
3943
- };
3944
- const DummyStripeUtils = ({ children }) => {
3945
- return /* @__PURE__ */ react.default.createElement(StripeUtilsContext.Provider, { value: { value: {} } }, children);
3946
- };
3947
- const PropsProvider = ({ children, ...props }) => {
3948
- const utils = usePaymentSourceUtils(props.for);
3949
- const [isPaymentElementReady, setIsPaymentElementReady] = (0, react.useState)(false);
3950
- return /* @__PURE__ */ react.default.createElement(PaymentElementContext.Provider, { value: { value: {
3951
- ...props,
3952
- ...utils,
3953
- setIsPaymentElementReady,
3954
- isPaymentElementReady
3955
- } } }, children);
3956
- };
3957
- const PaymentElementProvider = ({ children, ...props }) => {
3958
- return /* @__PURE__ */ react.default.createElement(PropsProvider, props, /* @__PURE__ */ react.default.createElement(PaymentElementInternalRoot, null, children));
3959
- };
3960
- const PaymentElementInternalRoot = (props) => {
3961
- const { stripe, externalClientSecret, stripeAppearance } = usePaymentElementContext();
3962
- const locale = useLocalization();
3963
- if (stripe && externalClientSecret) return /* @__PURE__ */ react.default.createElement(Elements, {
3964
- key: externalClientSecret,
3965
- stripe,
3966
- options: {
3967
- loader: "never",
3968
- clientSecret: externalClientSecret,
3969
- appearance: { variables: stripeAppearance },
3970
- locale
3971
- }
3972
- }, /* @__PURE__ */ react.default.createElement(ValidateStripeUtils, null, props.children));
3973
- return /* @__PURE__ */ react.default.createElement(DummyStripeUtils, null, props.children);
3974
- };
3975
- const PaymentElement = ({ fallback }) => {
3976
- const { setIsPaymentElementReady, paymentMethodOrder, checkout, stripe, externalClientSecret, paymentDescription, for: _for } = usePaymentElementContext();
3977
- const environment = useInternalEnvironment();
3978
- const applePay = (0, react.useMemo)(() => {
3979
- if (!checkout || !checkout.totals || !checkout.plan) return;
3980
- return { recurringPaymentRequest: {
3981
- paymentDescription: paymentDescription || "",
3982
- managementURL: _for === "organization" ? environment?.displayConfig.organizationProfileUrl || "" : environment?.displayConfig.userProfileUrl || "",
3983
- regularBilling: {
3984
- amount: checkout.totals.totalDueNow?.amount || checkout.totals.grandTotal.amount,
3985
- label: checkout.plan.name,
3986
- recurringPaymentIntervalUnit: checkout.planPeriod === "annual" ? "year" : "month"
3987
- }
3988
- } };
3989
- }, [
3990
- checkout,
3991
- paymentDescription,
3992
- _for,
3993
- environment
3994
- ]);
3995
- const options = (0, react.useMemo)(() => {
3996
- return {
3997
- layout: {
3998
- type: "tabs",
3999
- defaultCollapsed: false
4000
- },
4001
- paymentMethodOrder,
4002
- applePay
4003
- };
4004
- }, [applePay, paymentMethodOrder]);
4005
- const onReady = (0, react.useCallback)(() => {
4006
- setIsPaymentElementReady(true);
4007
- }, [setIsPaymentElementReady]);
4008
- if (!stripe || !externalClientSecret) return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, fallback);
4009
- return /* @__PURE__ */ react.default.createElement(PaymentElement$1, {
4010
- fallback,
4011
- onReady,
4012
- options
4013
- });
4014
- };
4015
- const throwLibsMissingError = () => {
4016
- throw new Error("Clerk: Unable to submit, Stripe libraries are not yet loaded. Be sure to check `isFormReady` before calling `submit`.");
4017
- };
4018
- const usePaymentElement = () => {
4019
- const { isPaymentElementReady, initializePaymentMethod } = usePaymentElementContext();
4020
- const { stripe, elements } = useStripeUtilsContext();
4021
- const { externalClientSecret } = usePaymentElementContext();
4022
- const submit = (0, react.useCallback)(async () => {
4023
- if (!stripe || !elements) return throwLibsMissingError();
4024
- const { setupIntent, error } = await stripe.confirmSetup({
4025
- elements,
4026
- confirmParams: { return_url: window.location.href },
4027
- redirect: "if_required"
4028
- });
4029
- if (error) return {
4030
- data: null,
4031
- error: {
4032
- gateway: "stripe",
4033
- error: {
4034
- code: error.code,
4035
- message: error.message,
4036
- type: error.type
4037
- }
4038
- }
4039
- };
4040
- return {
4041
- data: {
4042
- gateway: "stripe",
4043
- paymentToken: setupIntent.payment_method
4044
- },
4045
- error: null
4046
- };
4047
- }, [stripe, elements]);
4048
- const reset = (0, react.useCallback)(async () => {
4049
- if (!stripe || !elements) return throwLibsMissingError();
4050
- await initializePaymentMethod();
4051
- }, [
4052
- stripe,
4053
- elements,
4054
- initializePaymentMethod
4055
- ]);
4056
- const isProviderReady = Boolean(stripe && externalClientSecret);
4057
- if (!isProviderReady) return {
4058
- submit: throwLibsMissingError,
4059
- reset: throwLibsMissingError,
4060
- isFormReady: false,
4061
- provider: void 0,
4062
- isProviderReady: false
4063
- };
4064
- return {
4065
- submit,
4066
- reset,
4067
- isFormReady: isPaymentElementReady,
4068
- provider: { name: "stripe" },
4069
- isProviderReady
4070
- };
4071
- };
4072
-
4073
- //#endregion
4074
- //#region src/react/PortalProvider.tsx
4075
- const [PortalContext, , usePortalContextWithoutGuarantee] = createContextAndHook("PortalProvider");
4076
- /**
4077
- * UNSAFE_PortalProvider allows you to specify a custom container for Clerk floating UI elements
4078
- * (popovers, modals, tooltips, etc.) that use portals.
4079
- *
4080
- * Only components within this provider will be affected. Components outside the provider
4081
- * will continue to use the default document.body for portals.
4082
- *
4083
- * This is particularly useful when using Clerk components inside external UI libraries
4084
- * like Radix Dialog or React Aria Components, where portaled elements need to render
4085
- * within the dialog's container to remain interactable.
4086
- *
4087
- * @example
4088
- * ```tsx
4089
- * function Example() {
4090
- * const containerRef = useRef(null);
4091
- * return (
4092
- * <RadixDialog ref={containerRef}>
4093
- * <UNSAFE_PortalProvider getContainer={() => containerRef.current}>
4094
- * <UserButton />
4095
- * </UNSAFE_PortalProvider>
4096
- * </RadixDialog>
4097
- * );
4098
- * }
4099
- * ```
4100
- */
4101
- const UNSAFE_PortalProvider = ({ children, getContainer }) => {
4102
- const contextValue = react.default.useMemo(() => ({ value: { getContainer } }), [getContainer]);
4103
- return /* @__PURE__ */ react.default.createElement(PortalContext.Provider, { value: contextValue }, children);
4104
- };
4105
- UNSAFE_PortalProvider.displayName = "UNSAFE_PortalProvider";
4106
- /**
4107
- * Hook to get the current portal root container.
4108
- * Returns the getContainer function from context if inside a PortalProvider,
4109
- * otherwise returns a function that returns null (default behavior).
4110
- */
4111
- const usePortalRoot = () => {
4112
- const contextValue = usePortalContextWithoutGuarantee();
4113
- if (contextValue && "getContainer" in contextValue && contextValue.getContainer) return contextValue.getContainer;
4114
- return () => null;
4115
- };
4116
-
4117
- //#endregion
4118
- exports.ClerkContextProvider = ClerkContextProvider;
4119
- exports.ClerkInstanceContext = ClerkInstanceContext;
4120
- exports.InitialStateProvider = InitialStateProvider;
4121
- exports.OptionsContext = OptionsContext;
4122
- exports.UNSAFE_PortalProvider = UNSAFE_PortalProvider;
4123
- exports.__createClerkTestQueryClient = __createClerkTestQueryClient;
4124
- exports.__experimental_CheckoutProvider = __experimental_CheckoutProvider;
4125
- exports.__experimental_PaymentElement = PaymentElement;
4126
- exports.__experimental_PaymentElementProvider = PaymentElementProvider;
4127
- exports.__experimental_useCheckout = useCheckout;
4128
- exports.__experimental_usePaymentAttempts = usePaymentAttempts;
4129
- exports.__experimental_usePaymentElement = usePaymentElement;
4130
- exports.__experimental_usePaymentMethods = usePaymentMethods;
4131
- exports.__experimental_usePlans = usePlans;
4132
- exports.__experimental_useStatements = useStatements;
4133
- exports.__experimental_useSubscription = useSubscription;
4134
- exports.__internal_useClientBase = useClientBase;
4135
- exports.__internal_useCreditBalanceQuery = __internal_useCreditBalanceQuery;
4136
- exports.__internal_useCreditHistoryQuery = __internal_useCreditHistoryQuery;
4137
- exports.__internal_useOrganizationBase = useOrganizationBase;
4138
- exports.__internal_useOrganizationDirectorySync = useOrganizationDirectorySync;
4139
- exports.__internal_useOrganizationDirectorySyncUsers = useOrganizationDirectorySyncUsers;
4140
- exports.__internal_useOrganizationDomains = useOrganizationDomains;
4141
- exports.__internal_useOrganizationEnterpriseConnectionTestRuns = useOrganizationEnterpriseConnectionTestRuns;
4142
- exports.__internal_useOrganizationEnterpriseConnections = useOrganizationEnterpriseConnections;
4143
- exports.__internal_useOrganizationSSOBypassAllowlist = useOrganizationSSOBypassAllowlist;
4144
- exports.__internal_usePaymentAttemptQuery = usePaymentAttemptQuery;
4145
- exports.__internal_usePlanDetailsQuery = __internal_usePlanDetailsQuery;
4146
- exports.__internal_useSessionBase = useSessionBase;
4147
- exports.__internal_useStatementQuery = useStatementQuery;
4148
- exports.__internal_useUserBase = useUserBase;
4149
- exports.__internal_useUserEnterpriseConnections = useUserEnterpriseConnections;
4150
- exports.__resetClerkQueryClientForTest = __resetClerkQueryClientForTest;
4151
- exports.__setClerkQueryClientForTest = __setClerkQueryClientForTest;
4152
- exports.assertContextExists = assertContextExists;
4153
- exports.createContextAndHook = createContextAndHook;
4154
- exports.getClerkQueryClient = getClerkQueryClient;
4155
- exports.isDeeplyEqual = isDeeplyEqual;
4156
- exports.useAPIKeys = useAPIKeys;
4157
- exports.useAssertWrappedByClerkProvider = useAssertWrappedByClerkProvider;
4158
- exports.useAttemptToEnableOrganizations = useAttemptToEnableOrganizations;
4159
- exports.useClerk = useClerk;
4160
- exports.useClerkInstanceContext = useClerkInstanceContext;
4161
- exports.useDeepEqualMemo = useDeepEqualMemo;
4162
- exports.useInitialStateContext = useInitialStateContext;
4163
- exports.useOAuthConsent = useOAuthConsent;
4164
- exports.useOAuthDeviceVerification = useOAuthDeviceVerification;
4165
- exports.useOptionsContext = useOptionsContext;
4166
- exports.useOrganization = useOrganization;
4167
- exports.useOrganizationCreationDefaults = useOrganizationCreationDefaults;
4168
- exports.useOrganizationList = useOrganizationList;
4169
- exports.usePortalRoot = usePortalRoot;
4170
- exports.useReverification = useReverification;
4171
- exports.useSafeLayoutEffect = useSafeLayoutEffect;
4172
- exports.useSession = useSession;
4173
- exports.useSessionList = useSessionList;
4174
- exports.useUser = useUser;
4175
- //# sourceMappingURL=index.js.map
2
+ const require_createContextAndHook = require('./hooks/createContextAndHook.js');
3
+ const require_contexts = require('./contexts.js');
4
+ const require_clerk_query_client = require('./query/clerk-query-client.js');
5
+ const require_useAPIKeys = require('./hooks/useAPIKeys.js');
6
+ const require_useUserBase = require('./hooks/base/useUserBase.js');
7
+ const require_useOAuthConsent = require('./hooks/useOAuthConsent.js');
8
+ const require_useOAuthDeviceVerification = require('./hooks/useOAuthDeviceVerification.js');
9
+ const require_useOrganizationBase = require('./hooks/base/useOrganizationBase.js');
10
+ const require_useSessionBase = require('./hooks/base/useSessionBase.js');
11
+ const require_useClerk = require('./hooks/useClerk.js');
12
+ const require_useAttemptToEnableOrganizations = require('./hooks/useAttemptToEnableOrganizations.js');
13
+ const require_useOrganization = require('./hooks/useOrganization.js');
14
+ const require_useOrganizationCreationDefaults = require('./hooks/useOrganizationCreationDefaults.js');
15
+ const require_useOrganizationList = require('./hooks/useOrganizationList.js');
16
+ const require_useSafeLayoutEffect = require('./hooks/useSafeLayoutEffect.js');
17
+ const require_useSession = require('./hooks/useSession.js');
18
+ const require_useClientBase = require('./hooks/base/useClientBase.js');
19
+ const require_useSessionList = require('./hooks/useSessionList.js');
20
+ const require_useUser = require('./hooks/useUser.js');
21
+ const require_useDeepEqualMemo = require('./hooks/useDeepEqualMemo.js');
22
+ const require_useReverification = require('./hooks/useReverification.js');
23
+ const require_useStatements = require('./hooks/useStatements.js');
24
+ const require_usePaymentAttempts = require('./hooks/usePaymentAttempts.js');
25
+ const require_usePaymentMethods = require('./hooks/usePaymentMethods.js');
26
+ const require_usePlans = require('./hooks/usePlans.js');
27
+ const require_useSubscription = require('./hooks/useSubscription.js');
28
+ const require_useCheckout = require('./hooks/useCheckout.js');
29
+ const require_useCreditBalance = require('./hooks/useCreditBalance.js');
30
+ const require_useCreditHistory = require('./hooks/useCreditHistory.js');
31
+ const require_useStatementQuery = require('./hooks/useStatementQuery.js');
32
+ const require_usePlanDetailsQuery = require('./hooks/usePlanDetailsQuery.js');
33
+ const require_usePaymentAttemptQuery = require('./hooks/usePaymentAttemptQuery.js');
34
+ const require_useUserEnterpriseConnections = require('./hooks/useUserEnterpriseConnections.js');
35
+ const require_useOrganizationEnterpriseConnections = require('./hooks/useOrganizationEnterpriseConnections.js');
36
+ const require_useOrganizationDomains = require('./hooks/useOrganizationDomains.js');
37
+ const require_useOrganizationDirectorySync = require('./hooks/useOrganizationDirectorySync.js');
38
+ const require_useOrganizationDirectorySyncUsers = require('./hooks/useOrganizationDirectorySyncUsers.js');
39
+ const require_useOrganizationEnterpriseConnectionTestRuns = require('./hooks/useOrganizationEnterpriseConnectionTestRuns.js');
40
+ const require_useOrganizationSSOBypassAllowlist = require('./hooks/useOrganizationSSOBypassAllowlist.js');
41
+ require('./hooks/index.js');
42
+ const require_ClerkContextProvider = require('./ClerkContextProvider.js');
43
+ const require_payment_element = require('./billing/payment-element.js');
44
+ const require_PortalProvider = require('./PortalProvider.js');
45
+
46
+ exports.ClerkContextProvider = require_ClerkContextProvider.ClerkContextProvider;
47
+ exports.ClerkInstanceContext = require_contexts.ClerkInstanceContext;
48
+ exports.InitialStateProvider = require_contexts.InitialStateProvider;
49
+ exports.OptionsContext = require_contexts.OptionsContext;
50
+ exports.UNSAFE_PortalProvider = require_PortalProvider.UNSAFE_PortalProvider;
51
+ exports.__createClerkTestQueryClient = require_clerk_query_client.__createClerkTestQueryClient;
52
+ exports.__experimental_CheckoutProvider = require_contexts.__experimental_CheckoutProvider;
53
+ exports.__experimental_PaymentElement = require_payment_element.PaymentElement;
54
+ exports.__experimental_PaymentElementProvider = require_payment_element.PaymentElementProvider;
55
+ exports.__experimental_useCheckout = require_useCheckout.useCheckout;
56
+ exports.__experimental_usePaymentAttempts = require_usePaymentAttempts.usePaymentAttempts;
57
+ exports.__experimental_usePaymentElement = require_payment_element.usePaymentElement;
58
+ exports.__experimental_usePaymentMethods = require_usePaymentMethods.usePaymentMethods;
59
+ exports.__experimental_usePlans = require_usePlans.usePlans;
60
+ exports.__experimental_useStatements = require_useStatements.useStatements;
61
+ exports.__experimental_useSubscription = require_useSubscription.useSubscription;
62
+ exports.__internal_useClientBase = require_useClientBase.useClientBase;
63
+ exports.__internal_useCreditBalanceQuery = require_useCreditBalance.__internal_useCreditBalanceQuery;
64
+ exports.__internal_useCreditHistoryQuery = require_useCreditHistory.__internal_useCreditHistoryQuery;
65
+ exports.__internal_useOrganizationBase = require_useOrganizationBase.useOrganizationBase;
66
+ exports.__internal_useOrganizationDirectorySync = require_useOrganizationDirectorySync.useOrganizationDirectorySync;
67
+ exports.__internal_useOrganizationDirectorySyncUsers = require_useOrganizationDirectorySyncUsers.useOrganizationDirectorySyncUsers;
68
+ exports.__internal_useOrganizationDomains = require_useOrganizationDomains.useOrganizationDomains;
69
+ exports.__internal_useOrganizationEnterpriseConnectionTestRuns = require_useOrganizationEnterpriseConnectionTestRuns.useOrganizationEnterpriseConnectionTestRuns;
70
+ exports.__internal_useOrganizationEnterpriseConnections = require_useOrganizationEnterpriseConnections.useOrganizationEnterpriseConnections;
71
+ exports.__internal_useOrganizationSSOBypassAllowlist = require_useOrganizationSSOBypassAllowlist.useOrganizationSSOBypassAllowlist;
72
+ exports.__internal_usePaymentAttemptQuery = require_usePaymentAttemptQuery.usePaymentAttemptQuery;
73
+ exports.__internal_usePlanDetailsQuery = require_usePlanDetailsQuery.__internal_usePlanDetailsQuery;
74
+ exports.__internal_useSessionBase = require_useSessionBase.useSessionBase;
75
+ exports.__internal_useStatementQuery = require_useStatementQuery.useStatementQuery;
76
+ exports.__internal_useUserBase = require_useUserBase.useUserBase;
77
+ exports.__internal_useUserEnterpriseConnections = require_useUserEnterpriseConnections.useUserEnterpriseConnections;
78
+ exports.__resetClerkQueryClientForTest = require_clerk_query_client.__resetClerkQueryClientForTest;
79
+ exports.__setClerkQueryClientForTest = require_clerk_query_client.__setClerkQueryClientForTest;
80
+ exports.assertContextExists = require_createContextAndHook.assertContextExists;
81
+ exports.createContextAndHook = require_createContextAndHook.createContextAndHook;
82
+ exports.getClerkQueryClient = require_clerk_query_client.getClerkQueryClient;
83
+ exports.isDeeplyEqual = require_useDeepEqualMemo.isDeeplyEqual;
84
+ exports.useAPIKeys = require_useAPIKeys.useAPIKeys;
85
+ exports.useAssertWrappedByClerkProvider = require_contexts.useAssertWrappedByClerkProvider;
86
+ exports.useAttemptToEnableOrganizations = require_useAttemptToEnableOrganizations.useAttemptToEnableOrganizations;
87
+ exports.useClerk = require_useClerk.useClerk;
88
+ exports.useClerkInstanceContext = require_contexts.useClerkInstanceContext;
89
+ exports.useDeepEqualMemo = require_useDeepEqualMemo.useDeepEqualMemo;
90
+ exports.useInitialStateContext = require_contexts.useInitialStateContext;
91
+ exports.useOAuthConsent = require_useOAuthConsent.useOAuthConsent;
92
+ exports.useOAuthDeviceVerification = require_useOAuthDeviceVerification.useOAuthDeviceVerification;
93
+ exports.useOptionsContext = require_contexts.useOptionsContext;
94
+ exports.useOrganization = require_useOrganization.useOrganization;
95
+ exports.useOrganizationCreationDefaults = require_useOrganizationCreationDefaults.useOrganizationCreationDefaults;
96
+ exports.useOrganizationList = require_useOrganizationList.useOrganizationList;
97
+ exports.usePortalRoot = require_PortalProvider.usePortalRoot;
98
+ exports.useReverification = require_useReverification.useReverification;
99
+ exports.useSafeLayoutEffect = require_useSafeLayoutEffect.useSafeLayoutEffect;
100
+ exports.useSession = require_useSession.useSession;
101
+ exports.useSessionList = require_useSessionList.useSessionList;
102
+ exports.useUser = require_useUser.useUser;