@clerk/shared
Version:
Internal package utils used by the Clerk SDKs
1 lines • 256 kB
Source Map (JSON)
{"version":3,"file":"index.mjs","names":["React","HOOK_NAME","undefinedPaginatedResource","HOOK_NAME","hookName","hookName","deepEqual","HOOK_NAME","HOOK_NAME","CheckoutProvider","PaymentElement","StripePaymentElement"],"sources":["../../src/react/hooks/createContextAndHook.ts","../../src/react/contexts.tsx","../../src/react/stable-keys.ts","../../src/react/hooks/createCacheKeys.ts","../../src/react/query/keep-previous-data.ts","../../src/react/query/clerk-query-client.ts","../../src/react/query/use-clerk-query-client.ts","../../src/react/query/useBaseQuery.ts","../../src/react/query/useInfiniteQuery.ts","../../src/react/query/useQuery.ts","../../src/react/hooks/usePreviousValue.ts","../../src/react/hooks/useClearQueriesOnSignOut.ts","../../src/react/hooks/usePagesOrInfinite.shared.ts","../../src/react/hooks/usePagesOrInfinite.tsx","../../src/react/hooks/useAPIKeys.tsx","../../src/react/hooks/base/useUserBase.ts","../../src/react/hooks/useOAuthConsent.shared.ts","../../src/react/hooks/useOAuthConsent.tsx","../../src/react/hooks/base/useOrganizationBase.ts","../../src/react/hooks/base/useSessionBase.ts","../../src/react/hooks/useClerk.ts","../../src/react/hooks/useAttemptToEnableOrganizations.ts","../../src/react/hooks/useOrganization.tsx","../../src/react/hooks/useOrganizationCreationDefaults.shared.ts","../../src/react/hooks/useOrganizationCreationDefaults.tsx","../../src/react/hooks/useOrganizationList.tsx","../../src/react/hooks/useSafeLayoutEffect.tsx","../../src/react/hooks/useSession.ts","../../src/react/hooks/base/useClientBase.ts","../../src/react/hooks/useSessionList.ts","../../src/react/hooks/useUser.ts","../../src/react/hooks/useDeepEqualMemo.ts","../../src/react/hooks/useReverification.ts","../../src/react/hooks/useBillingIsEnabled.ts","../../src/react/hooks/createBillingPaginatedHook.tsx","../../src/react/hooks/useStatements.tsx","../../src/react/hooks/usePaymentAttempts.tsx","../../src/react/hooks/usePaymentMethods.tsx","../../src/react/hooks/usePlans.tsx","../../src/react/hooks/useSubscription.shared.ts","../../src/react/hooks/useSubscription.tsx","../../src/react/hooks/useCheckout.ts","../../src/react/hooks/useCreditBalance.tsx","../../src/react/hooks/useCreditHistory.tsx","../../src/react/hooks/useStatementQuery.shared.ts","../../src/react/hooks/useStatementQuery.tsx","../../src/react/hooks/usePlanDetailsQuery.shared.ts","../../src/react/hooks/usePlanDetailsQuery.tsx","../../src/react/hooks/usePaymentAttemptQuery.shared.ts","../../src/react/hooks/usePaymentAttemptQuery.tsx","../../src/react/hooks/useUserEnterpriseConnections.shared.ts","../../src/react/hooks/useUserEnterpriseConnections.tsx","../../src/react/hooks/useOrganizationEnterpriseConnections.shared.ts","../../src/react/hooks/useOrganizationEnterpriseConnections.tsx","../../src/react/hooks/useOrganizationDomains.shared.ts","../../src/react/hooks/useOrganizationDomains.tsx","../../src/react/hooks/useOrganizationEnterpriseConnectionTestRuns.shared.ts","../../src/react/hooks/useOrganizationEnterpriseConnectionTestRuns.tsx","../../src/react/utils.ts","../../src/react/ClerkContextProvider.tsx","../../src/react/stripe-react/utils.ts","../../src/react/stripe-react/index.tsx","../../src/react/billing/useInitializePaymentMethod.tsx","../../src/react/billing/useStripeClerkLibs.tsx","../../src/react/billing/useStripeLoader.tsx","../../src/react/billing/payment-element.tsx","../../src/react/PortalProvider.tsx"],"sourcesContent":["'use client';\nimport React from 'react';\n\n/**\n * Assert that the context value exists, otherwise throw an error.\n *\n * @internal\n */\nexport function assertContextExists(contextVal: unknown, msgOrCtx: string | React.Context<any>): asserts contextVal {\n if (!contextVal) {\n throw typeof msgOrCtx === 'string' ? new Error(msgOrCtx) : new Error(`${msgOrCtx.displayName} not found`);\n }\n}\n\ntype Options = { assertCtxFn?: (v: unknown, msg: string) => void };\ntype ContextOf<T> = React.Context<{ value: T } | undefined>;\ntype UseCtxFn<T> = () => T;\n\n/**\n * Create and return a Context and two hooks that return the context value.\n * The Context type is derived from the type passed in by the user.\n *\n * The first hook returned guarantees that the context exists so the returned value is always `CtxValue`\n * The second hook makes no guarantees, so the returned value can be `CtxValue | undefined`\n *\n * @internal\n */\nexport const createContextAndHook = <CtxVal>(\n displayName: string,\n options?: Options,\n): [ContextOf<CtxVal>, UseCtxFn<CtxVal>, UseCtxFn<CtxVal | Partial<CtxVal>>] => {\n const { assertCtxFn = assertContextExists } = options || {};\n const Ctx = React.createContext<{ value: CtxVal } | undefined>(undefined);\n Ctx.displayName = displayName;\n\n const useCtx = () => {\n const ctx = React.useContext(Ctx);\n assertCtxFn(ctx, `${displayName} not found`);\n return (ctx as any).value as CtxVal;\n };\n\n const useCtxWithoutGuarantee = () => {\n const ctx = React.useContext(Ctx);\n return ctx ? ctx.value : {};\n };\n\n return [Ctx, useCtx, useCtxWithoutGuarantee];\n};\n","'use client';\n\nimport type { PropsWithChildren } from 'react';\nimport React, { useState } from 'react';\n\nimport type { BillingSubscriptionPlanPeriod, ClerkOptions, ForPayerType, InitialState, LoadedClerk } from '../types';\nimport { createContextAndHook } from './hooks/createContextAndHook';\n\nconst [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook<LoadedClerk>('ClerkInstanceContext');\n\nconst [InitialStateContext, _useInitialStateContext] = createContextAndHook<\n InitialState | Promise<InitialState> | undefined\n>('InitialStateContext');\n\n/**\n * Provides initial Clerk state (session, user, organization data) from server-side rendering\n * to child components via React context.\n *\n * Passing in a promise is only supported for React >= 19.\n *\n * The initialState is snapshotted on mount and cannot change during the component lifecycle.\n *\n * Note that different parts of the React tree can use separate InitialStateProvider instances\n * with different initialState values if needed.\n */\nexport function InitialStateProvider({\n children,\n initialState,\n}: {\n children: React.ReactNode;\n initialState: InitialState | Promise<InitialState> | undefined;\n}) {\n // The initialState is not allowed to change, we snapshot it to turn that expectation into a guarantee.\n // Note that despite this, it could still be different for different parts of the React tree which is fine,\n // but that requires using a separate provider.\n // eslint-disable-next-line react/hook-use-state\n const [initialStateSnapshot] = useState(initialState);\n const initialStateCtx = React.useMemo(() => ({ value: initialStateSnapshot }), [initialStateSnapshot]);\n return <InitialStateContext.Provider value={initialStateCtx}>{children}</InitialStateContext.Provider>;\n}\n\nexport function useInitialStateContext(): InitialState | undefined {\n const initialState = _useInitialStateContext();\n\n if (initialState instanceof Promise) {\n if ('use' in React && typeof React.use === 'function') {\n return React.use(initialState);\n } else {\n throw new Error('initialState cannot be a promise if React version is less than 19');\n }\n }\n\n return initialState;\n}\n\nconst OptionsContext = React.createContext<ClerkOptions>({});\n\n/**\n * @interface\n */\nexport type UseCheckoutOptions = {\n /**\n * Specifies if the checkout is for an Organization.\n *\n * @default 'user'\n */\n for?: ForPayerType;\n /**\n * The billing period for the Plan.\n */\n planPeriod: BillingSubscriptionPlanPeriod;\n /**\n * The ID of the Subscription Plan to check out (e.g., `cplan_xxx`).\n */\n planId: string;\n /**\n * The number of total seats to check out for\n */\n seatsQuantity?: number;\n /**\n * The specific price ID to check out for, used when the desired price ID is not the current default price\n */\n priceId?: string;\n};\n\nconst [CheckoutContext, useCheckoutContext] = createContextAndHook<UseCheckoutOptions>('CheckoutContext');\n\nconst __experimental_CheckoutProvider = ({ children, ...rest }: PropsWithChildren<UseCheckoutOptions>) => {\n return <CheckoutContext.Provider value={{ value: rest }}>{children}</CheckoutContext.Provider>;\n};\n\n/**\n * @internal\n */\nfunction useOptionsContext(): ClerkOptions {\n const context = React.useContext(OptionsContext);\n if (context === undefined) {\n throw new Error('useOptions must be used within an OptionsContext');\n }\n return context;\n}\n\n/**\n * @internal\n */\nfunction useAssertWrappedByClerkProvider(displayNameOrFn: string | (() => void)): void {\n const ctx = React.useContext(ClerkInstanceContext);\n\n if (!ctx) {\n if (typeof displayNameOrFn === 'function') {\n displayNameOrFn();\n return;\n }\n\n throw new Error(\n `${displayNameOrFn} can only be used within the <ClerkProvider /> component.\n\nPossible fixes:\n1. Ensure that the <ClerkProvider /> is correctly wrapping your application where this component is used.\n2. 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.\n\nLearn more: https://clerk.com/docs/components/clerk-provider`.trim(),\n );\n }\n}\n\nexport {\n __experimental_CheckoutProvider,\n ClerkInstanceContext,\n OptionsContext,\n useAssertWrappedByClerkProvider,\n useCheckoutContext,\n useClerkInstanceContext,\n useOptionsContext,\n};\n","// Keys for `useOrganizationList`\nconst USER_MEMBERSHIPS_KEY = 'userMemberships';\nconst USER_INVITATIONS_KEY = 'userInvitations';\nconst USER_SUGGESTIONS_KEY = 'userSuggestions';\n\n// Keys for `useOrganization`\nconst DOMAINS_KEY = 'domains';\nconst MEMBERSHIP_REQUESTS_KEY = 'membershipRequests';\nconst MEMBERSHIPS_KEY = 'memberships';\nconst INVITATIONS_KEY = 'invitations';\n\n// Keys for `useAPIKeys`\nconst API_KEYS_KEY = 'apiKeys';\n\n// Keys for `useOrganizationCreationDefaults`\nconst ORGANIZATION_CREATION_DEFAULTS_KEY = 'organizationCreationDefaults';\n\n// Keys for `useOAuthConsent`\nconst OAUTH_CONSENT_INFO_KEY = 'oauthConsentInfo';\n\n// Keys for `usePlans`\nconst PLANS_KEY = 'billing-plans';\n\n// Keys for `useSubscription`\nconst SUBSCRIPTION_KEY = 'billing-subscription';\n\n// Keys for `usePaymentMethods`\nconst PAYMENT_METHODS_KEY = 'billing-payment-methods';\n\n// Keys for `usePaymentAttempts`\nconst PAYMENT_ATTEMPTS_KEY = 'billing-payment-attempts';\n\n// Keys for `useStatements`\nconst STATEMENTS_KEY = 'billing-statements';\n\n// Keys for `useCreditBalance`\nconst CREDIT_BALANCE_KEY = 'billing-credit-balance';\n\nexport const STABLE_KEYS = {\n // Keys for `useOrganizationList`\n USER_MEMBERSHIPS_KEY,\n USER_INVITATIONS_KEY,\n USER_SUGGESTIONS_KEY,\n\n // Keys for `useOrganization`\n DOMAINS_KEY,\n MEMBERSHIP_REQUESTS_KEY,\n MEMBERSHIPS_KEY,\n INVITATIONS_KEY,\n\n // Keys for billing\n PLANS_KEY,\n SUBSCRIPTION_KEY,\n PAYMENT_METHODS_KEY,\n PAYMENT_ATTEMPTS_KEY,\n STATEMENTS_KEY,\n\n // Keys for `useAPIKeys`\n API_KEYS_KEY,\n\n // Keys for `useOrganizationCreationDefaults`\n ORGANIZATION_CREATION_DEFAULTS_KEY,\n\n // Keys for `useOAuthConsent`\n OAUTH_CONSENT_INFO_KEY,\n\n // Keys for `useCreditBalance`\n CREDIT_BALANCE_KEY,\n} as const;\n\nexport type ResourceCacheStableKey = (typeof STABLE_KEYS)[keyof typeof STABLE_KEYS];\n\n/**\n * Internal stable keys for queries only used by our UI components.\n * These keys are not used by the hooks themselves.\n */\n\nconst PAYMENT_ATTEMPT_KEY = 'billing-payment-attempt';\nconst BILLING_PLANS_KEY = 'billing-plan';\nconst BILLING_STATEMENTS_KEY = 'billing-statement';\nconst USER_ENTERPRISE_CONNECTIONS_KEY = 'userEnterpriseConnections';\nconst ENTERPRISE_CONNECTION_TEST_RUNS_KEY = 'enterpriseConnectionTestRuns';\nconst ORGANIZATION_ENTERPRISE_CONNECTIONS_KEY = 'organizationEnterpriseConnections';\nconst ORGANIZATION_ENTERPRISE_CONNECTION_TEST_RUNS_KEY = 'organizationEnterpriseConnectionTestRuns';\nconst ORGANIZATION_DOMAINS_KEY = 'organizationDomains';\n\nconst CREDIT_HISTORY_KEY = 'billing-credit-history';\n\nexport const INTERNAL_STABLE_KEYS = {\n PAYMENT_ATTEMPT_KEY,\n BILLING_PLANS_KEY,\n BILLING_STATEMENTS_KEY,\n CREDIT_HISTORY_KEY,\n USER_ENTERPRISE_CONNECTIONS_KEY,\n ENTERPRISE_CONNECTION_TEST_RUNS_KEY,\n ORGANIZATION_ENTERPRISE_CONNECTIONS_KEY,\n ORGANIZATION_ENTERPRISE_CONNECTION_TEST_RUNS_KEY,\n ORGANIZATION_DOMAINS_KEY,\n} as const;\n\nexport type __internal_ResourceCacheStableKey = (typeof INTERNAL_STABLE_KEYS)[keyof typeof INTERNAL_STABLE_KEYS];\n","import type { __internal_ResourceCacheStableKey, ResourceCacheStableKey } from '../stable-keys';\n\n/**\n * @internal\n */\nexport function createCacheKeys<\n Params,\n T extends Record<string, unknown> = Record<string, unknown>,\n U extends Record<string, unknown> | undefined = undefined,\n>(params: {\n stablePrefix: ResourceCacheStableKey | __internal_ResourceCacheStableKey;\n authenticated: boolean;\n tracked: T;\n untracked: U extends { args: Params } ? U : never;\n}) {\n return {\n queryKey: [params.stablePrefix, params.authenticated, params.tracked, params.untracked] as const,\n invalidationKey: [params.stablePrefix, params.authenticated, params.tracked] as const,\n stableKey: params.stablePrefix,\n authenticated: params.authenticated,\n };\n}\n","/**\n * @internal\n */\nexport function defineKeepPreviousDataFn(enabled: boolean) {\n if (enabled) {\n return function KeepPreviousDataFn<Data>(previousData: Data): Data {\n return previousData;\n };\n }\n return undefined;\n}\n","import { QueryClient } from '@tanstack/query-core';\n\n/**\n * The QueryClient backing every clerk-query hook. Owned by `@clerk/shared` so the\n * `QueryObserver` that observes it and the `Query` objects inside it always\n * resolve to the same `@tanstack/query-core` (no cross-bundle drift between\n * the consumer-side `@clerk/shared` and the production CDN `clerk-js` bundle).\n *\n * Lazily instantiated on the client only. Server-side renders return\n * `undefined` so per-request renders never share a cache across requests.\n */\nlet clerkQueryClient: QueryClient | undefined;\nlet initialized = false;\n\nexport function getClerkQueryClient(): QueryClient | undefined {\n if (typeof window === 'undefined') {\n return undefined;\n }\n if (!initialized) {\n clerkQueryClient = new QueryClient();\n initialized = true;\n }\n return clerkQueryClient;\n}\n\n/**\n * Test-only: install a custom client (for deterministic defaults like\n * `staleTime: Infinity`) or pass `undefined` to simulate the \"no client\"\n * state without triggering lazy creation on subsequent reads.\n */\nexport function __setClerkQueryClientForTest(client: QueryClient | undefined): void {\n clerkQueryClient = client;\n initialized = true;\n}\n\n/**\n * Test-only: build and install a fresh `QueryClient` with deterministic\n * defaults (no retries, infinite stale time, no refetching). Returns the\n * client so the spec can read/write its cache directly.\n *\n * Avoids forcing every test consumer to depend on `@tanstack/query-core`.\n */\nexport function __createClerkTestQueryClient(): QueryClient {\n const client = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n },\n },\n });\n __setClerkQueryClientForTest(client);\n return client;\n}\n\n/**\n * Test-only: clear both the override and the initialization flag so the\n * next read lazy-creates a fresh client.\n */\nexport function __resetClerkQueryClientForTest(): void {\n clerkQueryClient = undefined;\n initialized = false;\n}\n","import type { QueryClient } from '@tanstack/query-core';\n\nimport { getClerkQueryClient } from './clerk-query-client';\n\nexport type RecursiveMock = {\n (...args: unknown[]): RecursiveMock;\n} & {\n readonly [key in string | symbol]: RecursiveMock;\n};\n\n/**\n * Creates a recursively self-referential Proxy that safely handles:\n * - Arbitrary property access (e.g., obj.any.prop.path)\n * - Function calls at any level (e.g., obj.a().b.c())\n * - Construction (e.g., new obj.a.b())\n *\n * Always returns itself to allow infinite chaining without throwing.\n */\nfunction createRecursiveProxy(label: string): RecursiveMock {\n // The callable target for the proxy so that `apply` works\n const callableTarget = function noop(): void {};\n\n // eslint-disable-next-line prefer-const\n let self: RecursiveMock;\n const handler: ProxyHandler<typeof callableTarget> = {\n get(_target, prop) {\n // Avoid being treated as a Promise/thenable by test runners or frameworks\n if (prop === 'then') {\n return undefined;\n }\n if (prop === 'toString') {\n return () => `[${label}]`;\n }\n if (prop === Symbol.toPrimitive) {\n return () => 0;\n }\n return self;\n },\n apply() {\n return self;\n },\n construct() {\n return self as unknown as object;\n },\n has() {\n return false;\n },\n set() {\n return false;\n },\n };\n\n self = new Proxy(callableTarget, handler) as unknown as RecursiveMock;\n return self;\n}\n\nconst mockQueryClient = createRecursiveProxy('ClerkMockQueryClient') as unknown as QueryClient;\n\n/**\n * Returns `[client, isLoaded]`. The real client is owned by `@clerk/shared`\n * and lazily instantiated on the browser only — SSR returns the proxy mock\n * + `isLoaded: false` so per-request renders never share a query cache.\n */\nconst useClerkQueryClient = (): [QueryClient, boolean] => {\n const client = getClerkQueryClient();\n return [client ?? mockQueryClient, Boolean(client)];\n};\n\nexport { useClerkQueryClient };\n","/**\n * Stripped down version of useBaseQuery from @tanstack/query-core.\n * This implementation allows for an observer to be created every time a query client changes.\n */\n\n'use client';\nimport type { DefaultedQueryObserverOptions, QueryKey, QueryObserver, QueryObserverResult } from '@tanstack/query-core';\nimport { noop, notifyManager } from '@tanstack/query-core';\nimport * as React from 'react';\n\nimport type { UseBaseQueryOptions } from './types';\nimport { useClerkQueryClient } from './use-clerk-query-client';\n\nexport type DistributivePick<T, K extends PropertyKey> = T extends unknown ? Pick<T, Extract<K, keyof T>> : never;\n\nexport type CommonQueryResult = 'data' | 'error' | 'isLoading' | 'isFetching' | 'status';\n\n/**\n * An alternative `useBaseQuery` implementation that allows for an observer to be created every time a query client changes.\n *\n * @internal\n */\nexport function useBaseQuery<TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey>(\n options: UseBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>,\n Observer: typeof QueryObserver,\n): DistributivePick<QueryObserverResult<TData, TError>, CommonQueryResult> {\n const [client, isQueryClientLoaded] = useClerkQueryClient();\n const defaultedOptions = isQueryClientLoaded\n ? client.defaultQueryOptions(options)\n : (options as DefaultedQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>);\n\n // Make sure results are optimistically set in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = 'optimistic';\n\n const observer = React.useMemo(() => {\n return new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(client, defaultedOptions);\n }, [client]);\n\n // note: this must be called before useSyncExternalStore\n const result = observer.getOptimisticResult(defaultedOptions);\n\n const shouldSubscribe = options.subscribed !== false;\n React.useSyncExternalStore(\n React.useCallback(\n onStoreChange => {\n const unsubscribe = shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop;\n\n // Update result to make sure we did not miss any query updates\n // between creating the observer and subscribing to it.\n observer.updateResult();\n\n return unsubscribe;\n },\n [observer, shouldSubscribe],\n ),\n () => observer.getCurrentResult(),\n () => observer.getCurrentResult(),\n );\n\n React.useEffect(() => {\n observer.setOptions(defaultedOptions);\n }, [defaultedOptions, observer]);\n\n if (!isQueryClientLoaded) {\n // Return a dummy result that matches RQ's pending state until the query client loads\n // (SSR, or on the client before clerk-js finishes bootstrapping it).\n // `isLoading` reflects whether the query *would* run once the client attaches — otherwise\n // consumers see `isLoading: false` with empty data and render a spurious \"no results\" state\n // in the window between clerk.loaded and the query client being ready.\n const isEnabled = options.enabled !== false;\n return {\n data: undefined,\n error: null,\n isLoading: isEnabled,\n isFetching: false,\n status: 'pending',\n };\n }\n\n // Handle result property usage tracking\n return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;\n}\n","import type { DefaultError, InfiniteData, QueryKey, QueryObserver } from '@tanstack/query-core';\nimport { InfiniteQueryObserver } from '@tanstack/query-core';\n\nimport type { DefinedInitialDataInfiniteOptions, UndefinedInitialDataInfiniteOptions } from './infiniteQueryOptions';\nimport type { DefinedUseInfiniteQueryResult, UseInfiniteQueryOptions, UseInfiniteQueryResult } from './types';\nimport { useBaseQuery } from './useBaseQuery';\n\nexport function useClerkInfiniteQuery<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>,\n): DefinedUseInfiniteQueryResult<TData, TError>;\n\nexport function useClerkInfiniteQuery<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>,\n): UseInfiniteQueryResult<TData, TError>;\n\nexport function useClerkInfiniteQuery<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>,\n): UseInfiniteQueryResult<TData, TError>;\n/**\n *\n */\nexport function useClerkInfiniteQuery(options: UseInfiniteQueryOptions) {\n return useBaseQuery(options, InfiniteQueryObserver as unknown as typeof QueryObserver);\n}\n","import type { DefaultError, QueryKey } from '@tanstack/query-core';\nimport { QueryObserver } from '@tanstack/query-core';\n\nimport type { DefinedInitialDataOptions, UndefinedInitialDataOptions } from './queryOptions';\nimport type { DefinedUseQueryResult, UseQueryOptions, UseQueryResult } from './types';\nimport type { CommonQueryResult, DistributivePick } from './useBaseQuery';\nimport { useBaseQuery } from './useBaseQuery';\n\nexport function useClerkQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,\n): DistributivePick<DefinedUseQueryResult<NoInfer<TData>, TError>, CommonQueryResult>;\n\nexport function useClerkQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,\n): DistributivePick<UseQueryResult<NoInfer<TData>, TError>, CommonQueryResult>;\n\nexport function useClerkQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): DistributivePick<UseQueryResult<NoInfer<TData>, TError>, CommonQueryResult>;\n\n/**\n *\n */\nexport function useClerkQuery(options: UseQueryOptions) {\n return useBaseQuery(options, QueryObserver);\n}\n","import { useRef } from 'react';\n\ntype Primitive = string | number | boolean | bigint | symbol | null | undefined;\n\n/**\n * A hook that retains the previous value of a primitive type.\n * It uses a ref to prevent causing unnecessary re-renders.\n *\n * @internal\n *\n * @example\n * ```\n * Render 1: value = 'A' → returns null\n * Render 2: value = 'B' → returns 'A'\n * Render 3: value = 'B' → returns 'A'\n * Render 4: value = 'B' → returns 'A'\n * Render 5: value = 'C' → returns 'B'\n * ```\n */\nexport function usePreviousValue<T extends Primitive>(value: T) {\n const currentRef = useRef(value);\n const previousRef = useRef<T | null>(null);\n\n if (currentRef.current !== value) {\n previousRef.current = currentRef.current;\n currentRef.current = value;\n }\n\n return previousRef.current;\n}\n","import { useEffect, useRef } from 'react';\n\nimport { useClerkQueryClient } from '../query/use-clerk-query-client';\nimport { usePreviousValue } from './usePreviousValue';\n\nexport const withInfiniteKey = <T extends string>(key: T) => [key, `${key}-inf`] as const;\n\ntype ClearQueriesOnSignOutOptions = {\n isSignedOut: boolean;\n stableKeys: string | readonly string[];\n /**\n * Whether the queries for this hook are keyed as authenticated.\n * If this is not `true`, the effect becomes a no-op.\n */\n authenticated?: boolean;\n /**\n * Optional callback that will run after queries are cleared on sign-out.\n */\n onCleanup?: () => void;\n};\n\n/**\n * Clears React Query caches associated with the given stable prefixes when\n * the authenticated state transitions from signed-in to signed-out.\n *\n * @internal\n */\nexport function useClearQueriesOnSignOut(options: ClearQueriesOnSignOutOptions) {\n const { isSignedOut, stableKeys, authenticated = true, onCleanup } = options;\n const stableKeysRef = useRef(stableKeys);\n\n const [queryClient] = useClerkQueryClient();\n const previousIsSignedIn = usePreviousValue(!isSignedOut);\n\n useEffect(() => {\n // If this hook's cache keys are not authenticated, skip all cleanup logic.\n if (authenticated !== true) {\n return;\n }\n\n const isNowSignedOut = isSignedOut === true;\n\n if (previousIsSignedIn && isNowSignedOut) {\n queryClient.removeQueries({\n predicate: query => {\n const [cachedStableKey, queryAuthenticated] = query.queryKey;\n\n return (\n queryAuthenticated === true &&\n typeof cachedStableKey === 'string' &&\n (Array.isArray(stableKeysRef.current)\n ? stableKeysRef.current.includes(cachedStableKey)\n : stableKeysRef.current === cachedStableKey)\n );\n },\n });\n\n onCleanup?.();\n }\n }, [authenticated, isSignedOut, previousIsSignedIn, queryClient]);\n}\n","import { useRef } from 'react';\n\nimport type { PagesOrInfiniteOptions } from '../types';\n\n/**\n * A hook that safely merges user-provided pagination options with default values.\n * It caches initial pagination values (page and size) until component unmount to prevent unwanted rerenders.\n *\n * @internal\n *\n * @example\n * ```typescript\n * // Example 1: With user-provided options\n * const userOptions = { initialPage: 2, pageSize: 20, infinite: true };\n * const defaults = { initialPage: 1, pageSize: 10, infinite: false };\n * useWithSafeValues(userOptions, defaults);\n * // Returns { initialPage: 2, pageSize: 20, infinite: true }\n *\n * // Example 2: With boolean true (use defaults)\n * const params = true;\n * const defaults = { initialPage: 1, pageSize: 10, infinite: false };\n * useWithSafeValues(params, defaults);\n * // Returns { initialPage: 1, pageSize: 10, infinite: false }\n *\n * // Example 3: With undefined options (fallback to defaults)\n * const params = undefined;\n * const defaults = { initialPage: 1, pageSize: 10, infinite: false };\n * useWithSafeValues(params, defaults);\n * // Returns { initialPage: 1, pageSize: 10, infinite: false }\n * ```\n */\nexport const useWithSafeValues = <T extends PagesOrInfiniteOptions>(params: T | true | undefined, defaultValues: T) => {\n const shouldUseDefaults = typeof params === 'boolean' && params;\n\n // Cache initialPage and initialPageSize until unmount\n const initialPageRef = useRef(\n shouldUseDefaults ? defaultValues.initialPage : (params?.initialPage ?? defaultValues.initialPage),\n );\n const pageSizeRef = useRef(shouldUseDefaults ? defaultValues.pageSize : (params?.pageSize ?? defaultValues.pageSize));\n\n const newObj: Record<string, unknown> = {};\n for (const key of Object.keys(defaultValues)) {\n // @ts-ignore - indexing into generic param to preserve unknown keys from defaults/params\n newObj[key] = shouldUseDefaults ? defaultValues[key] : (params?.[key] ?? defaultValues[key]);\n }\n\n return {\n ...newObj,\n initialPage: initialPageRef.current,\n pageSize: pageSizeRef.current,\n } as T;\n};\n\n/**\n * Returns an object containing only the keys from the first object that are not present in the second object.\n * Useful for extracting unique parameters that should be passed to a request while excluding common cache keys.\n *\n * @internal\n *\n * @example\n * ```typescript\n * // Example 1: Basic usage\n * const obj1 = { name: 'John', age: 30, city: 'NY' };\n * const obj2 = { name: 'John', age: 30 };\n * getDifferentKeys(obj1, obj2); // Returns { city: 'NY' }\n *\n * // Example 2: With cache keys\n * const requestParams = { page: 1, limit: 10, userId: '123' };\n * const cacheKeys = { userId: '123' };\n * getDifferentKeys(requestParams, cacheKeys); // Returns { page: 1, limit: 10 }\n * ```\n */\nexport function getDifferentKeys(\n obj1: Record<string, unknown>,\n obj2: Record<string, unknown>,\n): Record<string, unknown> {\n const keysSet = new Set(Object.keys(obj2));\n const differentKeysObject: Record<string, unknown> = {};\n\n for (const key1 of Object.keys(obj1)) {\n if (!keysSet.has(key1)) {\n differentKeysObject[key1] = obj1[key1];\n }\n }\n\n return differentKeysObject;\n}\n\n/**\n * Calculates the offset count for pagination based on initial page and page size.\n * This represents the number of items to skip before the first page.\n *\n * @param initialPage - The starting page number (1-based)\n * @param pageSize - The number of items per page\n * @returns The number of items to offset\n *\n * @example\n * ```typescript\n * calculateOffsetCount(1, 10); // Returns 0 (no offset for first page)\n * calculateOffsetCount(2, 10); // Returns 10 (skip first 10 items)\n * calculateOffsetCount(3, 20); // Returns 40 (skip first 40 items)\n * ```\n */\nexport function calculateOffsetCount(initialPage: number, pageSize: number): number {\n return (initialPage - 1) * pageSize;\n}\n\n/**\n * Calculates the total number of pages based on total count, offset, and page size.\n *\n * @param totalCount - The total number of items\n * @param offsetCount - The number of items to offset (from calculateOffsetCount)\n * @param pageSize - The number of items per page\n * @returns The total number of pages\n *\n * @example\n * ```typescript\n * calculatePageCount(100, 0, 10); // Returns 10\n * calculatePageCount(95, 0, 10); // Returns 10 (rounds up)\n * calculatePageCount(100, 20, 10); // Returns 8 (100 - 20 = 80 items, 8 pages)\n * ```\n */\nexport function calculatePageCount(totalCount: number, offsetCount: number, pageSize: number): number {\n return Math.ceil((totalCount - offsetCount) / pageSize);\n}\n\n/**\n * Determines if there is a next page available in non-infinite pagination mode.\n *\n * @param totalCount - The total number of items\n * @param offsetCount - The number of items to offset\n * @param currentPage - The current page number (1-based)\n * @param pageSize - The number of items per page\n * @returns True if there are more items beyond the current page\n *\n * @example\n * ```typescript\n * calculateHasNextPage(100, 0, 1, 10); // Returns true (page 1 of 10)\n * calculateHasNextPage(100, 0, 10, 10); // Returns false (last page)\n * calculateHasNextPage(25, 0, 2, 10); // Returns true (page 2, 5 more items)\n * calculateHasNextPage(20, 0, 2, 10); // Returns false (exactly 2 pages)\n * ```\n */\nexport function calculateHasNextPage(\n totalCount: number,\n offsetCount: number,\n currentPage: number,\n pageSize: number,\n): boolean {\n return totalCount - offsetCount > currentPage * pageSize;\n}\n\n/**\n * Determines if there is a previous page available in non-infinite pagination mode.\n *\n * @param currentPage - The current page number (1-based)\n * @param pageSize - The number of items per page\n * @param offsetCount - The number of items to offset\n * @returns True if there are pages before the current page\n *\n * @example\n * ```typescript\n * calculateHasPreviousPage(1, 10, 0); // Returns false (first page)\n * calculateHasPreviousPage(2, 10, 0); // Returns true (can go back to page 1)\n * calculateHasPreviousPage(1, 10, 10); // Returns false (first page with offset)\n * ```\n */\nexport function calculateHasPreviousPage(currentPage: number, pageSize: number, offsetCount: number): boolean {\n return (currentPage - 1) * pageSize > offsetCount;\n}\n","import { useCallback, useMemo, useRef, useState } from 'react';\n\nimport type { ClerkPaginatedResponse } from '../../types';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQueryClient } from '../query/use-clerk-query-client';\nimport { useClerkInfiniteQuery } from '../query/useInfiniteQuery';\nimport { useClerkQuery } from '../query/useQuery';\nimport type { CacheSetter, ValueOrSetter } from '../types';\nimport { useClearQueriesOnSignOut, withInfiniteKey } from './useClearQueriesOnSignOut';\nimport type { UsePagesOrInfiniteSignature } from './usePageOrInfinite.types';\nimport {\n calculateHasNextPage,\n calculateHasPreviousPage,\n calculateOffsetCount,\n calculatePageCount,\n useWithSafeValues,\n} from './usePagesOrInfinite.shared';\n\nexport const usePagesOrInfinite: UsePagesOrInfiniteSignature = params => {\n const { fetcher, config, keys } = params;\n\n const [paginatedPage, setPaginatedPage] = useState(config.initialPage ?? 1);\n\n // Cache initialPage and initialPageSize until unmount\n const initialPageRef = useRef(config.initialPage ?? 1);\n const pageSizeRef = useRef(config.pageSize ?? 10);\n\n const enabled = config.enabled ?? true;\n const isSignedIn = config.isSignedIn;\n const triggerInfinite = config.infinite ?? false;\n const cacheMode = config.__experimental_mode === 'cache';\n const keepPreviousData = config.keepPreviousData ?? false;\n\n const [queryClient] = useClerkQueryClient();\n\n // Compute the actual enabled state for queries (considering all conditions)\n const queriesEnabled = enabled && Boolean(fetcher) && !cacheMode && isSignedIn !== false;\n\n // Force re-render counter for cache-only updates\n const [forceUpdateCounter, setForceUpdateCounter] = useState(0);\n const forceUpdate = useCallback((updater: (n: number) => number) => {\n setForceUpdateCounter(updater);\n }, []);\n\n // Non-infinite mode: single page query\n const pagesQueryKey = useMemo(() => {\n const [stablePrefix, authenticated, tracked, untracked] = keys.queryKey;\n\n return [\n stablePrefix,\n authenticated,\n tracked,\n {\n ...untracked,\n args: {\n ...untracked.args,\n initialPage: paginatedPage,\n pageSize: pageSizeRef.current,\n },\n },\n ] as const;\n }, [keys.queryKey, paginatedPage]);\n\n const singlePageQuery = useClerkQuery({\n queryKey: pagesQueryKey,\n queryFn: ({ queryKey }) => {\n const { args } = queryKey[3];\n\n if (!fetcher) {\n return undefined as any;\n }\n\n return fetcher(args);\n },\n staleTime: 60_000,\n enabled: queriesEnabled && !triggerInfinite,\n // Use placeholderData to keep previous data while fetching new page\n placeholderData: defineKeepPreviousDataFn(keepPreviousData),\n });\n\n // Infinite mode: accumulate pages\n const infiniteQueryKey = useMemo(() => {\n const [stablePrefix, authenticated, tracked, untracked] = keys.queryKey;\n\n return [stablePrefix + '-inf', authenticated, tracked, untracked] as const;\n }, [keys.queryKey]);\n\n const infiniteQuery = useClerkInfiniteQuery<ClerkPaginatedResponse<any>, any, any, typeof infiniteQueryKey, any>({\n queryKey: infiniteQueryKey,\n initialPageParam: config.initialPage ?? 1,\n getNextPageParam: (lastPage, allPages, lastPageParam) => {\n const total = lastPage?.total_count ?? 0;\n const consumed = (allPages.length + (config.initialPage ? config.initialPage - 1 : 0)) * (config.pageSize ?? 10);\n return consumed < total ? (lastPageParam as number) + 1 : undefined;\n },\n queryFn: ({ pageParam, queryKey }) => {\n const { args } = queryKey[3];\n if (!fetcher) {\n return undefined as any;\n }\n return fetcher({ ...args, initialPage: pageParam, pageSize: pageSizeRef.current });\n },\n staleTime: 60_000,\n enabled: queriesEnabled && triggerInfinite,\n });\n\n useClearQueriesOnSignOut({\n isSignedOut: isSignedIn === false,\n authenticated: keys.authenticated,\n stableKeys: withInfiniteKey(keys.stableKey),\n onCleanup: () => {\n // Reset paginated page to initial\n setPaginatedPage(initialPageRef.current);\n\n // Force re-render to reflect cache changes\n void Promise.resolve().then(() => forceUpdate(n => n + 1));\n },\n });\n\n // Compute data, count and page from the same data source to ensure consistency\n const computedValues = useMemo(() => {\n if (triggerInfinite) {\n // Read from query data first, fallback to cache\n const cachedData = queryClient.getQueryData<{ pages?: Array<ClerkPaginatedResponse<any>> }>(infiniteQueryKey);\n const pages = queriesEnabled ? (infiniteQuery.data?.pages ?? cachedData?.pages ?? []) : (cachedData?.pages ?? []);\n\n // Ensure pages is always an array and filter out null/undefined pages\n const validPages = Array.isArray(pages) ? pages.filter(Boolean) : [];\n\n return {\n data:\n validPages\n .map((a: ClerkPaginatedResponse<any>) => a?.data)\n .flat()\n .filter(Boolean) ?? [],\n count: validPages[validPages.length - 1]?.total_count ?? 0,\n page: validPages.length > 0 ? validPages.length : initialPageRef.current,\n };\n }\n\n // When query is disabled (via enabled flag), the hook's data is stale, so only read from cache\n // This ensures that after cache clearing, we return consistent empty state\n const pageData = queriesEnabled\n ? (singlePageQuery.data ?? queryClient.getQueryData<ClerkPaginatedResponse<any>>(pagesQueryKey))\n : queryClient.getQueryData<ClerkPaginatedResponse<any>>(pagesQueryKey);\n\n return {\n data: Array.isArray(pageData?.data) ? pageData.data : [],\n count: typeof pageData?.total_count === 'number' ? pageData.total_count : 0,\n page: paginatedPage,\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps -- forceUpdateCounter is used to trigger re-renders for cache updates\n }, [\n queriesEnabled,\n forceUpdateCounter,\n triggerInfinite,\n infiniteQuery.data?.pages,\n singlePageQuery.data,\n queryClient,\n infiniteQueryKey,\n pagesQueryKey,\n paginatedPage,\n ]);\n\n const { data, count, page } = computedValues;\n\n const fetchPage: ValueOrSetter<number> = useCallback(\n numberOrgFn => {\n if (triggerInfinite) {\n const next = typeof numberOrgFn === 'function' ? (numberOrgFn as (n: number) => number)(page) : numberOrgFn;\n const targetCount = Math.max(0, next);\n const cachedData = queryClient.getQueryData<{ pages?: Array<ClerkPaginatedResponse<any>> }>(infiniteQueryKey);\n const pages = infiniteQuery.data?.pages ?? cachedData?.pages ?? [];\n const currentCount = pages.length;\n const toFetch = targetCount - currentCount;\n if (toFetch > 0) {\n void infiniteQuery.fetchNextPage({ cancelRefetch: false });\n }\n return;\n }\n return setPaginatedPage(numberOrgFn);\n },\n [infiniteQuery, page, triggerInfinite, queryClient, infiniteQueryKey],\n );\n\n const isLoading = triggerInfinite ? infiniteQuery.isLoading : singlePageQuery.isLoading;\n const isFetching = triggerInfinite ? infiniteQuery.isFetching : singlePageQuery.isFetching;\n const error = (triggerInfinite ? infiniteQuery.error : singlePageQuery.error) ?? null;\n const isError = !!error;\n\n const fetchNext = useCallback(() => {\n if (triggerInfinite) {\n void infiniteQuery.fetchNextPage({ cancelRefetch: false });\n return;\n }\n setPaginatedPage(n => Math.max(0, n + 1));\n }, [infiniteQuery, triggerInfinite]);\n\n const fetchPrevious = useCallback(() => {\n if (triggerInfinite) {\n // not natively supported by forward-only pagination; noop\n return;\n }\n setPaginatedPage(n => Math.max(0, n - 1));\n }, [triggerInfinite]);\n\n const offsetCount = calculateOffsetCount(initialPageRef.current, pageSizeRef.current);\n const pageCount = calculatePageCount(count, offsetCount, pageSizeRef.current);\n const hasNextPage = triggerInfinite\n ? Boolean(infiniteQuery.hasNextPage)\n : calculateHasNextPage(count, offsetCount, page, pageSizeRef.current);\n const hasPreviousPage = triggerInfinite\n ? Boolean(infiniteQuery.hasPreviousPage)\n : calculateHasPreviousPage(page, pageSizeRef.current, offsetCount);\n\n const setData: CacheSetter = value => {\n if (triggerInfinite) {\n queryClient.setQueryData(infiniteQueryKey, (prevValue: any = {}) => {\n const prevPages = Array.isArray(prevValue?.pages) ? prevValue.pages : [];\n const nextPages = (typeof value === 'function' ? value(prevPages) : value) as Array<\n ClerkPaginatedResponse<any>\n >;\n return { ...prevValue, pages: nextPages };\n });\n // Force immediate re-render to reflect cache changes\n forceUpdate(n => n + 1);\n return Promise.resolve();\n }\n queryClient.setQueryData(pagesQueryKey, (prevValue: any = { data: [], total_count: 0 }) => {\n const nextValue = (typeof value === 'function' ? value(prevValue) : value) as ClerkPaginatedResponse<any>;\n return nextValue;\n });\n // Force re-render to reflect cache changes\n forceUpdate(n => n + 1);\n return Promise.resolve();\n };\n\n const revalidate = async () => {\n await queryClient.invalidateQueries({ queryKey: keys.invalidationKey });\n const [stablePrefix, ...rest] = keys.invalidationKey;\n return queryClient.invalidateQueries({ queryKey: [stablePrefix + '-inf', ...rest] });\n };\n\n return {\n data,\n count,\n error,\n isLoading,\n isFetching,\n isError,\n page,\n pageCount,\n fetchPage,\n fetchNext,\n fetchPrevious,\n hasNextPage,\n hasPreviousPage,\n revalidate: revalidate as any,\n setData: setData as any,\n };\n};\n\nexport { useWithSafeValues };\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { APIKeyResource, GetAPIKeysParams } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport type { PaginatedHookConfig, PaginatedResources } from '../types';\nimport { createCacheKeys } from './createCacheKeys';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @interface\n */\nexport type UseAPIKeysParams = PaginatedHookConfig<\n GetAPIKeysParams & {\n /**\n * If `true`, a request will be triggered when the hook is mounted.\n *\n * @default true\n */\n enabled?: boolean;\n }\n>;\n\n/**\n * @interface\n */\nexport type UseAPIKeysReturn<T extends UseAPIKeysParams> = PaginatedResources<\n APIKeyResource,\n T extends { infinite: true } ? true : false\n>;\n\n/**\n * The `useAPIKeys()` hook provides access to paginated API keys for the current user or organization.\n *\n * @example\n * ### Basic usage with default pagination\n *\n * ```tsx\n * const { data, isLoading, page, pageCount, fetchNext, fetchPrevious } = useAPIKeys({\n * subject: 'user_123',\n * pageSize: 10,\n * initialPage: 1,\n * });\n * ```\n *\n * @example\n * ### With search query\n *\n * ```tsx\n * const [searchValue, setSearchValue] = useState('');\n * const debouncedSearch = useDebounce(searchValue, 500);\n *\n * const { data, isLoading } = useAPIKeys({\n * subject: 'user_123',\n * query: debouncedSearch.trim(),\n * pageSize: 10,\n * });\n * ```\n *\n * @example\n * ### Infinite scroll\n *\n * ```tsx\n * const { data, isLoading, fetchNext, hasNextPage } = useAPIKeys({\n * subject: 'user_123',\n * infinite: true,\n * });\n * ```\n */\nexport function useAPIKeys<T extends UseAPIKeysParams>(params?: T): UseAPIKeysReturn<T> {\n useAssertWrappedByClerkProvider('useAPIKeys');\n\n const safeValues = useWithSafeValues(params, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n subject: '',\n query: '',\n enabled: true,\n } as UseAPIKeysParams);\n\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled('useAPIKeys'));\n\n const hookParams: GetAPIKeysParams = {\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n ...(safeValues.subject ? { subject: safeValues.subject } : {}),\n ...(safeValues.query ? { query: safeValues.query } : {}),\n };\n\n const isEnabled = (safeValues.enabled ?? true) && clerk.loaded;\n\n return usePagesOrInfinite({\n fetcher: clerk.apiKeys?.getAll\n ? (params: GetAPIKeysParams) => clerk.apiKeys.getAll({ ...params, subject: safeValues.subject })\n : undefined,\n config: {\n keepPreviousData: safeValues.keepPreviousData,\n infinite: safeValues.infinite,\n enabled: isEnabled,\n isSignedIn: clerk.user !== null,\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.API_KEYS_KEY,\n authenticated: true,\n tracked: {\n subject: safeValues.subject,\n },\n untracked: {\n args: hookParams,\n },\n }),\n }) as UseAPIKeysReturn<T>;\n}\n","import { useCallback, useSyncExternalStore } from 'react';\n\nimport type { UserResource } from '@/types';\n\nimport { useClerkInstanceContext, useInitialStateContext } from '../../contexts';\n\nexport function useUserBase(): UserResource | null | undefined {\n const clerk = useClerkInstanceContext();\n const initialState = useInitialStateContext();\n const getInitialState = useCallback(() => initialState?.user, [initialState?.user]);\n\n const user = useSyncExternalStore(\n useCallback(\n callback => {\n return clerk.addListener(callback, { skipInitialEmit: true });\n },\n [clerk],\n ),\n useCallback(() => {\n if (!clerk.loaded || !clerk.__internal_lastEmittedResources) {\n return getInitialState();\n }\n return clerk.__internal_lastEmittedResources.user;\n }, [clerk, getInitialState]),\n getInitialState,\n );\n\n return user;\n}\n","import { useMemo } from 'react';\n\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function useOAuthConsentCacheKeys(params: {\n userId: string | null;\n oauthClientId: string;\n scope?: string;\n redirectUri?: string;\n}) {\n const { userId, oauthClientId, scope, redirectUri } = params;\n return useMemo(() => {\n const args = {\n oauthClientId,\n ...(scope !== undefined && { scope }),\n ...(redirectUri !== undefined && { redirectUri }),\n };\n return createCacheKeys({\n stablePrefix: STABLE_KEYS.OAUTH_CONSENT_INFO_KEY,\n authenticated: true,\n tracked: {\n userId: userId ?? null,\n },\n untracked: {\n args,\n },\n });\n }, [userId, oauthClientId, scope, redirectUri]);\n}\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { LoadedClerk } from '../../types/clerk';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQuery } from '../query/useQuery';\nimport { useUserBase } from './base/useUserBase';\nimport { useOAuthConsentCacheKeys } from './useOAuthConsent.shared';\nimport type { UseOAuthConsentParams, UseOAuthConsentReturn } from './useOAuthConsent.types';\n\nconst HOOK_NAME = 'useOAuthConsent';\n\n/**\n * The `useOAuthConsent()` hook loads OAuth application consent metadata for the **signed-in** user\n * (`GET /me/oauth/consent/{oauthClientId}`). Ensure the user is authenticated before relying on this hook\n * (e.g., redirect to sign-in on your custom consent route).\n *\n * @example\n * ```tsx\n * import { useOAuthConsent } from '@clerk/react/internal'\n *\n * const { data, isLoading, error } = useOAuthConsent({\n * oauthClientId: clientIdFromProps,\n * scope: scopeFromProps,\n * })\n * ```\n */\nexport function useOAuthConsent(params: UseOAuthConsentParams): UseOAuthConsentReturn {\n useAssertWrappedByClerkProvider(HOOK_NAME);\n\n const { oauthClientId: oauthClientIdParam, scope, redirectUri, keepPreviousData = true, enabled = true } = params;\n const clerk = useClerkInstanceContext();\n const user = useUserBase();\n\n const oauthClientId = (oauthClientIdParam ?? '').trim();\n\n clerk.telemetry?.record(eventMethodCalled(HOOK_NAME));\n\n const { queryKey } = useOAuthConsentCacheKeys({\n userId: user?.id ?? null,\n oauthClientId,\n scope,\n redirectUri,\n });\n\n const hasClientId = oauthClientId.length > 0;\n const queryEnabled = Boolean(user) && hasClientId && enabled && clerk.loaded;\n\n const query = useClerkQuery({\n queryKey,\n queryFn: () => fetchConsentInfo(clerk, { oauthClientId, scope, redirectUri }),\n enabled: queryEnabled,\n placeholderData: defineKeepPreviousDataFn(keepPreviousData && queryEnabled),\n });\n\n return {\n data: query.data,\n error: (query.error ?? null) as UseOAuthConsentReturn['error'],\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n };\n}\n\nfunction fetchConsentInfo(clerk: LoadedClerk, params: { oauthClientId: string; scope?: string; redirectUri?: string }) {\n return clerk.oauthApplication.getConsentInfo(params);\n}\n","import { useCallback, useSyncExternalStore } from 'react';\n\nimport type { OrganizationResource } from '@/types';\n\nimport { useClerkInstanceContext, useInitialStateContext } from '../../contexts';\n\nexport function useOrganizationBase(): OrganizationResource | null | undefined {\n const clerk = useClerkInstanceContext();\n const initialState = useInitialStateContext();\n\n const getInitialState = useCallback(() => initialState?.organization, [initialState?.organization]);\n\n const organization = useSyncExternalStore(\n useCallback(callback => clerk.addListener(callback, { skipInitialEmit: true }), [clerk]),\n useCallback(() => {\n if (!clerk.loaded || !clerk.__internal_lastEmittedResources) {\n return getInitialState();\n }\n return clerk.__internal_lastEmittedResources.organization;\n }, [clerk, getInitialState]),\n getInitialState,\n );\n\n return organization;\n}\n","import { useCallback, useSyncExternalStore } from 'react';\n\nimport { deriveFromSsrInitialState } from '@/deriveState';\nimport type { SignedInSessionResource } from '@/types';\n\nimport { useClerkInstanceContext, useInitialStateContext } from '../../contexts';\n\nexport function useSessionBase(): SignedInSessionResource | null | undefined {\n const clerk = useClerkInstanceContext();\n const initialState = useInitialStateContext();\n const getInitialState = useCallback(() => {\n return initialState ? deriveFromSsrInitialState(initialState)?.session : undefined;\n }, [initialState]);\n\n const session = useSyncExternalStore(\n useCallback(callback => clerk.addListener(callback, { skipInitialEmit: true }), [clerk]),\n useCallback(() => {\n if (!clerk.loaded || !clerk.__internal_lastEmittedResources) {\n return getInitialState();\n }\n return clerk.__internal_lastEmittedResources.session;\n }, [clerk, getInitialState]),\n getInitialState,\n );\n\n return session;\n}\n","import type { LoadedClerk } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\n\n/**\n * > [!WARNING]\n * > 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.\n *\n * 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.\n *\n * @function\n *\n * @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).\n *\n * @example\n *\n * 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#sign-in) method to open the sign-in modal.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useClerk } from '@clerk/react'\n *\n * export default function Home() {\n * const clerk = useClerk()\n *\n * return <button onClick={() => clerk.openSignIn({})}>Sign in</button>\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * ```tsx {{ filename: 'app/page.tsx' }}\n * 'use client';\n *\n * import { useClerk } from '@clerk/nextjs';\n *\n * export default function HomePage() {\n * const clerk = useClerk();\n *\n * return <button onClick={() => clerk.openSignIn({})}>Sign in</button>;\n * }\n * ```\n *\n * </Tab>\n * </Tabs>\n */\nexport const useClerk = (): LoadedClerk => {\n useAssertWrappedByClerkProvider('useClerk');\n return useClerkInstanceContext();\n};\n","import { useEffect, useRef } from 'react';\n\nimport { useClerk } from './useClerk';\n\n/**\n * Attempts to enable the organizations environment setting for a given caller\n *\n * @internal\n */\nexport function useAttemptToEnableOrganizations(caller: 'useOrganization' | 'useOrganizationList') {\n const clerk = useClerk();\n const hasAttempted = useRef(false);\n\n useEffect(() => {\n // Guard to not run this effect twice on Clerk resource update\n if (hasAttempted.current) {\n return;\n }\n\n hasAttempted.current = true;\n // Optional chaining is important for `@clerk/clerk-react` usage with older clerk-js versions that don't have the method\n clerk.__internal_attemptToEnableEnvironmentSetting?.({\n for: 'organizations',\n caller,\n });\n }, [clerk, caller]);\n}\n","import { getCurrentOrganizationMembership } from '../../organization';\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type {\n GetDomainsParams,\n GetInvitationsParams,\n GetMembershipRequestParams,\n GetMembersParams,\n OrganizationDomainResource,\n OrganizationInvitationResource,\n OrganizationMembershipRequestResource,\n OrganizationMembershipResource,\n OrganizationResource,\n} from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport type { PaginatedHookConfig, PaginatedResources, PaginatedResourcesWithDefault } from '../types';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useSessionBase } from './base/useSessionBase';\nimport { createCacheKeys } from './createCacheKeys';\nimport { useAttemptToEnableOrganizations } from './useAttemptToEnableOrganizations';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @interface\n */\nexport type UseOrganizationParams = {\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`enrollmentMode`: A string that filters the domains by the provided [enrollment mode](https://clerk.com/docs/guides/organizations/add-members/verified-domains#enable-verified-domains).</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n domains?: true | PaginatedHookConfig<GetDomainsParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`status`: A string that filters the membership requests by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n membershipRequests?: true | PaginatedHookConfig<GetMembershipRequestParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`role`: An array of [`OrganizationCustomRoleKey`](https://clerk.com/docs/reference/types/organization-custom-role-key).</li>\n * <li>`query`: A string that filters the memberships by the provided string.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n memberships?: true | PaginatedHookConfig<GetMembersParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n * <ul>\n * <li>`status`: A string that filters the invitations by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n invitations?: true | PaginatedHookConfig<GetInvitationsParams>;\n};\n\n/**\n * @interface\n */\nexport type UseOrganizationReturn<T extends UseOrganizationParams> =\n | {\n /**\n * Indicates whether Clerk has loaded the current authentication state. Initially `false`, becomes `true` once Clerk loads, and can revert to `false` while auth state is updating (e.g., when switching organizations via [`setActive()`](https://clerk.com/docs/reference/objects/clerk#set-active)).\n */\n isLoaded: false;\n /**\n * The currently Active Organization.\n */\n organization: undefined;\n /**\n * The current Organization membership.\n */\n membership: undefined;\n /**\n * Includes a paginated list of the Organization's domains.\n */\n domains: PaginatedResourcesWithDefault<OrganizationDomainResource>;\n /**\n * Includes a paginated list of the Organization's membership requests.\n */\n membershipRequests: PaginatedResourcesWithDefault<OrganizationMembershipRequestResource>;\n /**\n * Includes a paginated list of the Organization's memberships.\n */\n memberships: PaginatedResourcesWithDefault<OrganizationMembershipResource>;\n /**\n * Includes a paginated list of the Organization's invitations.\n */\n invitations: PaginatedResourcesWithDefault<OrganizationInvitationResource>;\n }\n | {\n isLoaded: true;\n organization: OrganizationResource;\n membership: undefined;\n domains: PaginatedResourcesWithDefault<OrganizationDomainResource>;\n membershipRequests: PaginatedResourcesWithDefault<OrganizationMembershipRequestResource>;\n memberships: PaginatedResourcesWithDefault<OrganizationMembershipResource>;\n invitations: PaginatedResourcesWithDefault<OrganizationInvitationResource>;\n }\n | {\n isLoaded: boolean;\n organization: OrganizationResource | null;\n membership: OrganizationMembershipResource | null | undefined;\n domains: PaginatedResources<\n OrganizationDomainResource,\n T['membershipRequests'] extends { infinite: true } ? true : false\n > | null;\n membershipRequests: PaginatedResources<\n OrganizationMembershipRequestResource,\n T['membershipRequests'] extends { infinite: true } ? true : false\n > | null;\n memberships: PaginatedResources<\n OrganizationMembershipResource,\n T['memberships'] extends { infinite: true } ? true : false\n > | null;\n invitations: PaginatedResources<\n OrganizationInvitationResource,\n T['invitations'] extends { infinite: true } ? true : false\n > | null;\n };\n\nconst undefinedPaginatedResource = {\n data: undefined,\n count: undefined,\n error: undefined,\n isLoading: false,\n isFetching: false,\n isError: false,\n page: undefined,\n pageCount: undefined,\n fetchPage: undefined,\n fetchNext: undefined,\n fetchPrevious: undefined,\n hasNextPage: false,\n hasPreviousPage: false,\n revalidate: undefined,\n setData: undefined,\n} as const;\n\n/**\n * The `useOrganization()` hook retrieves attributes of the currently Active Organization.\n *\n * @example\n * ### Expand and paginate attributes\n *\n * 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.\n *\n * ```tsx\n * // invitations.data will never be populated.\n * const { invitations } = useOrganization()\n *\n * // Use default values to fetch invitations, such as initialPage = 1 and pageSize = 10\n * const { invitations } = useOrganization({\n * invitations: true,\n * })\n *\n * // Pass your own values to fetch invitations\n * const { invitations } = useOrganization({\n * invitations: {\n * pageSize: 20,\n * initialPage: 2, // skips the first page\n * },\n * })\n *\n * // Aggregate pages in order to render an infinite list\n * const { invitations } = useOrganization({\n * invitations: {\n * infinite: true,\n * },\n * })\n * ```\n *\n * @example\n * ### Infinite pagination\n *\n * 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.\n *\n * ```tsx\n * import { useOrganization } from '@clerk/react'\n *\n * export default function MemberList() {\n * const { memberships } = useOrganization({\n * memberships: {\n * infinite: true, // Append new data to the existing list\n * keepPreviousData: true, // Persist the cached data until the new data has been fetched\n * },\n * })\n *\n * if (!memberships) {\n * // Handle loading state\n * return null\n * }\n *\n * return (\n * <div>\n * <h2>Organization members</h2>\n * <ul>\n * {memberships.data?.map((membership) => (\n * <li key={membership.id}>\n * {membership.publicUserData.firstName} {membership.publicUserData.lastName} <\n * {membership.publicUserData.identifier}> :: {membership.role}\n * </li>\n * ))}\n * </ul>\n *\n * <button\n * disabled={!memberships.hasNextPage} // Disable the button if there are no more available pages to be fetched\n * onClick={memberships.fetchNext}\n * >\n * Load more\n * </button>\n * </div>\n * )\n * }\n * ```\n *\n * @example\n * ### Simple pagination\n *\n * 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.\n *\n * Notice the difference between this example's pagination and the infinite pagination example above.\n *\n * ```tsx\n * import { useOrganization } from '@clerk/react'\n *\n * export default function MemberList() {\n * const { memberships } = useOrganization({\n * memberships: {\n * keepPreviousData: true, // Persist the cached data until the new data has been fetched\n * },\n * })\n *\n * if (!memberships) {\n * // Handle loading state\n * return null\n * }\n *\n * return (\n * <div>\n * <h2>Organization members</h2>\n * <ul>\n * {memberships.data?.map((membership) => (\n * <li key={membership.id}>\n * {membership.publicUserData.firstName} {membership.publicUserData.lastName} <\n * {membership.publicUserData.identifier}> :: {membership.role}\n * </li>\n * ))}\n * </ul>\n *\n * <button disabled={!memberships.hasPreviousPage} onClick={memberships.fetchPrevious}>\n * Previous page\n * </button>\n *\n * <button disabled={!memberships.hasNextPage} onClick={memberships.fetchNext}>\n * Next page\n * </button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useOrganization<T extends UseOrganizationParams>(params?: T): UseOrganizationReturn<T> {\n const {\n domains: domainListParams,\n membershipRequests: membershipRequestsListParams,\n memberships: membersListParams,\n invitations: invitationsListParams,\n } = params || {};\n\n useAssertWrappedByClerkProvider('useOrganization');\n useAttemptToEnableOrganizations('useOrganization');\n\n const organization = useOrganizationBase();\n const session = useSessionBase();\n\n const domainSafeValues = useWithSafeValues(domainListParams, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n enrollmentMode: undefined,\n });\n\n const membershipRequestSafeValues = useWithSafeValues(membershipRequestsListParams, {\n initialPage: 1,\n pageSize: 10,\n status: 'pending',\n keepPreviousData: false,\n infinite: false,\n });\n\n const membersSafeValues = useWithSafeValues(membersListParams, {\n initialPage: 1,\n pageSize: 10,\n role: undefined,\n keepPreviousData: false,\n infinite: false,\n query: undefined,\n });\n\n const invitationsSafeValues = useWithSafeValues(invitationsListParams, {\n initialPage: 1,\n pageSize: 10,\n status: ['pending'],\n keepPreviousData: false,\n infinite: false,\n });\n\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled('useOrganization'));\n\n const domainParams =\n typeof domainListParams === 'undefined'\n ? undefined\n : {\n initialPage: domainSafeValues.initialPage,\n pageSize: domainSafeValues.pageSize,\n enrollmentMode: domainSafeValues.enrollmentMode,\n };\n\n const membershipRequestParams =\n typeof membershipRequestsListParams === 'undefined'\n ? undefined\n : {\n initialPage: membershipRequestSafeValues.initialPage,\n pageSize: membershipRequestSafeValues.pageSize,\n status: membershipRequestSafeValues.status,\n };\n\n const membersParams =\n typeof membersListParams === 'undefined'\n ? undefined\n : {\n initialPage: membersSafeValues.initialPage,\n pageSize: membersSafeValues.pageSize,\n role: membersSafeValues.role,\n query: membersSafeValues.query,\n };\n\n const invitationsParams =\n typeof invitationsListParams === 'undefined'\n ? undefined\n : {\n initialPage: invitationsSafeValues.initialPage,\n pageSize: invitationsSafeValues.pageSize,\n status: invitationsSafeValues.status,\n };\n\n const domains = usePagesOrInfinite({\n fetcher: organization?.getDomains,\n config: {\n keepPreviousData: domainSafeValues.keepPreviousData,\n infinite: domainSafeValues.infinite,\n enabled: !!domainParams,\n isSignedIn: organization !== null,\n initialPage: domainSafeValues.initialPage,\n pageSize: domainSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.DOMAINS_KEY,\n authenticated: true,\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: domainParams,\n },\n }),\n });\n\n const membershipRequests = usePagesOrInfinite({\n fetcher: organization?.getMembershipRequests,\n config: {\n keepPreviousData: membershipRequestSafeValues.keepPreviousData,\n infinite: membershipRequestSafeValues.infinite,\n enabled: !!membershipRequestParams,\n isSignedIn: organization !== null,\n initialPage: membershipRequestSafeValues.initialPage,\n pageSize: membershipRequestSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.MEMBERSHIP_REQUESTS_KEY,\n authenticated: true,\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: membershipRequestParams,\n },\n }),\n });\n\n const memberships = usePagesOrInfinite({\n fetcher: organization?.getMemberships,\n config: {\n keepPreviousData: membersSafeValues.keepPreviousData,\n infinite: membersSafeValues.infinite,\n enabled: !!membersParams,\n isSignedIn: organization !== null,\n initialPage: membersSafeValues.initialPage,\n pageSize: membersSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.MEMBERSHIPS_KEY,\n authenticated: true,\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: membersParams,\n },\n }),\n });\n\n const invitations = usePagesOrInfinite({\n fetcher: organization?.getInvitations,\n config: {\n keepPreviousData: invitationsSafeValues.keepPreviousData,\n infinite: invitationsSafeValues.infinite,\n enabled: !!invitationsParams,\n isSignedIn: organization !== null,\n initialPage: invitationsSafeValues.initialPage,\n pageSize: invitationsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.INVITATIONS_KEY,\n authenticated: true,\n tracked: {\n organizationId: organization?.id,\n },\n untracked: {\n args: invitationsParams,\n },\n }),\n });\n\n if (organization === undefined) {\n return {\n isLoaded: false,\n organization: undefined,\n membership: undefined,\n domains: undefinedPaginatedResource,\n membershipRequests: undefinedPaginatedResource,\n memberships: undefinedPaginatedResource,\n invitations: undefinedPaginatedResource,\n };\n }\n\n if (organization === null) {\n return {\n isLoaded: true,\n organization: null,\n membership: null,\n domains: null,\n membershipRequests: null,\n memberships: null,\n invitations: null,\n };\n }\n\n /** In SSR context we include only the organization object when loadOrg is set to true. */\n if (!clerk.loaded && organization) {\n return {\n isLoaded: true,\n organization,\n membership: undefined,\n domains: undefinedPaginatedResource,\n membershipRequests: undefinedPaginatedResource,\n memberships: undefinedPaginatedResource,\n invitations: undefinedPaginatedResource,\n };\n }\n\n return {\n isLoaded: clerk.loaded,\n organization,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n membership: getCurrentOrganizationMembership(session!.user.organizationMemberships, organization.id), // your membership in the current org\n domains,\n membershipRequests,\n memberships,\n invitations,\n };\n}\n","import { useMemo } from 'react';\n\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function useOrganizationCreationDefaultsCacheKeys(params: { userId: string | null }) {\n const { userId } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: STABLE_KEYS.ORGANIZATION_CREATION_DEFAULTS_KEY,\n authenticated: Boolean(userId),\n tracked: {\n userId: userId ?? null,\n },\n untracked: {\n args: {},\n },\n });\n }, [userId]);\n}\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { EnvironmentResource } from '../../types/environment';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQuery } from '../query/useQuery';\nimport { useUserBase } from './base/useUserBase';\nimport { useOrganizationCreationDefaultsCacheKeys } from './useOrganizationCreationDefaults.shared';\nimport type {\n UseOrganizationCreationDefaultsParams,\n UseOrganizationCreationDefaultsReturn,\n} from './useOrganizationCreationDefaults.types';\n\nconst HOOK_NAME = 'useOrganizationCreationDefaults';\n\n/**\n * The `useOrganizationCreationDefaults()` hook retrieves the organization creation defaults for the current user.\n *\n * @example\n * ### Basic usage\n *\n * ```tsx\n * import { useOrganizationCreationDefaults } from '@clerk/clerk-react'\n *\n * export default function CreateOrganizationForm() {\n * const { data, isLoading } = useOrganizationCreationDefaults()\n *\n * if (isLoading) return <div>Loading...</div>\n *\n * return (\n * <form>\n * <input defaultValue={data?.form.name} placeholder=\"Organization name\" />\n * <input defaultValue={data?.form.slug} placeholder=\"Slug\" />\n * <button type=\"submit\">Create</button>\n * </form>\n * )\n * }\n * ```\n */\nexport function useOrganizationCreationDefaults(\n params: UseOrganizationCreationDefaultsParams = {},\n): UseOrganizationCreationDefaultsReturn {\n useAssertWrappedByClerkProvider(HOOK_NAME);\n\n const { keepPreviousData = true, enabled = true } = params;\n const clerk = useClerkInstanceContext();\n const user = useUserBase();\n\n // @ts-expect-error `__internal_environment` is not typed\n const environment = clerk.__internal_environment as unknown as EnvironmentResource | null | undefined;\n const featureEnabled = environment?.organizationSettings?.organizationCreationDefaults?.enabled ?? false;\n\n clerk.telemetry?.record(eventMethodCalled(HOOK_NAME));\n\n const { queryKey } = useOrganizationCreationDefaultsCacheKeys({ userId: user?.id ?? null });\n\n const queryEnabled = Boolean(user) && enabled && featureEnabled && clerk.loaded;\n\n const query = useClerkQuery({\n queryKey,\n queryFn: user?.getOrganizationCreationDefaults,\n enabled: queryEnabled,\n placeholderData: defineKeepPreviousDataFn(keepPreviousData),\n });\n\n return {\n data: query.data,\n error: (query.error ?? null) as UseOrganizationCreationDefaultsReturn['error'],\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n };\n}\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type {\n CreateOrganizationParams,\n GetUserOrganizationInvitationsParams,\n GetUserOrganizationMembershipParams,\n GetUserOrganizationSuggestionsParams,\n OrganizationMembershipResource,\n OrganizationResource,\n OrganizationSuggestionResource,\n SetActive,\n UserOrganizationInvitationResource,\n} from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport type { PaginatedHookConfig, PaginatedResources, PaginatedResourcesWithDefault } from '../types';\nimport { useUserBase } from './base/useUserBase';\nimport { createCacheKeys } from './createCacheKeys';\nimport { useAttemptToEnableOrganizations } from './useAttemptToEnableOrganizations';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @interface\n */\nexport type UseOrganizationListParams = {\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n *\n * <ul>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n userMemberships?: true | PaginatedHookConfig<GetUserOrganizationMembershipParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n *\n * <ul>\n * <li>`status`: A string that filters the invitations by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n userInvitations?: true | PaginatedHookConfig<GetUserOrganizationInvitationsParams>;\n /**\n * If set to `true`, all default properties will be used.<br />\n * Otherwise, accepts an object with the following optional properties:\n *\n * <ul>\n * <li>`status`: A string that filters the suggestions by the provided status.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n userSuggestions?: true | PaginatedHookConfig<GetUserOrganizationSuggestionsParams>;\n};\n\nconst undefinedPaginatedResource = {\n data: undefined,\n count: undefined,\n error: undefined,\n isLoading: false,\n isFetching: false,\n isError: false,\n page: undefined,\n pageCount: undefined,\n fetchPage: undefined,\n fetchNext: undefined,\n fetchPrevious: undefined,\n hasNextPage: false,\n hasPreviousPage: false,\n revalidate: undefined,\n setData: undefined,\n} as const;\n\n/**\n * @interface\n */\nexport type UseOrganizationListReturn<T extends UseOrganizationListParams> =\n | {\n /**\n * Indicates whether Clerk has loaded the current authentication state and there is an authenticated user. Initially `false`, becomes `true` once Clerk loads with a user, and can revert to `false` while auth state is updating (e.g., when switching organizations via [`setActive()`](https://clerk.com/docs/reference/objects/clerk#set-active)).\n */\n isLoaded: false;\n /**\n * A function that returns a `Promise` which resolves to the newly created `Organization`.\n */\n createOrganization: undefined;\n /**\n * A function that sets the active session and/or Organization.\n */\n setActive: undefined;\n /**\n * Returns `PaginatedResources` which includes a list of the user's Organization memberships.\n */\n userMemberships: PaginatedResourcesWithDefault<OrganizationMembershipResource>;\n /**\n * Returns `PaginatedResources` which includes a list of the user's Organization invitations.\n */\n userInvitations: PaginatedResourcesWithDefault<UserOrganizationInvitationResource>;\n /**\n * Returns `PaginatedResources` which includes a list of suggestions for Organizations that the user can join.\n */\n userSuggestions: PaginatedResourcesWithDefault<OrganizationSuggestionResource>;\n }\n | {\n isLoaded: boolean;\n createOrganization: (CreateOrganizationParams: CreateOrganizationParams) => Promise<OrganizationResource>;\n setActive: SetActive;\n userMemberships: PaginatedResources<\n OrganizationMembershipResource,\n T['userMemberships'] extends { infinite: true } ? true : false\n >;\n userInvitations: PaginatedResources<\n UserOrganizationInvitationResource,\n T['userInvitations'] extends { infinite: true } ? true : false\n >;\n userSuggestions: PaginatedResources<\n OrganizationSuggestionResource,\n T['userSuggestions'] extends { infinite: true } ? true : false\n >;\n };\n\n/**\n * 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.\n *\n * @example\n * ### Expanding and paginating attributes\n *\n * 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.\n *\n * ```tsx\n * // userMemberships.data will never be populated\n * const { userMemberships } = useOrganizationList()\n *\n * // Use default values to fetch userMemberships, such as initialPage = 1 and pageSize = 10\n * const { userMemberships } = useOrganizationList({\n * userMemberships: true,\n * })\n *\n * // Pass your own values to fetch userMemberships\n * const { userMemberships } = useOrganizationList({\n * userMemberships: {\n * pageSize: 20,\n * initialPage: 2, // skips the first page\n * },\n * })\n *\n * // Aggregate pages in order to render an infinite list\n * const { userMemberships } = useOrganizationList({\n * userMemberships: {\n * infinite: true,\n * },\n * })\n * ```\n *\n * @example\n * ### Infinite pagination\n *\n * 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.\n *\n * ```tsx {{ filename: 'src/components/JoinedOrganizations.tsx' }}\n * import { useOrganizationList } from '@clerk/react'\n * import React from 'react'\n *\n * const JoinedOrganizations = () => {\n * const { isLoaded, setActive, userMemberships } = useOrganizationList({\n * userMemberships: {\n * infinite: true,\n * },\n * })\n *\n * if (!isLoaded) {\n * return <>Loading</>\n * }\n *\n * return (\n * <>\n * <ul>\n * {userMemberships.data?.map((mem) => (\n * <li key={mem.id}>\n * <span>{mem.organization.name}</span>\n * <button onClick={() => setActive({ organization: mem.organization.id })}>Select</button>\n * </li>\n * ))}\n * </ul>\n *\n * <button disabled={!userMemberships.hasNextPage} onClick={() => userMemberships.fetchNext()}>\n * Load more\n * </button>\n * </>\n * )\n * }\n *\n * export default JoinedOrganizations\n * ```\n *\n * @example\n * ### Simple pagination\n *\n * 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.\n *\n * Notice the difference between this example's pagination and the infinite pagination example above.\n *\n * ```tsx {{ filename: 'src/components/UserInvitationsTable.tsx' }}\n * import { useOrganizationList } from '@clerk/react'\n * import React from 'react'\n *\n * const UserInvitationsTable = () => {\n * const { isLoaded, userInvitations } = useOrganizationList({\n * userInvitations: {\n * infinite: true,\n * keepPreviousData: true,\n * },\n * })\n *\n * if (!isLoaded || userInvitations.isLoading) {\n * return <>Loading</>\n * }\n *\n * return (\n * <>\n * <table>\n * <thead>\n * <tr>\n * <th>Email</th>\n * <th>Org name</th>\n * </tr>\n * </thead>\n *\n * <tbody>\n * {userInvitations.data?.map((inv) => (\n * <tr key={inv.id}>\n * <th>{inv.emailAddress}</th>\n * <th>{inv.publicOrganizationData.name}</th>\n * </tr>\n * ))}\n * </tbody>\n * </table>\n *\n * <button disabled={!userInvitations.hasPreviousPage} onClick={userInvitations.fetchPrevious}>\n * Prev\n * </button>\n * <button disabled={!userInvitations.hasNextPage} onClick={userInvitations.fetchNext}>\n * Next\n * </button>\n * </>\n * )\n * }\n *\n * export default UserInvitationsTable\n * ```\n */\nexport function useOrganizationList<T extends UseOrganizationListParams>(params?: T): UseOrganizationListReturn<T> {\n const { userMemberships, userInvitations, userSuggestions } = params || {};\n\n useAssertWrappedByClerkProvider('useOrganizationList');\n useAttemptToEnableOrganizations('useOrganizationList');\n\n const userMembershipsSafeValues = useWithSafeValues(userMemberships, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n });\n\n const userInvitationsSafeValues = useWithSafeValues(userInvitations, {\n initialPage: 1,\n pageSize: 10,\n status: 'pending',\n keepPreviousData: false,\n infinite: false,\n });\n\n const userSuggestionsSafeValues = useWithSafeValues(userSuggestions, {\n initialPage: 1,\n pageSize: 10,\n status: 'pending',\n keepPreviousData: false,\n infinite: false,\n });\n\n const clerk = useClerkInstanceContext();\n const user = useUserBase();\n\n clerk.telemetry?.record(eventMethodCalled('useOrganizationList'));\n\n const userMembershipsParams =\n typeof userMemberships === 'undefined'\n ? undefined\n : {\n initialPage: userMembershipsSafeValues.initialPage,\n pageSize: userMembershipsSafeValues.pageSize,\n };\n\n const userInvitationsParams =\n typeof userInvitations === 'undefined'\n ? undefined\n : {\n initialPage: userInvitationsSafeValues.initialPage,\n pageSize: userInvitationsSafeValues.pageSize,\n status: userInvitationsSafeValues.status,\n };\n\n const userSuggestionsParams =\n typeof userSuggestions === 'undefined'\n ? undefined\n : {\n initialPage: userSuggestionsSafeValues.initialPage,\n pageSize: userSuggestionsSafeValues.pageSize,\n status: userSuggestionsSafeValues.status,\n };\n\n const isClerkLoaded = !!(clerk.loaded && user);\n\n const memberships = usePagesOrInfinite({\n fetcher: user?.getOrganizationMemberships,\n config: {\n keepPreviousData: userMembershipsSafeValues.keepPreviousData,\n infinite: userMembershipsSafeValues.infinite,\n enabled: !!userMembershipsParams,\n isSignedIn: user !== null,\n initialPage: userMembershipsSafeValues.initialPage,\n pageSize: userMembershipsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.USER_MEMBERSHIPS_KEY,\n authenticated: true,\n tracked: {\n userId: user?.id,\n },\n untracked: {\n args: userMembershipsParams,\n },\n }),\n });\n\n const invitations = usePagesOrInfinite({\n fetcher: user?.getOrganizationInvitations,\n config: {\n keepPreviousData: userInvitationsSafeValues.keepPreviousData,\n infinite: userInvitationsSafeValues.infinite,\n // In useOrganizationList, you need to opt in by passing an object or `true`.\n enabled: !!userInvitationsParams,\n isSignedIn: user !== null,\n initialPage: userInvitationsSafeValues.initialPage,\n pageSize: userInvitationsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.USER_INVITATIONS_KEY,\n authenticated: true,\n tracked: {\n userId: user?.id,\n },\n untracked: {\n args: userInvitationsParams,\n },\n }),\n });\n\n const suggestions = usePagesOrInfinite({\n fetcher: user?.getOrganizationSuggestions,\n config: {\n keepPreviousData: userSuggestionsSafeValues.keepPreviousData,\n infinite: userSuggestionsSafeValues.infinite,\n enabled: !!userSuggestionsParams,\n isSignedIn: user !== null,\n initialPage: userSuggestionsSafeValues.initialPage,\n pageSize: userSuggestionsSafeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: STABLE_KEYS.USER_SUGGESTIONS_KEY,\n authenticated: true,\n tracked: {\n userId: user?.id,\n },\n untracked: {\n args: userSuggestionsParams,\n },\n }),\n });\n\n // TODO: Properly check for SSR user values\n if (!isClerkLoaded) {\n return {\n isLoaded: false,\n createOrganization: undefined,\n setActive: undefined,\n userMemberships: undefinedPaginatedResource,\n userInvitations: undefinedPaginatedResource,\n userSuggestions: undefinedPaginatedResource,\n };\n }\n\n return {\n isLoaded: isClerkLoaded,\n setActive: clerk.setActive,\n createOrganization: clerk.createOrganization,\n userMemberships: memberships,\n userInvitations: invitations,\n userSuggestions: suggestions,\n };\n}\n","import React from 'react';\n\n/**\n * @internal\n */\nexport const useSafeLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { UseSessionReturn } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { useSessionBase } from './base/useSessionBase';\n\ntype UseSession = () => UseSessionReturn;\n\nconst hookName = `useSession`;\n/**\n * 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.\n *\n * @unionReturnHeadings\n * [\"Loading\", \"Signed out\", \"Signed in\"]\n *\n * @function\n *\n * @param [options] - An object containing options for the `useSession()` hook.\n * @example\n * ### Access the `Session` object\n *\n * 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.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useSession } from '@clerk/react'\n *\n * export default function Home() {\n * const { isLoaded, session, isSignedIn } = useSession()\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null\n * }\n * if (!isSignedIn) {\n * // Handle signed out state\n * return null\n * }\n *\n * return (\n * <div>\n * <p>This session has been active since {session.lastActiveAt.toLocaleString()}</p>\n * </div>\n * )\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * ```tsx {{ filename: 'app/page.tsx' }}\n * 'use client';\n *\n * import { useSession } from '@clerk/nextjs';\n *\n * export default function HomePage() {\n * const { isLoaded, session, isSignedIn } = useSession();\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null;\n * }\n * if (!isSignedIn) {\n * // Handle signed out state\n * return null;\n * }\n *\n * return (\n * <div>\n * <p>This session has been active since {session.lastActiveAt.toLocaleString()}</p>\n * </div>\n * );\n * }\n * ```\n *\n * </Tab>\n * </Tabs>\n */\nexport const useSession: UseSession = () => {\n useAssertWrappedByClerkProvider(hookName);\n\n const session = useSessionBase();\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n if (session === undefined) {\n return { isLoaded: false, isSignedIn: undefined, session: undefined };\n }\n\n if (session === null) {\n return { isLoaded: true, isSignedIn: false, session: null };\n }\n\n return { isLoaded: true, isSignedIn: clerk.isSignedIn, session };\n};\n","import { useCallback, useSyncExternalStore } from 'react';\n\nimport type { ClientResource } from '@/types';\n\nimport { useClerkInstanceContext } from '../../contexts';\n\nconst initialSnapshot = undefined;\nconst getInitialSnapshot = () => initialSnapshot;\nexport function useClientBase(): ClientResource | null | undefined {\n const clerk = useClerkInstanceContext();\n\n const client = useSyncExternalStore(\n useCallback(callback => clerk.addListener(callback, { skipInitialEmit: true }), [clerk]),\n useCallback(() => {\n if (!clerk.loaded || !clerk.__internal_lastEmittedResources) {\n return initialSnapshot;\n }\n return clerk.__internal_lastEmittedResources.client;\n }, [clerk]),\n getInitialSnapshot,\n );\n\n return client;\n}\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { UseSessionListReturn } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { useClientBase } from './base/useClientBase';\n\nconst hookName = 'useSessionList';\n/**\n * The `useSessionList()` hook returns an array of [`Session`](https://clerk.com/docs/reference/objects/session) objects that have been registered on the client device.\n *\n * @unionReturnHeadings\n * [\"Initialization\", \"Loaded\"]\n *\n * @function\n *\n * @example\n * ### Get a list of sessions\n *\n * 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.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useSessionList } from '@clerk/react'\n *\n * export default function Home() {\n * const { isLoaded, sessions } = useSessionList()\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null\n * }\n *\n * return (\n * <div>\n * <p>Welcome back. You've been here {sessions.length} times before.</p>\n * </div>\n * )\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * ```tsx {{ filename: 'app/page.tsx' }}\n * 'use client';\n *\n * import { useSessionList } from '@clerk/nextjs';\n *\n * export default function HomePage() {\n * const { isLoaded, sessions } = useSessionList();\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null;\n * }\n *\n * return (\n * <div>\n * <p>Welcome back. You've been here {sessions.length} times before.</p>\n * </div>\n * );\n * }\n * ```\n *\n * </Tab>\n * </Tabs>\n */\nexport const useSessionList = (): UseSessionListReturn => {\n useAssertWrappedByClerkProvider(hookName);\n\n const isomorphicClerk = useClerkInstanceContext();\n const client = useClientBase();\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n if (!client) {\n return { isLoaded: false, sessions: undefined, setActive: undefined };\n }\n\n return {\n isLoaded: true,\n sessions: client.sessions,\n setActive: isomorphicClerk.setActive,\n };\n};\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { UseUserReturn } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { useUserBase } from './base/useUserBase';\n\nconst hookName = 'useUser';\n/**\n * 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.\n *\n * @unionReturnHeadings\n * [\"Loading\", \"Signed out\", \"Signed in\"]\n *\n * @example\n * ### Get the current user\n *\n * 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.\n *\n * ```tsx {{ filename: 'src/Example.tsx' }}\n * import { useUser } from '@clerk/react'\n *\n * export default function Example() {\n * const { isSignedIn, user, isLoaded } = useUser()\n *\n * if (!isLoaded) {\n * return <div>Loading...</div>\n * }\n *\n * if (!isSignedIn) {\n * return <div>Sign in to view this page</div>\n * }\n *\n * return <div>Hello {user.firstName}!</div>\n * }\n * ```\n *\n * @example\n * ### Update user data\n *\n * 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.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useUser } from '@clerk/react'\n *\n * export default function Home() {\n * const { isSignedIn, isLoaded, user } = useUser()\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null\n * }\n *\n * if (!isSignedIn) return null\n *\n * const updateUser = async () => {\n * await user.update({\n * firstName: 'John',\n * lastName: 'Doe',\n * })\n * }\n *\n * return (\n * <>\n * <button onClick={updateUser}>Update your name</button>\n * <p>user.firstName: {user.firstName}</p>\n * <p>user.lastName: {user.lastName}</p>\n * </>\n * )\n * }\n * ```\n * </Tab>\n * <Tab>\n *\n * ```tsx {{ filename: 'app/page.tsx' }}\n * 'use client';\n *\n * import { useUser } from '@clerk/nextjs';\n *\n * export default function HomePage() {\n * const { isSignedIn, isLoaded, user } = useUser();\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null;\n * }\n *\n * if (!isSignedIn) return null;\n *\n * const updateUser = async () => {\n * await user.update({\n * firstName: 'John',\n * lastName: 'Doe',\n * });\n * };\n *\n * return (\n * <>\n * <button onClick={updateUser}>Update your name</button>\n * <p>user.firstName: {user.firstName}</p>\n * <p>user.lastName: {user.lastName}</p>\n * </>\n * );\n * }\n * ```\n *\n * </Tab>\n * </Tabs>\n *\n * @example\n * ### Reload user data\n *\n * 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.\n *\n * <Tabs items='React,Next.js'>\n * <Tab>\n *\n * ```tsx {{ filename: 'src/Home.tsx' }}\n * import { useUser } from '@clerk/react'\n *\n * export default function Home() {\n * const { isSignedIn, isLoaded, user } = useUser();\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null;\n * }\n *\n * if (!isSignedIn) return null;\n *\n * const updateUser = async () => {\n * // Update data via an API endpoint\n * const updateMetadata = await fetch('/api/updateMetadata', {\n * method: 'POST',\n * body: JSON.stringify({\n * role: 'admin'\n * })\n * });\n *\n * // Check if the update was successful\n * if ((await updateMetadata.json()).message !== 'success') {\n * throw new Error('Error updating');\n * }\n *\n * // If the update was successful, reload the user data\n * await user.reload();\n * };\n *\n * return (\n * <>\n * <button onClick={updateUser}>Update your metadata</button>\n * <p>user role: {user.publicMetadata.role}</p>\n * </>\n * );\n * }\n * ```\n *\n * </Tab>\n * <Tab>\n *\n * ```tsx {{ filename: 'app/page.tsx' }}\n * 'use client';\n *\n * import { useUser } from '@clerk/nextjs';\n *\n * export default function HomePage() {\n * const { isSignedIn, isLoaded, user } = useUser();\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null;\n * }\n *\n * if (!isSignedIn) return null;\n *\n * const updateUser = async () => {\n * // Update data via an API endpoint\n * const updateMetadata = await fetch('/api/updateMetadata', {\n * method: 'POST',\n * body: JSON.stringify({\n * role: 'admin',\n * }),\n * });\n *\n * // Check if the update was successful\n * if ((await updateMetadata.json()).message !== 'success') {\n * throw new Error('Error updating');\n * }\n *\n * // If the update was successful, reload the user data\n * await user.reload();\n * };\n *\n * return (\n * <>\n * <button onClick={updateUser}>Update your metadata</button>\n * <p>user role: {user.publicMetadata.role}</p>\n * </>\n * );\n * }\n * ```\n *\n * </Tab>\n * </Tabs>\n */\nexport function useUser(): UseUserReturn {\n useAssertWrappedByClerkProvider(hookName);\n\n const user = useUserBase();\n const clerk = useClerkInstanceContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n if (user === undefined) {\n return { isLoaded: false, isSignedIn: undefined, user: undefined };\n }\n\n if (user === null) {\n return { isLoaded: true, isSignedIn: false, user: null };\n }\n\n return { isLoaded: true, isSignedIn: true, user };\n}\n","import { dequal as deepEqual } from 'dequal';\nimport React from 'react';\n\ntype UseMemoFactory<T> = () => T;\ntype UseMemoDependencyArray = Exclude<Parameters<typeof React.useMemo>[1], 'undefined'>;\ntype UseDeepEqualMemo = <T>(factory: UseMemoFactory<T>, dependencyArray: UseMemoDependencyArray) => T;\n\nconst useDeepEqualMemoize = <T>(value: T) => {\n const ref = React.useRef<T>(value);\n if (!deepEqual(value, ref.current)) {\n ref.current = value;\n }\n return React.useMemo(() => ref.current, [ref.current]);\n};\n\n/**\n * @internal\n */\nexport const useDeepEqualMemo: UseDeepEqualMemo = (factory, dependencyArray) => {\n return React.useMemo(factory, useDeepEqualMemoize(dependencyArray));\n};\n\n/**\n * @internal\n */\nexport const isDeeplyEqual = deepEqual;\n","import { useCallback, useRef } from 'react';\n\nimport { validateReverificationConfig } from '../../authorization';\nimport { isReverificationHint, reverificationError } from '../../authorization-errors';\nimport { ClerkRuntimeError, isClerkAPIResponseError } from '../../error';\nimport { eventMethodCalled } from '../../telemetry';\nimport type { Clerk, SessionVerificationLevel } from '../../types';\nimport { createDeferredPromise } from '../../utils/createDeferredPromise';\nimport { useClerk } from './useClerk';\nimport { useSafeLayoutEffect } from './useSafeLayoutEffect';\n\nconst CLERK_API_REVERIFICATION_ERROR_CODE = 'session_reverification_required';\n\n/**\n *\n */\nasync function resolveResult<T>(result: Promise<T> | T): Promise<T | ReturnType<typeof reverificationError>> {\n try {\n const r = await result;\n if (r instanceof Response) {\n return r.json();\n }\n return r;\n } catch (e) {\n // Treat fapi assurance as an assurance hint\n if (isClerkAPIResponseError(e) && e.errors.find(({ code }) => code === CLERK_API_REVERIFICATION_ERROR_CODE)) {\n return reverificationError();\n }\n\n // rethrow\n throw e;\n }\n}\n\ntype ExcludeClerkError<T> = T extends { clerk_error: any } ? never : T;\n\n/**\n * @interface\n */\nexport type NeedsReverificationParameters = {\n /**\n * Marks the reverification process as cancelled and rejects the original request.\n */\n cancel: () => void;\n /**\n * Marks the reverification process as complete and retries the original request.\n */\n complete: () => void;\n /**\n * The verification level required for the reverification process.\n */\n level: SessionVerificationLevel | undefined;\n};\n\n/**\n * The optional options object.\n *\n * @interface\n */\nexport type UseReverificationOptions = {\n /**\n * Handler for the reverification process. Opts out of using the default UI. Use this to build a custom UI.\n *\n * @param properties - Callbacks and info to control the reverification flow.\n * @param properties.cancel - A function that will cancel the reverification process.\n * @param properties.complete - A function that will retry the original request after reverification.\n * @param properties.level - The level returned with the reverification hint.\n */\n onNeedsReverification?: (properties: NeedsReverificationParameters) => void;\n};\n\n/**\n * @interface\n */\ntype UseReverificationResult<Fetcher extends (...args: any[]) => Promise<any> | undefined> = (\n ...args: Parameters<Fetcher>\n) => Promise<ExcludeClerkError<Awaited<ReturnType<Fetcher>>>>;\n\n/**\n * @interface\n */\ntype UseReverification = <\n Fetcher extends (...args: any[]) => Promise<any> | undefined,\n Options extends UseReverificationOptions = UseReverificationOptions,\n>(\n /**\n * A function that returns a promise.\n */\n fetcher: Fetcher,\n /**\n * Optional configuration object extending [`UseReverificationOptions`](https://clerk.com/docs/reference/hooks/use-reverification#use-reverification-options).\n */\n options?: Options,\n) => UseReverificationResult<Fetcher>;\n\ntype CreateReverificationHandlerParams = UseReverificationOptions & {\n openUIComponent: Clerk['__internal_openReverification'];\n telemetry: Clerk['telemetry'];\n};\n\n/**\n *\n */\nfunction createReverificationHandler(params: CreateReverificationHandlerParams) {\n /**\n *\n */\n function assertReverification<Fetcher extends (...args: any[]) => Promise<any> | undefined>(\n fetcher: Fetcher,\n ): (...args: Parameters<Fetcher>) => Promise<ExcludeClerkError<Awaited<ReturnType<Fetcher>>>> {\n return (async (...args: Parameters<Fetcher>) => {\n let result = await resolveResult(fetcher(...args));\n\n if (isReverificationHint(result)) {\n /**\n * Create a promise\n */\n const resolvers = createDeferredPromise();\n\n const isValidMetadata = validateReverificationConfig(result.clerk_error.metadata?.reverification);\n\n const level = isValidMetadata ? isValidMetadata().level : undefined;\n\n const cancel = () => {\n resolvers.reject(\n new ClerkRuntimeError('User cancelled attempted verification', {\n code: 'reverification_cancelled',\n }),\n );\n };\n\n const complete = () => {\n resolvers.resolve(true);\n };\n\n if (params.onNeedsReverification === undefined) {\n /**\n * On success resolve the pending promise\n * On cancel reject the pending promise\n */\n params.openUIComponent?.({\n level: level,\n afterVerification: complete,\n afterVerificationCancelled: cancel,\n });\n } else {\n params.onNeedsReverification({\n cancel,\n complete,\n level,\n });\n }\n\n /**\n * Wait until the promise from above have been resolved or rejected\n */\n await resolvers.promise;\n\n /**\n * After the promise resolved successfully try the original request one more time\n */\n result = await resolveResult(fetcher(...args));\n }\n\n return result;\n }) as ExcludeClerkError<Awaited<ReturnType<Fetcher>>>;\n }\n\n return assertReverification;\n}\n\n/**\n * > [!WARNING]\n * >\n * > 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.\n *\n * 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.\n *\n * @function\n *\n * @returns The `useReverification()` hook returns an array with the \"enhanced\" fetcher.\n *\n * @example\n * ### Handle cancellation of the reverification process\n *\n * 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`.\n *\n * 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.\n *\n * ```tsx {{ filename: 'src/components/MyButton.tsx' }}\n * import { useReverification } from '@clerk/react'\n * import { isReverificationCancelledError } from '@clerk/react/error'\n *\n * type MyData = {\n * balance: number\n * }\n *\n * export function MyButton() {\n * const fetchMyData = () => fetch('/api/balance').then(res=> res.json() as Promise<MyData>)\n * const enhancedFetcher = useReverification(fetchMyData);\n *\n * const handleClick = async () => {\n * try {\n * const myData = await enhancedFetcher()\n * // ^ is types as `MyData`\n * } catch (e) {\n * // Handle error returned from the fetcher here\n *\n * // You can also handle cancellation with the following\n * if (isReverificationCancelledError(err)) {\n * // Handle the cancellation error here\n * }\n * }\n * }\n *\n * return <button onClick={handleClick}>Update User</button>\n * }\n * ```\n */\nexport const useReverification: UseReverification = (fetcher, options) => {\n const { __internal_openReverification, telemetry } = useClerk();\n const fetcherRef = useRef(fetcher);\n const optionsRef = useRef(options);\n\n telemetry?.record(\n eventMethodCalled('useReverification', {\n onNeedsReverification: Boolean(options?.onNeedsReverification),\n }),\n );\n\n // Keep fetcher and options ref in sync\n useSafeLayoutEffect(() => {\n fetcherRef.current = fetcher;\n optionsRef.current = options;\n });\n\n return useCallback(\n (...args) => {\n const handler = createReverificationHandler({\n openUIComponent: __internal_openReverification,\n telemetry,\n ...optionsRef.current,\n })(fetcherRef.current);\n return handler(...args);\n },\n [__internal_openReverification, telemetry],\n );\n};\n","import type { ForPayerType } from '../../types/billing';\nimport { useClerkInstanceContext } from '../contexts';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useUserBase } from './base/useUserBase';\n\n/**\n * @internal\n */\nexport function useBillingIsEnabled(params?: { for?: ForPayerType; enabled?: boolean; authenticated?: boolean }) {\n const clerk = useClerkInstanceContext();\n\n const enabledFromParam = params?.enabled ?? true;\n\n // @ts-expect-error `__internal_environment` is not typed\n const environment = clerk.__internal_environment as unknown as EnvironmentResource | null | undefined;\n\n const user = useUserBase();\n const organization = useOrganizationBase();\n\n const userBillingEnabled = environment?.commerceSettings.billing.user.enabled;\n const orgBillingEnabled = environment?.commerceSettings.billing.organization.enabled;\n\n const billingEnabled =\n params?.for === 'organization'\n ? orgBillingEnabled\n : params?.for === 'user'\n ? userBillingEnabled\n : userBillingEnabled || orgBillingEnabled;\n\n const isOrganization = params?.for === 'organization';\n const requireUserAndOrganizationWhenAuthenticated =\n (params?.authenticated ?? true) ? (isOrganization ? Boolean(organization?.id) : true) && Boolean(user?.id) : true;\n\n return billingEnabled && enabledFromParam && clerk.loaded && requireUserAndOrganizationWhenAuthenticated;\n}\n","import { eventMethodCalled } from '../../telemetry/events/method-called';\nimport type { ClerkPaginatedResponse, ClerkResource, ForPayerType } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport type { ResourceCacheStableKey } from '../stable-keys';\nimport type { PagesOrInfiniteOptions, PaginatedHookConfig, PaginatedResources } from '../types';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useUserBase } from './base/useUserBase';\nimport { createCacheKeys } from './createCacheKeys';\nimport { useBillingIsEnabled } from './useBillingIsEnabled';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @internal\n */\ntype BillingHookConfig<TResource extends ClerkResource, TParams extends PagesOrInfiniteOptions> = {\n hookName: string;\n resourceType: ResourceCacheStableKey;\n useFetcher: (\n param: ForPayerType,\n ) => ((params: TParams & { orgId?: string }) => Promise<ClerkPaginatedResponse<TResource>>) | undefined;\n options?: {\n unauthenticated?: boolean;\n };\n};\n\n/**\n * @interface\n * @standalonePage\n */\nexport interface HookParams extends PaginatedHookConfig<\n PagesOrInfiniteOptions & {\n /**\n * If `true`, a request will be triggered when the hook is mounted.\n *\n * @default true\n */\n enabled?: boolean;\n /**\n * On `cache` mode, no request will be triggered when the hook is mounted and the data will be fetched from the cache.\n *\n * @default undefined\n *\n * @hidden\n *\n * @experimental\n */\n __experimental_mode?: 'cache';\n }\n> {\n /**\n * Specifies whether to fetch for the current user or Organization.\n *\n * @default 'user'\n */\n for?: ForPayerType;\n}\n\n/**\n * A hook factory that creates paginated data fetching hooks for commerce-related resources.\n * It provides a standardized way to create hooks that can fetch either user or Organization resources\n * with built-in pagination support.\n *\n * The generated hooks handle:\n * - Clerk authentication context\n * - Resource-specific data fetching\n * - Pagination (both traditional and infinite scroll)\n * - Telemetry tracking\n * - Type safety for the specific resource.\n *\n * @internal\n */\nexport function createBillingPaginatedHook<TResource extends ClerkResource, TParams extends PagesOrInfiniteOptions>({\n hookName,\n resourceType,\n useFetcher,\n options,\n}: BillingHookConfig<TResource, TParams>) {\n return function useBillingHook<T extends HookParams>(\n params?: T,\n ): PaginatedResources<TResource, T extends { infinite: true } ? true : false> {\n const { for: _for, enabled: externalEnabled, ...paginationParams } = params || ({} as Partial<T>);\n\n const safeFor = _for || 'user';\n\n useAssertWrappedByClerkProvider(hookName);\n\n const fetchFn = useFetcher(safeFor);\n\n const safeValues = useWithSafeValues(paginationParams, {\n initialPage: 1,\n pageSize: 10,\n keepPreviousData: false,\n infinite: false,\n __experimental_mode: undefined,\n } as unknown as T);\n\n const clerk = useClerkInstanceContext();\n\n const user = useUserBase();\n const organization = useOrganizationBase();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n const isForOrganization = safeFor === 'organization';\n\n const billingEnabled = useBillingIsEnabled({\n for: safeFor,\n enabled: externalEnabled,\n authenticated: !options?.unauthenticated,\n });\n\n const hookParams =\n typeof paginationParams === 'undefined'\n ? undefined\n : ({\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n ...(options?.unauthenticated ? {} : isForOrganization ? { orgId: organization?.id } : {}),\n } as TParams);\n\n const isEnabled = !!hookParams && clerk.loaded && !!billingEnabled;\n\n return usePagesOrInfinite({\n fetcher: fetchFn,\n config: {\n keepPreviousData: safeValues.keepPreviousData,\n infinite: safeValues.infinite,\n enabled: isEnabled,\n ...(options?.unauthenticated ? {} : { isSignedIn: user !== null }),\n __experimental_mode: safeValues.__experimental_mode,\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n },\n keys: createCacheKeys({\n stablePrefix: resourceType,\n authenticated: !options?.unauthenticated,\n tracked: options?.unauthenticated\n ? ({ for: safeFor } as const)\n : ({\n userId: user?.id,\n ...(isForOrganization ? { orgId: organization?.id } : {}),\n } as const),\n untracked: {\n args: hookParams as TParams,\n },\n }),\n });\n };\n}\n","import type { BillingStatementResource, GetStatementsParams } from '../../types';\nimport { useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const useStatements = createBillingPaginatedHook<BillingStatementResource, GetStatementsParams>({\n hookName: 'useStatements',\n resourceType: STABLE_KEYS.STATEMENTS_KEY,\n useFetcher: () => {\n const clerk = useClerkInstanceContext();\n if (clerk.loaded) {\n return clerk.billing.getStatements;\n }\n return undefined;\n },\n});\n\n/**\n * @interface\n */\nexport type UseStatementsReturn = ReturnType<typeof useStatements>;\n","import type { BillingPaymentResource, GetPaymentAttemptsParams } from '../../types';\nimport { useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const usePaymentAttempts = createBillingPaginatedHook<BillingPaymentResource, GetPaymentAttemptsParams>({\n hookName: 'usePaymentAttempts',\n resourceType: STABLE_KEYS.PAYMENT_ATTEMPTS_KEY,\n useFetcher: () => {\n const clerk = useClerkInstanceContext();\n if (clerk.loaded) {\n return clerk.billing.getPaymentAttempts;\n }\n return undefined;\n },\n});\n\n/**\n * @interface\n */\nexport type UsePaymentAttemptsReturn = ReturnType<typeof usePaymentAttempts>;\n","import type { BillingPaymentMethodResource, GetPaymentMethodsParams } from '../../types';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useUserBase } from './base/useUserBase';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const usePaymentMethods = createBillingPaginatedHook<BillingPaymentMethodResource, GetPaymentMethodsParams>({\n hookName: 'usePaymentMethods',\n resourceType: STABLE_KEYS.PAYMENT_METHODS_KEY,\n useFetcher: resource => {\n const organization = useOrganizationBase();\n const user = useUserBase();\n\n if (resource === 'organization') {\n return organization?.getPaymentMethods;\n }\n return user?.getPaymentMethods;\n },\n});\n\n/**\n * @interface\n */\nexport type UsePaymentMethodsReturn = ReturnType<typeof usePaymentMethods>;\n","import type { BillingPlanResource, GetPlansParams } from '../../types';\nimport { useClerkInstanceContext } from '../contexts';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createBillingPaginatedHook } from './createBillingPaginatedHook';\n\n/**\n * @internal\n */\nexport const usePlans = createBillingPaginatedHook<BillingPlanResource, GetPlansParams>({\n hookName: 'usePlans',\n resourceType: STABLE_KEYS.PLANS_KEY,\n useFetcher: _for => {\n const clerk = useClerkInstanceContext();\n if (!clerk.loaded) {\n return undefined;\n }\n return params => clerk.billing.getPlans({ ...params, for: _for });\n },\n options: {\n unauthenticated: true,\n },\n});\n\n/**\n * @interface\n */\nexport type UsePlansReturn = ReturnType<typeof usePlans>;\n","import { useMemo } from 'react';\n\nimport type { ForPayerType } from '../../types';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function useSubscriptionCacheKeys(params: {\n userId: string | undefined;\n orgId: string | undefined;\n for?: ForPayerType;\n}) {\n const { userId, orgId, for: forType } = params;\n return useMemo(() => {\n const isOrganization = forType === 'organization';\n\n const safeOrgId = isOrganization ? orgId : undefined;\n return createCacheKeys({\n stablePrefix: STABLE_KEYS.SUBSCRIPTION_KEY,\n authenticated: true,\n tracked: {\n userId,\n orgId: safeOrgId,\n },\n untracked: {\n args: { orgId: safeOrgId },\n },\n });\n }, [userId, orgId, forType]);\n}\n","import { useCallback, useEffect, useRef } from 'react';\n\nimport { eventMethodCalled } from '../../telemetry/events';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQueryClient } from '../query/use-clerk-query-client';\nimport { useClerkQuery } from '../query/useQuery';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useUserBase } from './base/useUserBase';\nimport { useBillingIsEnabled } from './useBillingIsEnabled';\nimport { useClearQueriesOnSignOut } from './useClearQueriesOnSignOut';\nimport { useSubscriptionCacheKeys } from './useSubscription.shared';\nimport type { SubscriptionResult, UseSubscriptionParams } from './useSubscription.types';\n\nconst HOOK_NAME = 'useSubscription';\n\n/**\n * @internal\n */\nexport function useSubscription(params?: UseSubscriptionParams): SubscriptionResult {\n useAssertWrappedByClerkProvider(HOOK_NAME);\n\n const clerk = useClerkInstanceContext();\n const user = useUserBase();\n const organization = useOrganizationBase();\n\n const billingEnabled = useBillingIsEnabled(params);\n\n const recordedRef = useRef(false);\n useEffect(() => {\n if (!recordedRef.current && clerk?.telemetry) {\n clerk.telemetry.record(eventMethodCalled(HOOK_NAME));\n recordedRef.current = true;\n }\n }, [clerk]);\n\n const keepPreviousData = params?.keepPreviousData ?? false;\n\n const [queryClient] = useClerkQueryClient();\n\n const { queryKey, invalidationKey, stableKey, authenticated } = useSubscriptionCacheKeys({\n userId: user?.id,\n orgId: organization?.id,\n for: params?.for,\n });\n\n const queriesEnabled = Boolean(user?.id && billingEnabled);\n useClearQueriesOnSignOut({\n isSignedOut: user === null,\n authenticated,\n stableKeys: stableKey,\n });\n\n const query = useClerkQuery({\n queryKey,\n queryFn: ({ queryKey }) => {\n const obj = queryKey[3];\n return clerk.billing.getSubscription(obj.args);\n },\n staleTime: 1_000 * 60,\n enabled: queriesEnabled,\n placeholderData: defineKeepPreviousDataFn(keepPreviousData && queriesEnabled),\n });\n\n const revalidate = useCallback(\n () => queryClient.invalidateQueries({ queryKey: invalidationKey }),\n [queryClient, invalidationKey],\n );\n\n return {\n data: query.data,\n // React Query returns null for no error, but our types expect undefined.\n // Convert to undefined for type compatibility.\n error: query.error ?? undefined,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n revalidate,\n };\n}\n","import { useCallback, useSyncExternalStore } from 'react';\n\nimport type { CheckoutSignalValue } from '../../types/clerk';\nimport type { __experimental_CheckoutProvider } from '../contexts';\nimport { useCheckoutContext, useClerkInstanceContext } from '../contexts';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useUser } from './useUser';\n\ntype UseCheckoutParams = Parameters<typeof __experimental_CheckoutProvider>[0];\n\n/**\n * @function\n *\n * @param [options] - An object containing the configuration for the checkout flow.\n *\n * **Required** if the hook is used without a `<CheckoutProvider />` wrapping the component tree.\n */\nexport const useCheckout = (options?: UseCheckoutParams): CheckoutSignalValue => {\n const contextOptions = useCheckoutContext();\n const { for: forOrganization, planId, planPeriod, seatsQuantity, priceId } = options || contextOptions;\n const organization = useOrganizationBase();\n const { isLoaded, user } = useUser();\n const clerk = useClerkInstanceContext();\n\n if (user === null && isLoaded) {\n throw new Error('Clerk: Ensure that `useCheckout` is inside a component wrapped with `<Show when=\"signed-in\" />`.');\n }\n\n if (isLoaded && forOrganization === 'organization' && organization === null) {\n throw new Error(\n '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',\n );\n }\n\n const signal = useCallback(() => {\n return clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization, seatsQuantity, priceId });\n }, [user?.id, organization?.id, planId, planPeriod, forOrganization, seatsQuantity, priceId]);\n\n const subscribe = useCallback(\n (callback: () => void) => {\n if (!clerk.loaded) {\n return () => {};\n }\n\n return clerk.__internal_state.__internal_effect(() => {\n signal();\n callback();\n });\n },\n [signal, clerk.loaded, clerk.__internal_state],\n );\n\n const getSnapshot = useCallback(() => {\n return signal();\n }, [signal]);\n\n const value = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n return value;\n};\n","import { useCallback, useEffect, useMemo, useRef } from 'react';\n\nimport { eventMethodCalled } from '../../telemetry/events';\nimport type { BillingCreditBalanceResource, ForPayerType } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQueryClient } from '../query/use-clerk-query-client';\nimport { useClerkQuery } from '../query/useQuery';\nimport { STABLE_KEYS } from '../stable-keys';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useUserBase } from './base/useUserBase';\nimport { createCacheKeys } from './createCacheKeys';\nimport { useBillingIsEnabled } from './useBillingIsEnabled';\nimport { useClearQueriesOnSignOut } from './useClearQueriesOnSignOut';\n\nconst HOOK_NAME = 'useCreditBalance';\n\nexport type UseCreditBalanceParams = {\n for?: ForPayerType;\n keepPreviousData?: boolean;\n enabled?: boolean;\n};\n\nexport type CreditBalanceResult = {\n data: BillingCreditBalanceResource | undefined | null;\n error: Error | undefined;\n isLoading: boolean;\n isFetching: boolean;\n revalidate: () => Promise<void> | void;\n};\n\n/**\n * @internal\n */\nexport function __internal_useCreditBalanceQuery(params?: UseCreditBalanceParams): CreditBalanceResult {\n useAssertWrappedByClerkProvider(HOOK_NAME);\n\n const clerk = useClerkInstanceContext();\n const user = useUserBase();\n const organization = useOrganizationBase();\n\n const billingEnabled = useBillingIsEnabled(params);\n\n const recordedRef = useRef(false);\n useEffect(() => {\n if (!recordedRef.current && clerk?.telemetry) {\n clerk.telemetry.record(eventMethodCalled(HOOK_NAME));\n recordedRef.current = true;\n }\n }, [clerk]);\n\n const keepPreviousData = params?.keepPreviousData ?? false;\n\n const [queryClient] = useClerkQueryClient();\n\n const { queryKey, invalidationKey, stableKey, authenticated } = useMemo(() => {\n const isOrganization = params?.for === 'organization';\n const safeOrgId = isOrganization ? organization?.id : undefined;\n\n return createCacheKeys({\n stablePrefix: STABLE_KEYS.CREDIT_BALANCE_KEY,\n authenticated: true,\n tracked: {\n userId: user?.id,\n orgId: safeOrgId,\n },\n untracked: {\n args: { orgId: safeOrgId },\n },\n });\n }, [user?.id, organization?.id, params?.for]);\n\n const queriesEnabled = Boolean(user?.id && billingEnabled && (params?.enabled ?? true));\n useClearQueriesOnSignOut({\n isSignedOut: user === null,\n authenticated,\n stableKeys: stableKey,\n });\n\n const query = useClerkQuery({\n queryKey,\n queryFn: ({ queryKey }) => {\n const obj = queryKey[3];\n return clerk.billing.getCreditBalance(obj.args);\n },\n staleTime: 1_000 * 60,\n enabled: queriesEnabled,\n placeholderData: defineKeepPreviousDataFn(keepPreviousData && queriesEnabled),\n });\n\n const revalidate = useCallback(\n () => queryClient.invalidateQueries({ queryKey: invalidationKey }),\n [queryClient, invalidationKey],\n );\n\n return {\n data: query.data,\n error: query.error ?? undefined,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n revalidate,\n };\n}\n","import { useCallback, useEffect, useMemo, useRef } from 'react';\n\nimport { eventMethodCalled } from '../../telemetry/events';\nimport type { BillingCreditLedgerResource, ClerkPaginatedResponse, ForPayerType } from '../../types';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';\nimport { useClerkQueryClient } from '../query/use-clerk-query-client';\nimport { useClerkQuery } from '../query/useQuery';\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useUserBase } from './base/useUserBase';\nimport { createCacheKeys } from './createCacheKeys';\nimport { useBillingIsEnabled } from './useBillingIsEnabled';\nimport { useClearQueriesOnSignOut } from './useClearQueriesOnSignOut';\n\nconst HOOK_NAME = 'useCreditHistory';\n\nexport type UseCreditHistoryParams = {\n for?: ForPayerType;\n enabled?: boolean;\n};\n\nexport type CreditHistoryResult = {\n data: ClerkPaginatedResponse<BillingCreditLedgerResource> | undefined;\n error: Error | undefined;\n isLoading: boolean;\n isFetching: boolean;\n revalidate: () => Promise<void> | void;\n};\n\n/**\n * @internal\n */\nexport function __internal_useCreditHistoryQuery(params?: UseCreditHistoryParams): CreditHistoryResult {\n useAssertWrappedByClerkProvider(HOOK_NAME);\n\n const clerk = useClerkInstanceContext();\n const user = useUserBase();\n const organization = useOrganizationBase();\n\n const billingEnabled = useBillingIsEnabled(params);\n\n const recordedRef = useRef(false);\n useEffect(() => {\n if (!recordedRef.current && clerk?.telemetry) {\n clerk.telemetry.record(eventMethodCalled(HOOK_NAME));\n recordedRef.current = true;\n }\n }, [clerk]);\n\n const [queryClient] = useClerkQueryClient();\n\n const { queryKey, invalidationKey, stableKey, authenticated } = useMemo(() => {\n const isOrganization = params?.for === 'organization';\n const safeOrgId = isOrganization ? organization?.id : undefined;\n\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.CREDIT_HISTORY_KEY,\n authenticated: true,\n tracked: {\n userId: user?.id,\n orgId: safeOrgId,\n },\n untracked: {\n args: { orgId: safeOrgId },\n },\n });\n }, [user?.id, organization?.id, params?.for]);\n\n const queriesEnabled = Boolean(user?.id && billingEnabled && (params?.enabled ?? true));\n useClearQueriesOnSignOut({\n isSignedOut: user === null,\n authenticated,\n stableKeys: stableKey,\n });\n\n const query = useClerkQuery({\n queryKey,\n queryFn: ({ queryKey }) => {\n const obj = queryKey[3];\n return clerk.billing.getCreditHistory(obj.args);\n },\n staleTime: 1_000 * 60,\n enabled: queriesEnabled,\n });\n\n const revalidate = useCallback(\n () => queryClient.invalidateQueries({ queryKey: invalidationKey }),\n [queryClient, invalidationKey],\n );\n\n return {\n data: query.data,\n error: query.error ?? undefined,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n revalidate,\n };\n}\n","import { useMemo } from 'react';\n\nimport type { ForPayerType } from '../../types';\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function useStatementQueryCacheKeys(params: {\n statementId: string | null;\n userId: string | null;\n orgId: string | null;\n for?: ForPayerType;\n}) {\n const { statementId, userId, orgId, for: forType } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.BILLING_STATEMENTS_KEY,\n authenticated: true,\n tracked: {\n statementId,\n forType,\n userId,\n orgId,\n },\n untracked: {\n args: {\n id: statementId ?? undefined,\n orgId: orgId ?? undefined,\n },\n },\n });\n }, [statementId, forType, userId, orgId]);\n}\n","import { useClerkInstanceContext } from '../contexts';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQuery } from '../query/useQuery';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useUserBase } from './base/useUserBase';\nimport { useBillingIsEnabled } from './useBillingIsEnabled';\nimport { useClearQueriesOnSignOut } from './useClearQueriesOnSignOut';\nimport { useStatementQueryCacheKeys } from './useStatementQuery.shared';\nimport type { StatementQueryResult, UseStatementQueryParams } from './useStatementQuery.types';\n\n/**\n * @internal\n */\nfunction useStatementQuery(params: UseStatementQueryParams = {}): StatementQueryResult {\n const { statementId = null, keepPreviousData = false, for: forType = 'user' } = params;\n const clerk = useClerkInstanceContext();\n const user = useUserBase();\n const organization = useOrganizationBase();\n\n const organizationId = forType === 'organization' ? (organization?.id ?? null) : null;\n const userId = user?.id ?? null;\n\n const { queryKey, stableKey, authenticated } = useStatementQueryCacheKeys({\n statementId,\n userId,\n orgId: organizationId,\n for: forType,\n });\n\n const billingEnabled = useBillingIsEnabled(params);\n\n const queryEnabled = Boolean(statementId) && billingEnabled;\n\n useClearQueriesOnSignOut({\n isSignedOut: user === null,\n authenticated,\n stableKeys: stableKey,\n });\n\n const query = useClerkQuery({\n queryKey,\n queryFn: () => {\n if (!statementId) {\n throw new Error('statementId is required to fetch a statement');\n }\n return clerk.billing.getStatement({ id: statementId, orgId: organizationId ?? undefined });\n },\n enabled: queryEnabled,\n placeholderData: defineKeepPreviousDataFn(keepPreviousData),\n staleTime: 1_000 * 60,\n });\n\n return {\n data: query.data,\n error: (query.error ?? null) as StatementQueryResult['error'],\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n };\n}\n\nexport { useStatementQuery as __internal_useStatementQuery };\n","import { useMemo } from 'react';\n\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function usePlanDetailsQueryCacheKeys(params: { planId: string | null }) {\n const { planId } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.BILLING_PLANS_KEY,\n authenticated: false,\n tracked: {\n planId: planId ?? null,\n },\n untracked: {\n args: {\n id: planId ?? undefined,\n },\n },\n });\n }, [planId]);\n}\n","import { useClerkInstanceContext } from '../contexts';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQuery } from '../query/useQuery';\nimport { useBillingIsEnabled } from './useBillingIsEnabled';\nimport { usePlanDetailsQueryCacheKeys } from './usePlanDetailsQuery.shared';\nimport type { PlanDetailsQueryResult, UsePlanDetailsQueryParams } from './usePlanDetailsQuery.types';\n\n/**\n * @internal\n */\nexport function __internal_usePlanDetailsQuery(params: UsePlanDetailsQueryParams = {}): PlanDetailsQueryResult {\n const { planId, initialPlan = null, keepPreviousData = true } = params;\n const clerk = useClerkInstanceContext();\n\n const targetPlanId = planId ?? initialPlan?.id ?? null;\n\n const { queryKey } = usePlanDetailsQueryCacheKeys({ planId: targetPlanId });\n\n const billingEnabled = useBillingIsEnabled({\n authenticated: false,\n });\n\n const queryEnabled = Boolean(targetPlanId) && billingEnabled;\n\n const query = useClerkQuery({\n queryKey,\n queryFn: () => {\n if (!targetPlanId) {\n throw new Error('planId is required to fetch plan details');\n }\n return clerk.billing.getPlan({ id: targetPlanId });\n },\n enabled: queryEnabled,\n initialData: initialPlan ?? undefined,\n placeholderData: defineKeepPreviousDataFn(keepPreviousData),\n initialDataUpdatedAt: 0,\n });\n\n return {\n data: query.data,\n error: (query.error ?? null) as PlanDetailsQueryResult['error'],\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n };\n}\n","import { useMemo } from 'react';\n\nimport type { ForPayerType } from '../../types';\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\nexport function usePaymentAttemptQueryCacheKeys(params: {\n paymentAttemptId: string;\n userId: string | null;\n orgId: string | null;\n for?: ForPayerType;\n}) {\n const { paymentAttemptId, userId, orgId, for: forType } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.PAYMENT_ATTEMPT_KEY,\n authenticated: true,\n tracked: {\n paymentAttemptId,\n forType,\n userId,\n orgId,\n },\n untracked: {\n args: {\n id: paymentAttemptId ?? undefined,\n orgId: orgId ?? undefined,\n },\n },\n });\n }, [paymentAttemptId, forType, userId, orgId]);\n}\n","import { useClerkInstanceContext } from '../contexts';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQuery } from '../query/useQuery';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useUserBase } from './base/useUserBase';\nimport { useBillingIsEnabled } from './useBillingIsEnabled';\nimport { useClearQueriesOnSignOut } from './useClearQueriesOnSignOut';\nimport { usePaymentAttemptQueryCacheKeys } from './usePaymentAttemptQuery.shared';\nimport type { PaymentAttemptQueryResult, UsePaymentAttemptQueryParams } from './usePaymentAttemptQuery.types';\n\n/**\n * @internal\n */\nfunction usePaymentAttemptQuery(params: UsePaymentAttemptQueryParams): PaymentAttemptQueryResult {\n const { paymentAttemptId, keepPreviousData = false, for: forType = 'user' } = params;\n const clerk = useClerkInstanceContext();\n const user = useUserBase();\n const organization = useOrganizationBase();\n\n const organizationId = forType === 'organization' ? (organization?.id ?? null) : null;\n const userId = user?.id ?? null;\n\n const { queryKey, stableKey, authenticated } = usePaymentAttemptQueryCacheKeys({\n paymentAttemptId,\n userId,\n orgId: organizationId,\n for: forType,\n });\n\n const billingEnabled = useBillingIsEnabled(params);\n\n const queryEnabled = Boolean(paymentAttemptId) && billingEnabled;\n\n useClearQueriesOnSignOut({\n isSignedOut: user === null, // works with the transitive state\n authenticated,\n stableKeys: stableKey,\n });\n\n const query = useClerkQuery({\n queryKey,\n queryFn: ({ queryKey }) => {\n const args = queryKey[3].args;\n return clerk.billing.getPaymentAttempt(args);\n },\n enabled: queryEnabled,\n placeholderData: defineKeepPreviousDataFn(keepPreviousData),\n staleTime: 1_000 * 60,\n });\n\n return {\n data: query.data,\n error: (query.error ?? null) as PaymentAttemptQueryResult['error'],\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n };\n}\n\nexport { usePaymentAttemptQuery as __internal_usePaymentAttemptQuery };\n","import { useMemo } from 'react';\n\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\n/**\n * @internal\n */\nexport function useUserEnterpriseConnectionsCacheKeys(params: {\n userId: string | null;\n withOrganizationAccountLinking?: boolean;\n}) {\n const { userId, withOrganizationAccountLinking = false } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.USER_ENTERPRISE_CONNECTIONS_KEY,\n authenticated: Boolean(userId),\n tracked: {\n userId: userId ?? null,\n withOrganizationAccountLinking,\n },\n untracked: {\n args: {},\n },\n });\n }, [userId, withOrganizationAccountLinking]);\n}\n","import { useCallback } from 'react';\n\nimport type { EnterpriseConnectionResource } from '../../types/enterpriseConnection';\nimport { useClerkInstanceContext } from '../contexts';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQueryClient } from '../query/use-clerk-query-client';\nimport { useClerkQuery } from '../query/useQuery';\nimport { useUserBase } from './base/useUserBase';\nimport { useClearQueriesOnSignOut } from './useClearQueriesOnSignOut';\nimport { useUserEnterpriseConnectionsCacheKeys } from './useUserEnterpriseConnections.shared';\n\nexport type UseUserEnterpriseConnectionsParams = {\n enabled?: boolean;\n keepPreviousData?: boolean;\n withOrganizationAccountLinking?: boolean;\n};\n\nexport type UseUserEnterpriseConnectionsReturn = {\n data: EnterpriseConnectionResource[] | undefined;\n error: Error | null;\n isLoading: boolean;\n isFetching: boolean;\n revalidate: () => Promise<void>;\n};\n\n/**\n * Enterprise connections for the signed-in user\n *\n * @internal\n */\nfunction useUserEnterpriseConnections(\n params: UseUserEnterpriseConnectionsParams = {},\n): UseUserEnterpriseConnectionsReturn {\n const { keepPreviousData = true, enabled = true, withOrganizationAccountLinking = false } = params;\n const clerk = useClerkInstanceContext();\n const user = useUserBase();\n const [queryClient] = useClerkQueryClient();\n\n const { queryKey, stableKey, authenticated } = useUserEnterpriseConnectionsCacheKeys({\n userId: user?.id ?? null,\n withOrganizationAccountLinking,\n });\n\n const queryEnabled = enabled && clerk.loaded && Boolean(user);\n\n useClearQueriesOnSignOut({\n isSignedOut: user === null,\n authenticated,\n stableKeys: stableKey,\n });\n\n const query = useClerkQuery({\n queryKey,\n queryFn: () => user?.getEnterpriseConnections({ withOrganizationAccountLinking }),\n enabled: queryEnabled,\n placeholderData: defineKeepPreviousDataFn(keepPreviousData),\n });\n\n const revalidate = useCallback(\n () => queryClient.invalidateQueries({ queryKey: [stableKey] }),\n [queryClient, stableKey],\n );\n\n return {\n data: query.data,\n error: query.error ?? null,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n revalidate,\n };\n}\n\nexport { useUserEnterpriseConnections as __internal_useUserEnterpriseConnections };\n","import { useMemo } from 'react';\n\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\n/**\n * @internal\n */\nexport function useOrganizationEnterpriseConnectionsCacheKeys(params: {\n organizationId: string | null;\n withOrganizationAccountLinking?: boolean;\n}) {\n const { organizationId, withOrganizationAccountLinking = false } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_ENTERPRISE_CONNECTIONS_KEY,\n authenticated: Boolean(organizationId),\n tracked: {\n organizationId: organizationId ?? null,\n withOrganizationAccountLinking,\n },\n untracked: {\n args: {},\n },\n });\n }, [organizationId, withOrganizationAccountLinking]);\n}\n","import { useCallback } from 'react';\n\nimport type { DeletedObjectResource } from '../../types/deletedObject';\nimport type {\n CreateOrganizationEnterpriseConnectionParams,\n EnterpriseConnectionResource,\n UpdateOrganizationEnterpriseConnectionParams,\n} from '../../types/enterpriseConnection';\nimport { useClerkInstanceContext } from '../contexts';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQueryClient } from '../query/use-clerk-query-client';\nimport { useClerkQuery } from '../query/useQuery';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useClearQueriesOnSignOut } from './useClearQueriesOnSignOut';\nimport { useOrganizationEnterpriseConnectionsCacheKeys } from './useOrganizationEnterpriseConnections.shared';\n\nexport type UseOrganizationEnterpriseConnectionsParams = {\n enabled?: boolean;\n keepPreviousData?: boolean;\n withOrganizationAccountLinking?: boolean;\n};\n\nexport type UseOrganizationEnterpriseConnectionsReturn = {\n data: EnterpriseConnectionResource[] | undefined;\n error: Error | null;\n isLoading: boolean;\n isFetching: boolean;\n createEnterpriseConnection: (\n params: CreateOrganizationEnterpriseConnectionParams,\n ) => Promise<EnterpriseConnectionResource | undefined>;\n updateEnterpriseConnection: (\n enterpriseConnectionId: string,\n params: UpdateOrganizationEnterpriseConnectionParams,\n ) => Promise<EnterpriseConnectionResource | undefined>;\n deleteEnterpriseConnection: (enterpriseConnectionId: string) => Promise<DeletedObjectResource | undefined>;\n revalidate: () => Promise<void>;\n};\n\n/**\n * Enterprise connections for the active organization\n *\n * @internal\n */\nfunction useOrganizationEnterpriseConnections(\n params: UseOrganizationEnterpriseConnectionsParams = {},\n): UseOrganizationEnterpriseConnectionsReturn {\n const { keepPreviousData = true, enabled = true, withOrganizationAccountLinking = false } = params;\n const clerk = useClerkInstanceContext();\n const organization = useOrganizationBase();\n const [queryClient] = useClerkQueryClient();\n\n const { queryKey, stableKey, authenticated } = useOrganizationEnterpriseConnectionsCacheKeys({\n organizationId: organization?.id ?? null,\n withOrganizationAccountLinking,\n });\n\n const queryEnabled = enabled && clerk.loaded && Boolean(organization);\n\n useClearQueriesOnSignOut({\n isSignedOut: organization === null,\n authenticated,\n stableKeys: stableKey,\n });\n\n const query = useClerkQuery({\n queryKey,\n queryFn: () => organization?.getEnterpriseConnections({ withOrganizationAccountLinking }),\n enabled: queryEnabled,\n placeholderData: defineKeepPreviousDataFn(keepPreviousData),\n });\n\n const revalidate = useCallback(\n () => queryClient.invalidateQueries({ queryKey: [stableKey] }),\n [queryClient, stableKey],\n );\n\n const createEnterpriseConnection = useCallback(\n async (createParams: CreateOrganizationEnterpriseConnectionParams) => {\n const created = await organization?.createEnterpriseConnection(createParams);\n await revalidate();\n return created;\n },\n [organization, revalidate],\n );\n\n const updateEnterpriseConnection = useCallback(\n async (enterpriseConnectionId: string, updateParams: UpdateOrganizationEnterpriseConnectionParams) => {\n const updated = await organization?.updateEnterpriseConnection(enterpriseConnectionId, updateParams);\n await revalidate();\n return updated;\n },\n [organization, revalidate],\n );\n\n const deleteEnterpriseConnection = useCallback(\n async (enterpriseConnectionId: string) => {\n const deleted = await organization?.deleteEnterpriseConnection(enterpriseConnectionId);\n await revalidate();\n return deleted;\n },\n [organization, revalidate],\n );\n\n return {\n data: query.data,\n error: query.error ?? null,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n createEnterpriseConnection,\n updateEnterpriseConnection,\n deleteEnterpriseConnection,\n revalidate,\n };\n}\n\nexport { useOrganizationEnterpriseConnections as __internal_useOrganizationEnterpriseConnections };\n","import { useMemo } from 'react';\n\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\n/**\n * @internal\n */\nexport function useOrganizationDomainsCacheKeys(params: { organizationId: string | null; enrollmentMode?: string }) {\n const { organizationId, enrollmentMode } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_DOMAINS_KEY,\n authenticated: Boolean(organizationId),\n tracked: {\n organizationId: organizationId ?? null,\n enrollmentMode: enrollmentMode ?? null,\n },\n untracked: {\n args: {},\n },\n });\n }, [organizationId, enrollmentMode]);\n}\n","import { useCallback, useEffect, useMemo, useRef } from 'react';\n\nimport { logger } from '../../logger';\nimport type { GetDomainsParams } from '../../types/organization';\nimport type {\n OrganizationDomainResource,\n OrganizationDomainsBulkOwnershipVerificationResource,\n OrganizationEnrollmentMode,\n} from '../../types/organizationDomain';\nimport { useClerkInstanceContext } from '../contexts';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQueryClient } from '../query/use-clerk-query-client';\nimport { useClerkQuery } from '../query/useQuery';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useClearQueriesOnSignOut } from './useClearQueriesOnSignOut';\nimport { useOrganizationDomainsCacheKeys } from './useOrganizationDomains.shared';\n\nconst OWNERSHIP_VERIFICATION_POLL_INTERVAL_MS = 10_000;\n\nexport type UseOrganizationDomainsParams = {\n enabled?: boolean;\n keepPreviousData?: boolean;\n /**\n * Filter the returned domains by enrollment mode.\n */\n enrollmentMode?: OrganizationEnrollmentMode;\n /**\n * Invoked from the ownership-verification poll whenever an `attempt` resolves\n * one or more domains as `verified`.\n */\n onOwnershipVerified?: (verifiedDomains: OrganizationDomainResource[]) => void | Promise<void>;\n};\n\nexport type UseOrganizationDomainsReturn = {\n data: OrganizationDomainResource[] | undefined;\n totalCount: number | undefined;\n error: Error | null;\n isLoading: boolean;\n isFetching: boolean;\n /**\n * Creates a new domain for the active organization, derived from the given name.\n */\n createDomain: (name: string) => Promise<OrganizationDomainResource | undefined>;\n /**\n * Issues a fresh TXT challenge for each of the given domains in a single\n * request. Each resolved domain's `ownershipVerification` carries the\n * `txtRecordName` and `txtRecordValue`.\n */\n prepareOwnershipVerification: (\n domains: OrganizationDomainResource[],\n ) => Promise<OrganizationDomainsBulkOwnershipVerificationResource | undefined>;\n /**\n * Resolves the published TXT records for the given domains to complete ownership verification.\n */\n attemptOwnershipVerification: (\n domains: OrganizationDomainResource[],\n ) => Promise<OrganizationDomainsBulkOwnershipVerificationResource | undefined>;\n revalidate: () => Promise<void>;\n};\n\n/**\n * Domains for the active organization.\n *\n * @internal\n */\nfunction useOrganizationDomains(params: UseOrganizationDomainsParams = {}): UseOrganizationDomainsReturn {\n const { keepPreviousData = true, enabled = true, enrollmentMode, onOwnershipVerified } = params;\n const clerk = useClerkInstanceContext();\n const organization = useOrganizationBase();\n const [queryClient] = useClerkQueryClient();\n\n const onOwnershipVerifiedRef = useRef(onOwnershipVerified);\n onOwnershipVerifiedRef.current = onOwnershipVerified;\n\n const { queryKey, stableKey, authenticated } = useOrganizationDomainsCacheKeys({\n organizationId: organization?.id ?? null,\n enrollmentMode,\n });\n\n const queryEnabled = enabled && clerk.loaded && Boolean(organization);\n\n useClearQueriesOnSignOut({\n isSignedOut: organization === null,\n authenticated,\n stableKeys: stableKey,\n });\n\n const fetchParams: GetDomainsParams | undefined = enrollmentMode ? { enrollmentMode } : undefined;\n\n const query = useClerkQuery({\n queryKey,\n queryFn: () => organization?.getDomains(fetchParams),\n enabled: queryEnabled,\n placeholderData: defineKeepPreviousDataFn(keepPreviousData),\n });\n\n const revalidate = useCallback(\n () => queryClient.invalidateQueries({ queryKey: [stableKey] }),\n [queryClient, stableKey],\n );\n\n const createDomain = useCallback(\n async (name: string) => {\n let created = await organization?.createDomain(name, enrollmentMode ? { enrollmentMode } : undefined);\n\n if (created && enrollmentMode === 'enterprise_sso') {\n const prepared = await organization?.prepareOwnershipVerification([created.id]);\n created = prepared?.data[0] ?? created;\n }\n\n await revalidate();\n return created;\n },\n [organization, revalidate, enrollmentMode],\n );\n\n const prepareOwnershipVerification = useCallback(\n async (domains: OrganizationDomainResource[]) => {\n const prepared = await organization?.prepareOwnershipVerification(domains.map(domain => domain.id));\n await revalidate();\n return prepared;\n },\n [organization, revalidate],\n );\n\n const attemptOwnershipVerification = useCallback(\n async (domains: OrganizationDomainResource[]) => {\n const attempted = await organization?.attemptOwnershipVerification(domains.map(domain => domain.id));\n await revalidate();\n return attempted;\n },\n [organization, revalidate],\n );\n\n const response = query.data;\n\n const unverifiedOwnershipDomainIds = useMemo(\n () =>\n (response?.data ?? [])\n .filter((domain: OrganizationDomainResource) => domain.ownershipVerification?.status === 'unverified')\n .map((domain: OrganizationDomainResource) => domain.id),\n [response?.data],\n );\n\n const unverifiedOwnershipKey = unverifiedOwnershipDomainIds.join(',');\n\n // Poll `attempt_ownership_verification` for the outstanding unverified domains\n // until none remain.\n useEffect(() => {\n if (!queryEnabled || !organization || !unverifiedOwnershipKey) {\n return;\n }\n\n let cancelled = false;\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const scheduleNext = () => {\n timeoutId = setTimeout(() => void runAttempt(), OWNERSHIP_VERIFICATION_POLL_INTERVAL_MS);\n };\n\n const domainIds = unverifiedOwnershipKey.split(',');\n\n const runAttempt = async () => {\n const result = await organization.attemptOwnershipVerification(domainIds).catch((error: unknown) => {\n logger.warnOnce(`Clerk: failed to attempt organization domain ownership verification: ${error}`);\n return undefined;\n });\n if (cancelled) {\n return;\n }\n\n // Refetch the domains list after every attempt so the UI reflects the\n // latest ownership status\n await revalidate();\n if (cancelled) {\n return;\n }\n\n const verifiedDomains = result?.data.filter(domain => domain.ownershipVerification?.status === 'verified') ?? [];\n if (verifiedDomains.length) {\n await onOwnershipVerifiedRef.current?.(verifiedDomains);\n }\n if (cancelled) {\n return;\n }\n\n // Stop polling once every domain in the attempt response is verified\n const allVerified =\n !!result?.data.length && result.data.every(domain => domain.ownershipVerification?.status === 'verified');\n if (allVerified) {\n return;\n }\n\n scheduleNext();\n };\n\n scheduleNext();\n\n return () => {\n cancelled = true;\n clearTimeout(timeoutId);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [unverifiedOwnershipKey, queryEnabled]);\n\n return {\n data: response?.data,\n totalCount: response?.total_count,\n error: query.error ?? null,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n createDomain,\n prepareOwnershipVerification,\n attemptOwnershipVerification,\n revalidate,\n };\n}\n\nexport { useOrganizationDomains as __internal_useOrganizationDomains };\n","import { useMemo } from 'react';\n\nimport type { GetEnterpriseConnectionTestRunsParams } from '../../types/enterpriseConnectionTestRun';\nimport { INTERNAL_STABLE_KEYS } from '../stable-keys';\nimport { createCacheKeys } from './createCacheKeys';\n\n/**\n * @internal\n */\nexport function useOrganizationEnterpriseConnectionTestRunsCacheKeys(params: {\n organizationId: string | null;\n enterpriseConnectionId: string | null;\n args: GetEnterpriseConnectionTestRunsParams;\n}) {\n const { organizationId, enterpriseConnectionId, args } = params;\n return useMemo(() => {\n return createCacheKeys({\n stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_ENTERPRISE_CONNECTION_TEST_RUNS_KEY,\n authenticated: Boolean(organizationId),\n tracked: {\n organizationId: organizationId ?? null,\n enterpriseConnectionId: enterpriseConnectionId ?? null,\n },\n untracked: {\n args,\n },\n });\n // The args object is intentionally serialized via the consumer to keep stability.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [organizationId, enterpriseConnectionId, JSON.stringify(args)]);\n}\n","import { useCallback, useEffect, useState } from 'react';\n\nimport type {\n EnterpriseConnectionTestRunResource,\n GetEnterpriseConnectionTestRunsParams,\n} from '../../types/enterpriseConnectionTestRun';\nimport { useClerkInstanceContext } from '../contexts';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQueryClient } from '../query/use-clerk-query-client';\nimport { useClerkQuery } from '../query/useQuery';\nimport { useOrganizationBase } from './base/useOrganizationBase';\nimport { useClearQueriesOnSignOut } from './useClearQueriesOnSignOut';\nimport { useOrganizationEnterpriseConnectionTestRunsCacheKeys } from './useOrganizationEnterpriseConnectionTestRuns.shared';\n\nconst DEFAULT_POLL_INTERVAL_MS = 2_000;\n\nexport type UseOrganizationEnterpriseConnectionTestRunsParams = {\n enterpriseConnectionId: string | null;\n /**\n * Pass-through fetch parameters (pagination, status filter).\n * Defaults to `{ initialPage: 1, pageSize: 10 }`.\n */\n params?: GetEnterpriseConnectionTestRunsParams;\n /**\n * Polling interval (ms) applied between `revalidate()` and the moment the\n * first record arrives in the response.\n *\n * @default 2000\n */\n pollIntervalMs?: number;\n /**\n * If `false`, the hook is dormant — no fetch, no polling.\n *\n * @default true\n */\n enabled?: boolean;\n /**\n * When `true`, a background refetch keeps the previously-loaded page visible\n * (`isFetching` stays `true`, `isLoading` does not flip back to `true`) instead\n * of clearing to a cold-load state.\n *\n * @default false\n */\n keepPreviousData?: boolean;\n};\n\n/**\n * The freshly-fetched page surfaced by `revalidate`, read straight from the\n * cache once the refetch settles. Lets a caller gate on the up-to-date result\n * synchronously after `await`, instead of waiting for the hook to re-render with\n * the new React state (whose value is still the pre-refetch one inside the\n * caller's closure).\n */\nexport type UseOrganizationEnterpriseConnectionTestRunsRevalidateResult = {\n data: EnterpriseConnectionTestRunResource[] | undefined;\n totalCount: number | undefined;\n};\n\nexport type UseOrganizationEnterpriseConnectionTestRunsReturn = {\n data: EnterpriseConnectionTestRunResource[] | undefined;\n totalCount: number | undefined;\n error: Error | null;\n isLoading: boolean;\n isFetching: boolean;\n /**\n * `true` while the hook is actively polling for the first record to appear\n */\n isPolling: boolean;\n /**\n * Force a refetch, resolving with the freshly-fetched page once it settles.\n *\n * By default this also arms polling when the list is currently empty, so a run\n * kicked off elsewhere is picked up as it lands. Pass `{ armPolling: false }`\n * for an entry/pagination refetch that should never arm polling merely because\n * the list happens to be empty — polling is then armed only by an explicit\n * `revalidate()` (or `revalidate({ armPolling: true })`) after a run is kicked\n * off.\n */\n revalidate: (\n options?: RevalidateTestRunsOptions,\n ) => Promise<UseOrganizationEnterpriseConnectionTestRunsRevalidateResult>;\n};\n\nexport type RevalidateTestRunsOptions = {\n /**\n * Whether to arm polling for the first record when the list is currently\n * empty.\n *\n * @default true\n */\n armPolling?: boolean;\n /**\n * Invalidate only this query's exact `queryKey` instead of the broad\n * org+connection `invalidationKey`. The default broad invalidation\n * prefix-matches every test-runs query for the connection, so a sibling query\n * (e.g. a success probe sharing the org+connection key with the visible list)\n * refetches too. Pass `true` to refetch ONLY this query and leave the siblings\n * — and their loading indicators — untouched.\n *\n * @default false\n */\n exact?: boolean;\n};\n\n/**\n * Subscribes to the list of enterprise-connection test runs for the active organization\n *\n * @internal\n */\nfunction useOrganizationEnterpriseConnectionTestRuns(\n params: UseOrganizationEnterpriseConnectionTestRunsParams,\n): UseOrganizationEnterpriseConnectionTestRunsReturn {\n const {\n enterpriseConnectionId,\n params: fetchParams = { initialPage: 1, pageSize: 10 },\n pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,\n enabled = true,\n keepPreviousData = false,\n } = params;\n\n const clerk = useClerkInstanceContext();\n const organization = useOrganizationBase();\n const [queryClient] = useClerkQueryClient();\n\n const { queryKey, invalidationKey, stableKey, authenticated } = useOrganizationEnterpriseConnectionTestRunsCacheKeys({\n organizationId: organization?.id ?? null,\n enterpriseConnectionId,\n args: fetchParams,\n });\n\n useClearQueriesOnSignOut({\n isSignedOut: organization === null,\n authenticated,\n stableKeys: stableKey,\n });\n\n const queryEnabled = enabled && clerk.loaded && Boolean(organization) && Boolean(enterpriseConnectionId);\n\n const [shouldPoll, setShouldPoll] = useState(false);\n\n useEffect(() => {\n // Polling intent is scoped to the current connection — clear it when the\n // connection changes so a reset/recreate doesn't inherit a stale armed poll.\n setShouldPoll(false);\n }, [enterpriseConnectionId]);\n\n const query = useClerkQuery({\n queryKey,\n queryFn: () => {\n if (!enterpriseConnectionId) {\n throw new Error('enterpriseConnectionId is required to fetch test runs');\n }\n return organization?.getEnterpriseConnectionTestRuns(enterpriseConnectionId, fetchParams);\n },\n refetchInterval: q => {\n if (!shouldPoll) {\n return false;\n }\n\n const hasRows = (q.state.data?.data?.length ?? 0) > 0;\n return hasRows ? false : pollIntervalMs;\n },\n enabled: queryEnabled,\n refetchIntervalInBackground: false,\n placeholderData: defineKeepPreviousDataFn(keepPreviousData),\n });\n\n const hasRows = (query.data?.data?.length ?? 0) > 0;\n\n useEffect(() => {\n if (shouldPoll && hasRows) {\n setShouldPoll(false);\n }\n }, [shouldPoll, hasRows]);\n\n const revalidate = useCallback(\n async (\n options?: RevalidateTestRunsOptions,\n ): Promise<UseOrganizationEnterpriseConnectionTestRunsRevalidateResult> => {\n // Arm polling only when the caller opts in (the default) AND there is\n // nothing in the list yet. An entry/pagination refetch passes\n // `armPolling: false` so an empty list on entry never arms polling on its\n // own — that stays the job of an explicit refetch after a run is kicked\n // off. Once any record has been seen, this is a one-shot refetch.\n const armPolling = options?.armPolling ?? true;\n if (armPolling && !hasRows) {\n setShouldPoll(true);\n }\n // `invalidateQueries` awaits the refetch it triggers, so by the time it\n // resolves the cache already holds the fresh page. Read it back from the\n // cache by the exact `queryKey` (not the broader `invalidationKey`) and\n // resolve with it, so a caller can gate on the up-to-date result right\n // after `await` — this hook's own `data` state is still the pre-refetch\n // value inside the caller's closure until a re-render lands.\n //\n // `exact` scopes the invalidation: the broad `invalidationKey` (org +\n // connection, no fetch params) prefix-matches every test-runs query for\n // the connection, so it refetches this query AND its siblings (the success\n // probe alongside the visible list). `exact: true` invalidates only this\n // query's own `queryKey`, leaving sibling queries untouched.\n if (options?.exact) {\n await queryClient.invalidateQueries({ queryKey, exact: true });\n } else {\n await queryClient.invalidateQueries({ queryKey: invalidationKey });\n }\n const fresh = queryClient.getQueryData<{\n data?: EnterpriseConnectionTestRunResource[];\n total_count?: number;\n }>(queryKey);\n return { data: fresh?.data, totalCount: fresh?.total_count };\n },\n [queryClient, invalidationKey, queryKey, hasRows],\n );\n\n const isPolling = queryEnabled && shouldPoll && !hasRows;\n\n return {\n data: query.data?.data,\n totalCount: query.data?.total_count,\n error: query.error ?? null,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n isPolling,\n revalidate,\n };\n}\n\nexport { useOrganizationEnterpriseConnectionTestRuns as __internal_useOrganizationEnterpriseConnectionTestRuns };\n","import { clerkCoreErrorNoClerkSingleton } from '../internal/clerk-js/errors';\nimport type { Clerk } from '../types';\n\nexport function assertClerkSingletonExists(clerk: Clerk | undefined): asserts clerk is Clerk {\n if (!clerk) {\n clerkCoreErrorNoClerkSingleton();\n }\n}\n","import React from 'react';\n\nimport type { Clerk, ClerkStatus, InitialState, LoadedClerk } from '../types';\nimport {\n __experimental_CheckoutProvider as CheckoutProvider,\n ClerkInstanceContext,\n InitialStateProvider,\n} from './contexts';\nimport { assertClerkSingletonExists } from './utils';\n\ntype ClerkContextProps = {\n clerk: Clerk;\n clerkStatus?: ClerkStatus;\n children: React.ReactNode;\n initialState?: InitialState | Promise<InitialState>;\n};\n\nexport function ClerkContextProvider(props: ClerkContextProps): JSX.Element | null {\n const clerk = props.clerk as LoadedClerk;\n\n assertClerkSingletonExists(clerk);\n\n // The initialState hook has the same check, but it's better to fail early\n if (props.initialState instanceof Promise && !('use' in React && typeof React.use === 'function')) {\n throw new Error('initialState cannot be a promise if React version is less than 19');\n }\n\n const clerkCtx = React.useMemo(\n () => ({ value: clerk }),\n // clerkStatus is a way to control the referential integrity of the clerk object from the outside,\n // we only change the context value when the status changes. Since clerk is mutable, any read from\n // the object will always be the latest value anyway.\n [props.clerkStatus],\n );\n\n return (\n <InitialStateProvider initialState={props.initialState}>\n <ClerkInstanceContext.Provider value={clerkCtx}>\n <CheckoutProvider\n // @ts-expect-error - value is not used\n value={undefined}\n >\n {props.children}\n </CheckoutProvider>\n </ClerkInstanceContext.Provider>\n </InitialStateProvider>\n );\n}\n","import type { StripeElement } from '@stripe/stripe-js';\nimport { useEffect, useRef } from 'react';\n\nexport const usePrevious = <T>(value: T): T => {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref.current;\n};\n\nexport const useAttachEvent = <A extends unknown[]>(\n element: StripeElement | null,\n event: string,\n cb?: (...args: A) => any,\n) => {\n const cbDefined = !!cb;\n const cbRef = useRef(cb);\n\n // In many integrations the callback prop changes on each render.\n // Using a ref saves us from calling element.on/.off every render.\n useEffect(() => {\n cbRef.current = cb;\n }, [cb]);\n\n useEffect(() => {\n if (!cbDefined || !element) {\n return () => {};\n }\n\n const decoratedCb = (...args: A): void => {\n if (cbRef.current) {\n cbRef.current(...args);\n }\n };\n\n (element as any).on(event, decoratedCb);\n\n return () => {\n (element as any).off(event, decoratedCb);\n };\n }, [cbDefined, event, element, cbRef]);\n};\n","/**\n * Original source: https://github.com/stripe/react-stripe-js.\n *\n * The current version of this file is a fork of the original version.\n * The main difference is that we have kept only the necessary parts of the file.\n * This is because we don't need it and it's not used in the Clerk codebase.\n *\n * The original version of this file is licensed under the MIT license.\n * Https://github.com/stripe/react-stripe-js/blob/master/LICENSE.\n */\n\nimport type { ElementProps, PaymentElementProps } from '@stripe/react-stripe-js';\nimport type {\n Stripe,\n StripeElement,\n StripeElements,\n StripeElementsOptions,\n StripeElementType,\n} from '@stripe/stripe-js';\nimport type { FunctionComponent, PropsWithChildren, ReactNode } from 'react';\nimport React, { useState } from 'react';\n\nimport { useAttachEvent, usePrevious } from './utils';\n\ninterface ElementsContextValue {\n elements: StripeElements | null;\n stripe: Stripe | null;\n}\n\nconst ElementsContext = React.createContext<ElementsContextValue | null>(null);\nElementsContext.displayName = 'ElementsContext';\n\nconst parseElementsContext = (ctx: ElementsContextValue | null, useCase: string): ElementsContextValue => {\n if (!ctx) {\n throw new Error(\n `Could not find Elements context; You need to wrap the part of your app that ${useCase} in an <Elements> provider.`,\n );\n }\n\n return ctx;\n};\n\ninterface ElementsProps {\n /**\n * A [Stripe object](https://stripe.com/docs/js/initializing) or a `Promise` resolving to a `Stripe` object.\n * The easiest way to initialize a `Stripe` object is with the the [Stripe.js wrapper module](https://github.com/stripe/stripe-js/blob/master/README.md#readme).\n * Once this prop has been set, it can not be changed.\n *\n * You can also pass in `null` or a `Promise` resolving to `null` if you are performing an initial server-side render or when generating a static site.\n */\n stripe: PromiseLike<Stripe | null> | Stripe | null;\n\n /**\n * Optional [Elements configuration options](https://stripe.com/docs/js/elements_object/create).\n * Once the stripe prop has been set, these options cannot be changed.\n */\n options?: StripeElementsOptions;\n}\n\ntype UnknownOptions = { [k: string]: unknown };\n\ninterface PrivateElementsProps {\n stripe: unknown;\n options?: UnknownOptions;\n children?: ReactNode;\n}\n\n/**\n * 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.\n * Render an `Elements` provider at the root of your React app so that it is available everywhere you need it.\n *\n * To use the `Elements` provider, call `loadStripe` from `@stripe/stripe-js` with your publishable key.\n * The `loadStripe` function will asynchronously load the Stripe.js script and initialize a `Stripe` object.\n * Pass the returned `Promise` to `Elements`.\n *\n * @docs https://stripe.com/docs/stripe-js/react#elements-provider\n */\nconst Elements: FunctionComponent<PropsWithChildren<ElementsProps>> = (({\n stripe: rawStripeProp,\n options,\n children,\n}: PrivateElementsProps) => {\n const parsed = React.useMemo(() => parseStripeProp(rawStripeProp), [rawStripeProp]);\n\n // For a sync stripe instance, initialize into context\n const [ctx, setContext] = React.useState<ElementsContextValue>(() => ({\n stripe: parsed.tag === 'sync' ? parsed.stripe : null,\n elements: parsed.tag === 'sync' ? parsed.stripe.elements(options) : null,\n }));\n\n React.useEffect(() => {\n let isMounted = true;\n\n const safeSetContext = (stripe: Stripe) => {\n setContext(ctx => {\n // no-op if we already have a stripe instance (https://github.com/stripe/react-stripe-js/issues/296)\n if (ctx.stripe) {\n return ctx;\n }\n return {\n stripe,\n elements: stripe.elements(options),\n };\n });\n };\n\n // For an async stripePromise, store it in context once resolved\n if (parsed.tag === 'async' && !ctx.stripe) {\n parsed.stripePromise.then(stripe => {\n if (stripe && isMounted) {\n // Only update Elements context if the component is still mounted\n // and stripe is not null. We allow stripe to be null to make\n // handling SSR easier.\n safeSetContext(stripe);\n }\n });\n } else if (parsed.tag === 'sync' && !ctx.stripe) {\n // Or, handle a sync stripe instance going from null -> populated\n safeSetContext(parsed.stripe);\n }\n\n return () => {\n isMounted = false;\n };\n }, [parsed, ctx, options]);\n\n // Warn on changes to stripe prop\n const prevStripe = usePrevious(rawStripeProp);\n React.useEffect(() => {\n if (prevStripe !== null && prevStripe !== rawStripeProp) {\n console.warn('Unsupported prop change on Elements: You cannot change the `stripe` prop after setting it.');\n }\n }, [prevStripe, rawStripeProp]);\n\n // Apply updates to elements when options prop has relevant changes\n const prevOptions = usePrevious(options);\n React.useEffect(() => {\n if (!ctx.elements) {\n return;\n }\n\n const updates = extractAllowedOptionsUpdates(options, prevOptions, ['clientSecret', 'fonts']);\n\n if (updates) {\n ctx.elements.update(updates);\n }\n }, [options, prevOptions, ctx.elements]);\n\n return <ElementsContext.Provider value={ctx}>{children}</ElementsContext.Provider>;\n}) as FunctionComponent<PropsWithChildren<ElementsProps>>;\n\nconst useElementsContextWithUseCase = (useCaseMessage: string): ElementsContextValue => {\n const ctx = React.useContext(ElementsContext);\n return parseElementsContext(ctx, useCaseMessage);\n};\n\nconst useElements = (): StripeElements | null => {\n const { elements } = useElementsContextWithUseCase('calls useElements()');\n return elements;\n};\n\nconst INVALID_STRIPE_ERROR =\n '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.';\n\n// We are using types to enforce the `stripe` prop in this lib, but in a real\n// integration `stripe` could be anything, so we need to do some sanity\n// validation to prevent type errors.\nconst validateStripe = (maybeStripe: unknown, errorMsg = INVALID_STRIPE_ERROR): null | Stripe => {\n if (maybeStripe === null || isStripe(maybeStripe)) {\n return maybeStripe;\n }\n\n throw new Error(errorMsg);\n};\n\ntype ParsedStripeProp =\n | { tag: 'empty' }\n | { tag: 'sync'; stripe: Stripe }\n | { tag: 'async'; stripePromise: Promise<Stripe | null> };\n\nconst parseStripeProp = (raw: unknown, errorMsg = INVALID_STRIPE_ERROR): ParsedStripeProp => {\n if (isPromise(raw)) {\n return {\n tag: 'async',\n stripePromise: Promise.resolve(raw).then(result => validateStripe(result, errorMsg)),\n };\n }\n\n const stripe = validateStripe(raw, errorMsg);\n\n if (stripe === null) {\n return { tag: 'empty' };\n }\n\n return { tag: 'sync', stripe };\n};\n\nconst isUnknownObject = (raw: unknown): raw is { [key in PropertyKey]: unknown } => {\n return raw !== null && typeof raw === 'object';\n};\n\nconst isPromise = (raw: unknown): raw is PromiseLike<unknown> => {\n return isUnknownObject(raw) && typeof raw.then === 'function';\n};\n\n// We are using types to enforce the `stripe` prop in this lib,\n// but in an untyped integration `stripe` could be anything, so we need\n// to do some sanity validation to prevent type errors.\nconst isStripe = (raw: unknown): raw is Stripe => {\n return (\n isUnknownObject(raw) &&\n typeof raw.elements === 'function' &&\n typeof raw.createToken === 'function' &&\n typeof raw.createPaymentMethod === 'function' &&\n typeof raw.confirmCardPayment === 'function'\n );\n};\n\nconst extractAllowedOptionsUpdates = (\n options: unknown | void,\n prevOptions: unknown | void,\n immutableKeys: string[],\n): UnknownOptions | null => {\n if (!isUnknownObject(options)) {\n return null;\n }\n\n return Object.keys(options).reduce((newOptions: null | UnknownOptions, key) => {\n const isUpdated = !isUnknownObject(prevOptions) || !isEqual(options[key], prevOptions[key]);\n\n if (immutableKeys.includes(key)) {\n if (isUpdated) {\n console.warn(`Unsupported prop change: options.${key} is not a mutable property.`);\n }\n\n return newOptions;\n }\n\n if (!isUpdated) {\n return newOptions;\n }\n\n return { ...(newOptions || {}), [key]: options[key] };\n }, null);\n};\n\nconst PLAIN_OBJECT_STR = '[object Object]';\n\nconst isEqual = (left: unknown, right: unknown): boolean => {\n if (!isUnknownObject(left) || !isUnknownObject(right)) {\n return left === right;\n }\n\n const leftArray = Array.isArray(left);\n const rightArray = Array.isArray(right);\n\n if (leftArray !== rightArray) {\n return false;\n }\n\n const leftPlainObject = Object.prototype.toString.call(left) === PLAIN_OBJECT_STR;\n const rightPlainObject = Object.prototype.toString.call(right) === PLAIN_OBJECT_STR;\n\n if (leftPlainObject !== rightPlainObject) {\n return false;\n }\n\n // not sure what sort of special object this is (regexp is one option), so\n // fallback to reference check.\n if (!leftPlainObject && !leftArray) {\n return left === right;\n }\n\n const leftKeys = Object.keys(left);\n const rightKeys = Object.keys(right);\n\n if (leftKeys.length !== rightKeys.length) {\n return false;\n }\n\n const keySet: { [key: string]: boolean } = {};\n for (let i = 0; i < leftKeys.length; i += 1) {\n keySet[leftKeys[i]] = true;\n }\n for (let i = 0; i < rightKeys.length; i += 1) {\n keySet[rightKeys[i]] = true;\n }\n const allKeys = Object.keys(keySet);\n if (allKeys.length !== leftKeys.length) {\n return false;\n }\n\n const l = left;\n const r = right;\n const pred = (key: string): boolean => {\n return isEqual(l[key], r[key]);\n };\n\n return allKeys.every(pred);\n};\n\nconst useStripe = (): Stripe | null => {\n const { stripe } = useElementsOrCheckoutSdkContextWithUseCase('calls useStripe()');\n return stripe;\n};\n\nconst useElementsOrCheckoutSdkContextWithUseCase = (useCaseString: string): ElementsContextValue => {\n const elementsContext = React.useContext(ElementsContext);\n\n return parseElementsContext(elementsContext, useCaseString);\n};\n\ntype UnknownCallback = (...args: unknown[]) => any;\n\ninterface PrivateElementProps {\n id?: string;\n className?: string;\n fallback?: ReactNode;\n onChange?: UnknownCallback;\n onBlur?: UnknownCallback;\n onFocus?: UnknownCallback;\n onEscape?: UnknownCallback;\n onReady?: UnknownCallback;\n onClick?: UnknownCallback;\n onLoadError?: UnknownCallback;\n onLoaderStart?: UnknownCallback;\n onNetworksChange?: UnknownCallback;\n onConfirm?: UnknownCallback;\n onCancel?: UnknownCallback;\n onShippingAddressChange?: UnknownCallback;\n onShippingRateChange?: UnknownCallback;\n options?: UnknownOptions;\n}\n\nconst capitalized = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);\n\nconst createElementComponent = (type: StripeElementType, isServer: boolean): FunctionComponent<ElementProps> => {\n const displayName = `${capitalized(type)}Element`;\n\n const ClientElement: FunctionComponent<PrivateElementProps> = ({\n id,\n className,\n fallback,\n options = {},\n onBlur,\n onFocus,\n onReady,\n onChange,\n onEscape,\n onClick,\n onLoadError,\n onLoaderStart,\n onNetworksChange,\n onConfirm,\n onCancel,\n onShippingAddressChange,\n onShippingRateChange,\n }) => {\n const ctx = useElementsOrCheckoutSdkContextWithUseCase(`mounts <${displayName}>`);\n const elements = 'elements' in ctx ? ctx.elements : null;\n const [element, setElement] = React.useState<StripeElement | null>(null);\n const elementRef = React.useRef<StripeElement | null>(null);\n const domNode = React.useRef<HTMLDivElement | null>(null);\n const [isReady, setReady] = useState(false);\n\n // For every event where the merchant provides a callback, call element.on\n // with that callback. If the merchant ever changes the callback, removes\n // the old callback with element.off and then call element.on with the new one.\n useAttachEvent(element, 'blur', onBlur);\n useAttachEvent(element, 'focus', onFocus);\n useAttachEvent(element, 'escape', onEscape);\n useAttachEvent(element, 'click', onClick);\n useAttachEvent(element, 'loaderror', onLoadError);\n useAttachEvent(element, 'loaderstart', onLoaderStart);\n useAttachEvent(element, 'networkschange', onNetworksChange);\n useAttachEvent(element, 'confirm', onConfirm);\n useAttachEvent(element, 'cancel', onCancel);\n useAttachEvent(element, 'shippingaddresschange', onShippingAddressChange);\n useAttachEvent(element, 'shippingratechange', onShippingRateChange);\n useAttachEvent(element, 'change', onChange);\n\n let readyCallback: UnknownCallback | undefined;\n if (onReady) {\n // For other Elements, pass through the Element itself.\n readyCallback = () => {\n setReady(true);\n onReady(element);\n };\n }\n\n useAttachEvent(element, 'ready', readyCallback);\n\n React.useLayoutEffect(() => {\n if (elementRef.current === null && domNode.current !== null && elements) {\n let newElement: StripeElement | null = null;\n if (elements) {\n newElement = elements.create(type as any, options);\n }\n\n // Store element in a ref to ensure it's _immediately_ available in cleanup hooks in StrictMode\n elementRef.current = newElement;\n // Store element in state to facilitate event listener attachment\n setElement(newElement);\n\n if (newElement) {\n newElement.mount(domNode.current);\n }\n }\n }, [elements, options]);\n\n const prevOptions = usePrevious(options);\n React.useEffect(() => {\n if (!elementRef.current) {\n return;\n }\n\n const updates = extractAllowedOptionsUpdates(options, prevOptions, ['paymentRequest']);\n\n if (updates && 'update' in elementRef.current) {\n elementRef.current.update(updates);\n }\n }, [options, prevOptions]);\n\n React.useLayoutEffect(() => {\n return () => {\n if (elementRef.current && typeof elementRef.current.destroy === 'function') {\n try {\n elementRef.current.destroy();\n elementRef.current = null;\n } catch {\n // Do nothing\n }\n }\n };\n }, []);\n\n return (\n <>\n {!isReady && fallback}\n <div\n id={id}\n style={{\n height: isReady ? 'unset' : '0px',\n visibility: isReady ? 'visible' : 'hidden',\n }}\n className={className}\n ref={domNode}\n />\n </>\n );\n };\n\n // Only render the Element wrapper in a server environment.\n const ServerElement: FunctionComponent<PrivateElementProps> = props => {\n useElementsOrCheckoutSdkContextWithUseCase(`mounts <${displayName}>`);\n const { id, className } = props;\n return (\n <div\n id={id}\n className={className}\n />\n );\n };\n\n const Element = isServer ? ServerElement : ClientElement;\n Element.displayName = displayName;\n (Element as any).__elementType = type;\n\n return Element as FunctionComponent<ElementProps>;\n};\n\nconst isServer = typeof window === 'undefined';\nconst PaymentElement: FunctionComponent<\n PaymentElementProps & {\n fallback?: ReactNode;\n }\n> = createElementComponent('payment', isServer);\n\nexport { Elements, PaymentElement, useElements, useStripe };\n","import { useCallback, useMemo } from 'react';\n\nimport type { BillingInitializedPaymentMethodResource, ForPayerType } from '../../types';\nimport { useOrganizationBase } from '../hooks/base/useOrganizationBase';\nimport { useUserBase } from '../hooks/base/useUserBase';\nimport { useBillingIsEnabled } from '../hooks/useBillingIsEnabled';\nimport { useClearQueriesOnSignOut } from '../hooks/useClearQueriesOnSignOut';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQueryClient } from '../query/use-clerk-query-client';\nimport { useClerkQuery } from '../query/useQuery';\n\ntype InitializePaymentMethodOptions = {\n for?: ForPayerType;\n};\n\nexport type UseInitializePaymentMethodResult = {\n initializedPaymentMethod: BillingInitializedPaymentMethodResource | undefined;\n initializePaymentMethod: () => Promise<BillingInitializedPaymentMethodResource | undefined>;\n};\n\n/**\n * @internal\n */\nfunction useInitializePaymentMethod(options?: InitializePaymentMethodOptions): UseInitializePaymentMethodResult {\n const { for: forType } = options ?? {};\n const organization = useOrganizationBase();\n const user = useUserBase();\n\n const resource = forType === 'organization' ? organization : user;\n\n const billingEnabled = useBillingIsEnabled(options);\n\n const stableKey = 'billing-payment-method-initialize';\n const authenticated = true;\n\n const queryKey = useMemo(() => {\n return [stableKey, authenticated, { resourceId: resource?.id }, {}] as const;\n }, [resource?.id]);\n\n const isEnabled = Boolean(resource?.id) && billingEnabled;\n\n useClearQueriesOnSignOut({\n isSignedOut: user === null,\n authenticated,\n stableKeys: stableKey,\n });\n\n const query = useClerkQuery({\n queryKey,\n queryFn: async () => {\n if (!resource) {\n return undefined;\n }\n\n return resource.initializePaymentMethod({\n gateway: 'stripe',\n });\n },\n enabled: isEnabled,\n staleTime: 1_000 * 60,\n refetchOnWindowFocus: false,\n placeholderData: defineKeepPreviousDataFn(isEnabled),\n });\n\n const [queryClient] = useClerkQueryClient();\n\n const initializePaymentMethod = useCallback(async () => {\n if (!resource) {\n return undefined;\n }\n\n const result = await resource.initializePaymentMethod({\n gateway: 'stripe',\n });\n\n queryClient.setQueryData(queryKey, result);\n\n return result;\n }, [queryClient, queryKey, resource]);\n\n return {\n initializedPaymentMethod: query.data ?? undefined,\n initializePaymentMethod,\n };\n}\n\nexport { useInitializePaymentMethod as __internal_useInitializePaymentMethod };\n","import type { loadStripe } from '@stripe/stripe-js';\n\nimport { useClerk } from '../hooks/useClerk';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQuery } from '../query/useQuery';\n\ntype LoadStripeFn = typeof loadStripe;\n\ntype StripeClerkLibs = {\n loadStripe: LoadStripeFn;\n};\n\nexport type UseStripeClerkLibsResult = StripeClerkLibs | null;\n\n/**\n * @internal\n */\nfunction useStripeClerkLibs(): UseStripeClerkLibsResult {\n const clerk = useClerk();\n\n const query = useClerkQuery({\n queryKey: ['clerk-stripe-sdk'],\n queryFn: async () => {\n const loadStripe = (await clerk.__internal_loadStripeJs()) as LoadStripeFn;\n return { loadStripe };\n },\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n placeholderData: defineKeepPreviousDataFn(true),\n });\n\n return query.data ?? null;\n}\n\nexport { useStripeClerkLibs as __internal_useStripeClerkLibs };\n","import type { Stripe } from '@stripe/stripe-js';\nimport { useMemo } from 'react';\n\nimport { useBillingIsEnabled } from '../hooks/useBillingIsEnabled';\nimport { defineKeepPreviousDataFn } from '../query/keep-previous-data';\nimport { useClerkQuery } from '../query/useQuery';\nimport type { UseStripeClerkLibsResult } from './useStripeClerkLibs';\n\ntype StripeLoaderOptions = {\n stripeClerkLibs: UseStripeClerkLibsResult;\n externalGatewayId?: string;\n stripePublishableKey?: string;\n};\n\nexport type UseStripeLoaderResult = Stripe | null | undefined;\n\n/**\n * @internal\n */\nfunction useStripeLoader(options: StripeLoaderOptions): UseStripeLoaderResult {\n const { stripeClerkLibs, externalGatewayId, stripePublishableKey } = options;\n\n const queryKey = useMemo(() => {\n return ['stripe-sdk', { externalGatewayId, stripePublishableKey }] as const;\n }, [externalGatewayId, stripePublishableKey]);\n\n const billingEnabled = useBillingIsEnabled({ authenticated: true });\n\n const isEnabled = Boolean(stripeClerkLibs && externalGatewayId && stripePublishableKey) && billingEnabled;\n\n const query = useClerkQuery({\n queryKey,\n queryFn: () => {\n if (!stripeClerkLibs || !externalGatewayId || !stripePublishableKey) {\n return null;\n }\n\n return stripeClerkLibs.loadStripe(stripePublishableKey, {\n stripeAccount: externalGatewayId,\n });\n },\n enabled: isEnabled,\n staleTime: 1_000 * 60,\n refetchOnWindowFocus: false,\n placeholderData: defineKeepPreviousDataFn(true),\n });\n\n return query.data;\n}\n\nexport { useStripeLoader as __internal_useStripeLoader };\n","import type { Stripe, StripeElements, StripeElementsOptions } from '@stripe/stripe-js';\nimport React, { type PropsWithChildren, type ReactNode, useCallback, useMemo, useState } from 'react';\n\nimport type { BillingCheckoutResource, CheckoutFlowResource, EnvironmentResource, ForPayerType } from '../../types';\nimport { createContextAndHook } from '../hooks/createContextAndHook';\nimport type { useCheckout } from '../hooks/useCheckout';\nimport { useClerk } from '../hooks/useClerk';\nimport { Elements, PaymentElement as StripePaymentElement, useElements, useStripe } from '../stripe-react';\nimport {\n __internal_useInitializePaymentMethod as useInitializePaymentMethod,\n type UseInitializePaymentMethodResult,\n} from './useInitializePaymentMethod';\nimport { __internal_useStripeClerkLibs as useStripeClerkLibs } from './useStripeClerkLibs';\nimport { __internal_useStripeLoader as useStripeLoader, type UseStripeLoaderResult } from './useStripeLoader';\n\ntype PaymentElementError = {\n gateway: 'stripe';\n error: {\n /**\n * For some errors that could be handled programmatically, a short string indicating the [error code](https://stripe.com/docs/error-codes) reported.\n */\n code?: string;\n message?: string;\n type: string;\n };\n};\n\nconst useInternalEnvironment = () => {\n const clerk = useClerk();\n // @ts-expect-error `__internal_environment` is not typed\n return clerk.__internal_environment as unknown as EnvironmentResource | null | undefined;\n};\n\nconst useLocalization = () => {\n const clerk = useClerk();\n\n let locale = 'en';\n try {\n const localization = clerk.__internal_getOption('localization');\n locale = localization?.locale || 'en';\n } catch {\n // ignore errors\n }\n\n // Normalize locale to 2-letter language code for Stripe compatibility\n const normalizedLocale = locale.split('-')[0];\n\n return normalizedLocale;\n};\n\nconst usePaymentSourceUtils = (forResource: ForPayerType = 'user') => {\n const stripeClerkLibs = useStripeClerkLibs();\n const environment = useInternalEnvironment();\n\n const { initializedPaymentMethod, initializePaymentMethod }: UseInitializePaymentMethodResult =\n useInitializePaymentMethod({ for: forResource });\n\n const stripePublishableKey = environment?.commerceSettings.billing.stripePublishableKey ?? undefined;\n\n const stripe: UseStripeLoaderResult = useStripeLoader({\n stripeClerkLibs,\n externalGatewayId: initializedPaymentMethod?.externalGatewayId,\n stripePublishableKey,\n });\n\n const externalClientSecret = initializedPaymentMethod?.externalClientSecret;\n const paymentMethodOrder = initializedPaymentMethod?.paymentMethodOrder;\n\n return {\n stripe,\n initializePaymentMethod,\n externalClientSecret,\n paymentMethodOrder,\n };\n};\n\ntype internalStripeAppearance = {\n colorPrimary: string;\n colorBackground: string;\n colorText: string;\n colorTextSecondary: string;\n colorSuccess: string;\n colorDanger: string;\n colorWarning: string;\n fontWeightNormal: string;\n fontWeightMedium: string;\n fontWeightBold: string;\n fontSizeXl: string;\n fontSizeLg: string;\n fontSizeSm: string;\n fontSizeXs: string;\n borderRadius: string;\n spacingUnit: string;\n};\n\n/**\n * @interface\n */\nexport type PaymentElementProviderProps = {\n /**\n * A checkout resource object. When provided, the payment element is scoped to the specific checkout session.\n */\n checkout?: CheckoutFlowResource | BillingCheckoutResource | ReturnType<typeof useCheckout>['checkout'];\n /**\n * An object to customize the appearance of the Stripe Payment Element. This allows you to match the form's styling to your application's theme.\n */\n stripeAppearance?: internalStripeAppearance;\n /**\n * Specifies whether to fetch for the current user or Organization.\n *\n * @default 'user'\n */\n for?: ForPayerType;\n /**\n * A description to display to the user within the payment element UI.\n */\n paymentDescription?: string;\n};\n\nconst [PaymentElementContext, usePaymentElementContext] = createContextAndHook<\n ReturnType<typeof usePaymentSourceUtils> &\n PaymentElementProviderProps & {\n setIsPaymentElementReady: (isPaymentElementReady: boolean) => void;\n isPaymentElementReady: boolean;\n }\n>('PaymentElementContext');\n\nconst [StripeUtilsContext, useStripeUtilsContext] = createContextAndHook<{\n stripe: Stripe | undefined | null;\n elements: StripeElements | undefined | null;\n}>('StripeUtilsContext');\n\nconst ValidateStripeUtils = ({ children }: PropsWithChildren) => {\n const stripe = useStripe();\n const elements = useElements();\n\n return <StripeUtilsContext.Provider value={{ value: { stripe, elements } }}>{children}</StripeUtilsContext.Provider>;\n};\n\nconst DummyStripeUtils = ({ children }: PropsWithChildren) => {\n return <StripeUtilsContext.Provider value={{ value: {} as any }}>{children}</StripeUtilsContext.Provider>;\n};\n\nconst PropsProvider = ({ children, ...props }: PropsWithChildren<PaymentElementProviderProps>) => {\n const utils = usePaymentSourceUtils(props.for);\n const [isPaymentElementReady, setIsPaymentElementReady] = useState(false);\n return (\n <PaymentElementContext.Provider\n value={{\n value: {\n ...props,\n ...utils,\n setIsPaymentElementReady,\n isPaymentElementReady,\n },\n }}\n >\n {children}\n </PaymentElementContext.Provider>\n );\n};\n\nconst PaymentElementProvider = ({ children, ...props }: PropsWithChildren<PaymentElementProviderProps>) => {\n return (\n <PropsProvider {...props}>\n <PaymentElementInternalRoot>{children}</PaymentElementInternalRoot>\n </PropsProvider>\n );\n};\n\nconst PaymentElementInternalRoot = (props: PropsWithChildren) => {\n const { stripe, externalClientSecret, stripeAppearance } = usePaymentElementContext();\n const locale = useLocalization();\n\n if (stripe && externalClientSecret) {\n return (\n <Elements\n // This key is used to reset the payment intent, since Stripe doesn't provide a way to reset the payment intent.\n key={externalClientSecret}\n stripe={stripe}\n options={{\n loader: 'never',\n clientSecret: externalClientSecret,\n appearance: {\n variables: stripeAppearance,\n },\n locale: locale as StripeElementsOptions['locale'],\n }}\n >\n <ValidateStripeUtils>{props.children}</ValidateStripeUtils>\n </Elements>\n );\n }\n\n return <DummyStripeUtils>{props.children}</DummyStripeUtils>;\n};\n\n/**\n * @interface\n */\nexport type PaymentElementProps = {\n /**\n * Optional fallback content, such as a loading skeleton, to display while the payment form is being initialized.\n */\n fallback?: ReactNode;\n};\n\nconst PaymentElement = ({ fallback }: PaymentElementProps) => {\n const {\n setIsPaymentElementReady,\n paymentMethodOrder,\n checkout,\n stripe,\n externalClientSecret,\n paymentDescription,\n for: _for,\n } = usePaymentElementContext();\n const environment = useInternalEnvironment();\n\n const applePay = useMemo(() => {\n if (!checkout || !checkout.totals || !checkout.plan) {\n return undefined;\n }\n\n return {\n recurringPaymentRequest: {\n paymentDescription: paymentDescription || '',\n managementURL:\n _for === 'organization'\n ? environment?.displayConfig.organizationProfileUrl || ''\n : environment?.displayConfig.userProfileUrl || '',\n regularBilling: {\n amount: checkout.totals.totalDueNow?.amount || checkout.totals.grandTotal.amount,\n label: checkout.plan.name,\n recurringPaymentIntervalUnit: checkout.planPeriod === 'annual' ? 'year' : 'month',\n },\n },\n } as const;\n }, [checkout, paymentDescription, _for, environment]);\n\n const options = useMemo(() => {\n return {\n layout: {\n type: 'tabs',\n defaultCollapsed: false,\n },\n paymentMethodOrder,\n applePay,\n } as const;\n }, [applePay, paymentMethodOrder]);\n\n const onReady = useCallback(() => {\n setIsPaymentElementReady(true);\n }, [setIsPaymentElementReady]);\n\n if (!stripe || !externalClientSecret) {\n return <>{fallback}</>;\n }\n\n return (\n <StripePaymentElement\n fallback={fallback}\n onReady={onReady}\n options={options}\n />\n );\n};\n\nconst throwLibsMissingError = () => {\n throw new Error(\n 'Clerk: Unable to submit, Stripe libraries are not yet loaded. Be sure to check `isFormReady` before calling `submit`.',\n );\n};\n\n/**\n * @interface\n */\nexport type UsePaymentElementReturn = {\n /**\n * A function that submits the payment form data to the payment provider. It returns a promise that resolves with either a `data` object containing a payment token on success, or an `error` object on failure.\n */\n submit: () => Promise<\n | {\n data: { gateway: 'stripe'; paymentToken: string };\n error: null;\n }\n | {\n data: null;\n error: PaymentElementError;\n }\n >;\n /**\n * A function that resets the payment form to its initial, empty state.\n */\n reset: () => Promise<void>;\n /**\n * Indicates whether the payment form UI has been rendered and is ready for user input. This is useful for disabling a submit button until the form is interactive.\n */\n isFormReady: boolean;\n} & (\n | {\n /**\n * An object containing information about the initialized payment provider. It is `undefined` until `isProviderReady` is `true`.\n */\n provider: {\n /** The name of the payment provider. */\n name: 'stripe';\n };\n /**\n * Indicates whether the underlying payment provider (e.g., Stripe) has been fully initialized.\n */\n isProviderReady: true;\n }\n | {\n provider: undefined;\n isProviderReady: false;\n }\n);\n\nconst usePaymentElement = (): UsePaymentElementReturn => {\n const { isPaymentElementReady, initializePaymentMethod } = usePaymentElementContext();\n const { stripe, elements } = useStripeUtilsContext();\n const { externalClientSecret } = usePaymentElementContext();\n\n const submit = useCallback(async () => {\n if (!stripe || !elements) {\n return throwLibsMissingError();\n }\n\n const { setupIntent, error } = await stripe.confirmSetup({\n elements,\n confirmParams: {\n return_url: window.location.href,\n },\n redirect: 'if_required',\n });\n if (error) {\n return {\n data: null,\n error: {\n gateway: 'stripe',\n error: {\n code: error.code,\n message: error.message,\n type: error.type,\n },\n },\n } as const;\n }\n return {\n data: { gateway: 'stripe', paymentToken: setupIntent.payment_method as string },\n error: null,\n } as const;\n }, [stripe, elements]);\n\n const reset = useCallback(async () => {\n if (!stripe || !elements) {\n return throwLibsMissingError();\n }\n\n await initializePaymentMethod();\n }, [stripe, elements, initializePaymentMethod]);\n\n const isProviderReady = Boolean(stripe && externalClientSecret);\n\n if (!isProviderReady) {\n return {\n submit: throwLibsMissingError,\n reset: throwLibsMissingError,\n isFormReady: false,\n provider: undefined,\n isProviderReady: false,\n };\n }\n return {\n submit,\n reset,\n isFormReady: isPaymentElementReady,\n provider: {\n name: 'stripe',\n },\n isProviderReady: isProviderReady,\n };\n};\n\nexport {\n PaymentElement as __experimental_PaymentElement,\n PaymentElementProvider as __experimental_PaymentElementProvider,\n usePaymentElement as __experimental_usePaymentElement,\n};\n","'use client';\n\nimport React from 'react';\n\nimport { createContextAndHook } from './hooks/createContextAndHook';\n\ntype PortalProviderProps = React.PropsWithChildren<{\n /**\n * Function that returns the container element where portals should be rendered.\n * This allows Clerk components to render inside external dialogs/popovers\n * (e.g., Radix Dialog, React Aria Components) instead of document.body.\n */\n getContainer: () => HTMLElement | null;\n}>;\n\nconst [PortalContext, , usePortalContextWithoutGuarantee] = createContextAndHook<{\n getContainer: () => HTMLElement | null;\n}>('PortalProvider');\n\n/**\n * UNSAFE_PortalProvider allows you to specify a custom container for Clerk floating UI elements\n * (popovers, modals, tooltips, etc.) that use portals.\n *\n * Only components within this provider will be affected. Components outside the provider\n * will continue to use the default document.body for portals.\n *\n * This is particularly useful when using Clerk components inside external UI libraries\n * like Radix Dialog or React Aria Components, where portaled elements need to render\n * within the dialog's container to remain interactable.\n *\n * @example\n * ```tsx\n * function Example() {\n * const containerRef = useRef(null);\n * return (\n * <RadixDialog ref={containerRef}>\n * <UNSAFE_PortalProvider getContainer={() => containerRef.current}>\n * <UserButton />\n * </UNSAFE_PortalProvider>\n * </RadixDialog>\n * );\n * }\n * ```\n */\nexport const UNSAFE_PortalProvider = ({ children, getContainer }: PortalProviderProps) => {\n const contextValue = React.useMemo(() => ({ value: { getContainer } }), [getContainer]);\n\n return <PortalContext.Provider value={contextValue}>{children}</PortalContext.Provider>;\n};\n\nUNSAFE_PortalProvider.displayName = 'UNSAFE_PortalProvider';\n\n/**\n * Hook to get the current portal root container.\n * Returns the getContainer function from context if inside a PortalProvider,\n * otherwise returns a function that returns null (default behavior).\n */\nexport const usePortalRoot = (): (() => HTMLElement | null) => {\n const contextValue = usePortalContextWithoutGuarantee();\n\n if (contextValue && 'getContainer' in contextValue && contextValue.getContainer) {\n return contextValue.getContainer;\n }\n\n // Return a function that returns null when not inside a PortalProvider\n return () => null;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAQA,SAAgB,oBAAoB,YAAqB,UAA2D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