@clerk/shared 3.22.1 → 3.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/react/index.ts","../../src/react/hooks/createContextAndHook.ts","../../src/organization.ts","../../src/telemetry/events/method-called.ts","../../src/react/contexts.tsx","../../src/react/clerk-swr.ts","../../src/react/hooks/usePagesOrInfinite.ts","../../src/react/hooks/useOrganization.tsx","../../src/react/hooks/useOrganizationList.tsx","../../src/react/hooks/useSafeLayoutEffect.tsx","../../src/react/hooks/useSession.ts","../../src/react/hooks/useSessionList.ts","../../src/react/hooks/useUser.ts","../../src/react/hooks/useClerk.ts","../../src/react/hooks/useDeepEqualMemo.ts","../../src/react/hooks/useReverification.ts","../../src/authorization.ts","../../src/authorization-errors.ts","../../src/error.ts","../../src/underscore.ts","../../src/utils/noop.ts","../../src/utils/createDeferredPromise.ts","../../src/react/hooks/createCommerceHook.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.tsx","../../src/react/hooks/useCheckout.ts","../../src/react/commerce.tsx","../../src/react/stripe-react/index.tsx","../../src/react/stripe-react/utils.ts"],"sourcesContent":["export * from './hooks';\n\nexport {\n ClerkInstanceContext,\n ClientContext,\n OptionsContext,\n OrganizationProvider,\n SessionContext,\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useClientContext,\n useOptionsContext,\n useOrganizationContext,\n UserContext,\n useSessionContext,\n useUserContext,\n __experimental_CheckoutProvider,\n} from './contexts';\n\nexport * from './commerce';\n","'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","import type { OrganizationMembershipResource } from '@clerk/types';\n\n/**\n * Finds the organization membership for a given organization ID from a list of memberships\n * @param organizationMemberships - Array of organization memberships to search through\n * @param organizationId - ID of the organization to find the membership for\n * @returns The matching organization membership or undefined if not found\n */\nexport function getCurrentOrganizationMembership(\n organizationMemberships: OrganizationMembershipResource[],\n organizationId: string,\n) {\n return organizationMemberships.find(\n organizationMembership => organizationMembership.organization.id === organizationId,\n );\n}\n","import type { TelemetryEventRaw } from '@clerk/types';\n\nconst EVENT_METHOD_CALLED = 'METHOD_CALLED';\nconst EVENT_SAMPLING_RATE = 0.1;\n\ntype EventMethodCalled = {\n method: string;\n} & Record<string, string | number | boolean>;\n\n/**\n * Fired when a helper method is called from a Clerk SDK.\n */\nexport function eventMethodCalled(\n method: string,\n payload?: Record<string, unknown>,\n): TelemetryEventRaw<EventMethodCalled> {\n return {\n event: EVENT_METHOD_CALLED,\n eventSamplingRate: EVENT_SAMPLING_RATE,\n payload: {\n method,\n ...payload,\n },\n };\n}\n","'use client';\n\nimport type {\n ClerkOptions,\n ClientResource,\n CommerceSubscriptionPlanPeriod,\n ForPayerType,\n LoadedClerk,\n OrganizationResource,\n SignedInSessionResource,\n UserResource,\n} from '@clerk/types';\nimport type { PropsWithChildren } from 'react';\nimport React from 'react';\n\nimport { SWRConfig } from './clerk-swr';\nimport { createContextAndHook } from './hooks/createContextAndHook';\n\nconst [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook<LoadedClerk>('ClerkInstanceContext');\nconst [UserContext, useUserContext] = createContextAndHook<UserResource | null | undefined>('UserContext');\nconst [ClientContext, useClientContext] = createContextAndHook<ClientResource | null | undefined>('ClientContext');\nconst [SessionContext, useSessionContext] = createContextAndHook<SignedInSessionResource | null | undefined>(\n 'SessionContext',\n);\n\nconst OptionsContext = React.createContext<ClerkOptions>({});\n\ntype UseCheckoutOptions = {\n for?: ForPayerType;\n planPeriod: CommerceSubscriptionPlanPeriod;\n planId: 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\ntype OrganizationContextProps = {\n organization: OrganizationResource | null | undefined;\n};\nconst [OrganizationContextInternal, useOrganizationContext] = createContextAndHook<{\n organization: OrganizationResource | null | undefined;\n}>('OrganizationContext');\n\nconst OrganizationProvider = ({\n children,\n organization,\n swrConfig,\n}: PropsWithChildren<\n OrganizationContextProps & {\n // Exporting inferred types directly from SWR will result in error while building declarations\n swrConfig?: any;\n }\n>) => {\n return (\n <SWRConfig value={swrConfig}>\n <OrganizationContextInternal.Provider\n value={{\n value: { organization },\n }}\n >\n {children}\n </OrganizationContextInternal.Provider>\n </SWRConfig>\n );\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 ClientContext,\n useClientContext,\n OrganizationProvider,\n useOrganizationContext,\n UserContext,\n OptionsContext,\n useOptionsContext,\n useUserContext,\n SessionContext,\n useSessionContext,\n ClerkInstanceContext,\n useClerkInstanceContext,\n useCheckoutContext,\n __experimental_CheckoutProvider,\n useAssertWrappedByClerkProvider,\n};\n","'use client';\n\nexport * from 'swr';\n\nexport { default as useSWR } from 'swr';\nexport { default as useSWRInfinite } from 'swr/infinite';\n","'use client';\n\nimport { useCallback, useMemo, useRef, useState } from 'react';\n\nimport { useSWR, useSWRInfinite } from '../clerk-swr';\nimport type {\n CacheSetter,\n PagesOrInfiniteConfig,\n PagesOrInfiniteOptions,\n PaginatedResources,\n ValueOrSetter,\n} from '../types';\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 */\nfunction getDifferentKeys(obj1: Record<string, unknown>, obj2: Record<string, unknown>): 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 * 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\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\nconst cachingSWROptions = {\n dedupingInterval: 1000 * 60,\n focusThrottleInterval: 1000 * 60 * 2,\n} satisfies Parameters<typeof useSWR>[2];\n\ntype ArrayType<DataArray> = DataArray extends Array<infer ElementType> ? ElementType : never;\ntype ExtractData<Type> = Type extends { data: infer Data } ? ArrayType<Data> : Type;\n\ntype UsePagesOrInfinite = <\n Params extends PagesOrInfiniteOptions,\n FetcherReturnData extends Record<string, any>,\n CacheKeys extends Record<string, unknown> = Record<string, unknown>,\n TConfig extends PagesOrInfiniteConfig = PagesOrInfiniteConfig,\n>(\n /**\n * The parameters will be passed to the fetcher.\n */\n params: Params,\n /**\n * A Promise returning function to fetch your data.\n */\n fetcher: ((p: Params) => FetcherReturnData | Promise<FetcherReturnData>) | undefined,\n /**\n * Internal configuration of the hook.\n */\n config: TConfig,\n cacheKeys: CacheKeys,\n) => PaginatedResources<ExtractData<FetcherReturnData>, TConfig['infinite']>;\n\n/**\n * A flexible pagination hook that supports both traditional pagination and infinite loading.\n * It provides a unified API for handling paginated data fetching, with built-in caching through SWR.\n * The hook can operate in two modes:\n * - Traditional pagination: Fetches one page at a time with page navigation\n * - Infinite loading: Accumulates data as more pages are loaded.\n *\n * Features:\n * - Cache management with SWR\n * - Loading and error states\n * - Page navigation helpers\n * - Data revalidation and updates\n * - Support for keeping previous data while loading.\n *\n * @internal\n */\nexport const usePagesOrInfinite: UsePagesOrInfinite = (params, fetcher, config, cacheKeys) => {\n const [paginatedPage, setPaginatedPage] = useState(params.initialPage ?? 1);\n\n // Cache initialPage and initialPageSize until unmount\n const initialPageRef = useRef(params.initialPage ?? 1);\n const pageSizeRef = useRef(params.pageSize ?? 10);\n\n const enabled = config.enabled ?? true;\n const cacheMode = config.__experimental_mode === 'cache';\n const triggerInfinite = config.infinite ?? false;\n const keepPreviousData = config.keepPreviousData ?? false;\n\n const pagesCacheKey = {\n ...cacheKeys,\n ...params,\n initialPage: paginatedPage,\n pageSize: pageSizeRef.current,\n };\n\n // cacheMode being `true` indicates that the cache key is defined, but the fetcher is not.\n // This allows to ready the cache instead of firing a request.\n const shouldFetch = !triggerInfinite && enabled && (!cacheMode ? !!fetcher : true);\n const swrKey = shouldFetch ? pagesCacheKey : null;\n const swrFetcher =\n !cacheMode && !!fetcher\n ? (cacheKeyParams: Record<string, unknown>) => {\n const requestParams = getDifferentKeys(cacheKeyParams, cacheKeys);\n return fetcher({ ...params, ...requestParams });\n }\n : null;\n\n const {\n data: swrData,\n isValidating: swrIsValidating,\n isLoading: swrIsLoading,\n error: swrError,\n mutate: swrMutate,\n } = useSWR(swrKey, swrFetcher, { keepPreviousData, ...cachingSWROptions });\n\n const {\n data: swrInfiniteData,\n isLoading: swrInfiniteIsLoading,\n isValidating: swrInfiniteIsValidating,\n error: swrInfiniteError,\n size,\n setSize,\n mutate: swrInfiniteMutate,\n } = useSWRInfinite(\n pageIndex => {\n if (!triggerInfinite || !enabled) {\n return null;\n }\n\n return {\n ...params,\n ...cacheKeys,\n initialPage: initialPageRef.current + pageIndex,\n pageSize: pageSizeRef.current,\n };\n },\n cacheKeyParams => {\n // @ts-ignore\n const requestParams = getDifferentKeys(cacheKeyParams, cacheKeys);\n // @ts-ignore\n return fetcher?.(requestParams);\n },\n cachingSWROptions,\n );\n\n const page = useMemo(() => {\n if (triggerInfinite) {\n return size;\n }\n return paginatedPage;\n }, [triggerInfinite, size, paginatedPage]);\n\n const fetchPage: ValueOrSetter<number> = useCallback(\n numberOrgFn => {\n if (triggerInfinite) {\n void setSize(numberOrgFn);\n return;\n }\n return setPaginatedPage(numberOrgFn);\n },\n [setSize],\n );\n\n const data = useMemo(() => {\n if (triggerInfinite) {\n return swrInfiniteData?.map(a => a?.data).flat() ?? [];\n }\n return swrData?.data ?? [];\n }, [triggerInfinite, swrData, swrInfiniteData]);\n\n const count = useMemo(() => {\n if (triggerInfinite) {\n return swrInfiniteData?.[swrInfiniteData?.length - 1]?.total_count || 0;\n }\n return swrData?.total_count ?? 0;\n }, [triggerInfinite, swrData, swrInfiniteData]);\n\n const isLoading = triggerInfinite ? swrInfiniteIsLoading : swrIsLoading;\n const isFetching = triggerInfinite ? swrInfiniteIsValidating : swrIsValidating;\n const error = (triggerInfinite ? swrInfiniteError : swrError) ?? null;\n const isError = !!error;\n /**\n * Helpers.\n */\n const fetchNext = useCallback(() => {\n fetchPage(n => Math.max(0, n + 1));\n }, [fetchPage]);\n\n const fetchPrevious = useCallback(() => {\n fetchPage(n => Math.max(0, n - 1));\n }, [fetchPage]);\n\n const offsetCount = (initialPageRef.current - 1) * pageSizeRef.current;\n\n const pageCount = Math.ceil((count - offsetCount) / pageSizeRef.current);\n const hasNextPage = count - offsetCount * pageSizeRef.current > page * pageSizeRef.current;\n const hasPreviousPage = (page - 1) * pageSizeRef.current > offsetCount * pageSizeRef.current;\n\n const setData: CacheSetter = triggerInfinite\n ? value =>\n swrInfiniteMutate(value, {\n revalidate: false,\n })\n : value =>\n swrMutate(value, {\n revalidate: false,\n });\n\n const revalidate = triggerInfinite ? () => swrInfiniteMutate() : () => swrMutate();\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 // Let the hook return type define this type\n revalidate: revalidate as any,\n // Let the hook return type define this type\n setData: setData as any,\n };\n};\n","/* eslint-disable jsdoc/require-description-complete-sentence */\nimport type {\n ClerkPaginatedResponse,\n CommerceSubscriptionItemResource,\n GetDomainsParams,\n GetInvitationsParams,\n GetMembershipRequestParams,\n GetMembersParams,\n GetSubscriptionsParams,\n OrganizationDomainResource,\n OrganizationInvitationResource,\n OrganizationMembershipRequestResource,\n OrganizationMembershipResource,\n OrganizationResource,\n} from '@clerk/types';\n\nimport { getCurrentOrganizationMembership } from '../../organization';\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useSessionContext,\n} from '../contexts';\nimport type { PaginatedHookConfig, PaginatedResources, PaginatedResourcesWithDefault } from '../types';\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/organizations/verified-domains#enrollment-mode).</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/references/javascript/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 * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change.\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>`orgId`: A string that filters the subscriptions by the provided organization ID.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n subscriptions?: true | PaginatedHookConfig<GetSubscriptionsParams>;\n};\n\n/**\n * @interface\n */\nexport type UseOrganizationReturn<T extends UseOrganizationParams> =\n | {\n /**\n * A boolean that indicates whether Clerk has completed initialization. Initially `false`, becomes `true` once Clerk loads.\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 * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change.\n * Includes a paginated list of the organization's subscriptions.\n */\n subscriptions: PaginatedResourcesWithDefault<CommerceSubscriptionItemResource>;\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 subscriptions: PaginatedResourcesWithDefault<CommerceSubscriptionItemResource>;\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 subscriptions: PaginatedResources<\n CommerceSubscriptionItemResource,\n T['subscriptions'] 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/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/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 subscriptions: subscriptionsListParams,\n } = params || {};\n\n useAssertWrappedByClerkProvider('useOrganization');\n\n const { organization } = useOrganizationContext();\n const session = useSessionContext();\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 subscriptionsSafeValues = useWithSafeValues(subscriptionsListParams, {\n initialPage: 1,\n pageSize: 10,\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 subscriptionsParams =\n typeof subscriptionsListParams === 'undefined'\n ? undefined\n : {\n initialPage: subscriptionsSafeValues.initialPage,\n pageSize: subscriptionsSafeValues.pageSize,\n orgId: organization?.id,\n };\n\n const domains = usePagesOrInfinite<GetDomainsParams, ClerkPaginatedResponse<OrganizationDomainResource>>(\n {\n ...domainParams,\n },\n organization?.getDomains,\n {\n keepPreviousData: domainSafeValues.keepPreviousData,\n infinite: domainSafeValues.infinite,\n enabled: !!domainParams,\n },\n {\n type: 'domains',\n organizationId: organization?.id,\n },\n );\n\n const membershipRequests = usePagesOrInfinite<\n GetMembershipRequestParams,\n ClerkPaginatedResponse<OrganizationMembershipRequestResource>\n >(\n {\n ...membershipRequestParams,\n },\n organization?.getMembershipRequests,\n {\n keepPreviousData: membershipRequestSafeValues.keepPreviousData,\n infinite: membershipRequestSafeValues.infinite,\n enabled: !!membershipRequestParams,\n },\n {\n type: 'membershipRequests',\n organizationId: organization?.id,\n },\n );\n\n const memberships = usePagesOrInfinite<GetMembersParams, ClerkPaginatedResponse<OrganizationMembershipResource>>(\n membersParams || {},\n organization?.getMemberships,\n {\n keepPreviousData: membersSafeValues.keepPreviousData,\n infinite: membersSafeValues.infinite,\n enabled: !!membersParams,\n },\n {\n type: 'members',\n organizationId: organization?.id,\n },\n );\n\n const invitations = usePagesOrInfinite<GetInvitationsParams, ClerkPaginatedResponse<OrganizationInvitationResource>>(\n {\n ...invitationsParams,\n },\n organization?.getInvitations,\n {\n keepPreviousData: invitationsSafeValues.keepPreviousData,\n infinite: invitationsSafeValues.infinite,\n enabled: !!invitationsParams,\n },\n {\n type: 'invitations',\n organizationId: organization?.id,\n },\n );\n\n const subscriptions = usePagesOrInfinite<\n GetSubscriptionsParams,\n ClerkPaginatedResponse<CommerceSubscriptionItemResource>\n >(\n {\n ...subscriptionsParams,\n },\n organization?.getSubscriptions,\n {\n keepPreviousData: subscriptionsSafeValues.keepPreviousData,\n infinite: subscriptionsSafeValues.infinite,\n enabled: !!subscriptionsParams,\n },\n {\n type: 'subscriptions',\n organizationId: organization?.id,\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 subscriptions: 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 subscriptions: 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 subscriptions: 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 subscriptions,\n };\n}\n","/* eslint-disable jsdoc/require-description-complete-sentence */\nimport type {\n ClerkPaginatedResponse,\n CreateOrganizationParams,\n GetUserOrganizationInvitationsParams,\n GetUserOrganizationMembershipParams,\n GetUserOrganizationSuggestionsParams,\n OrganizationMembershipResource,\n OrganizationResource,\n OrganizationSuggestionResource,\n SetActive,\n UserOrganizationInvitationResource,\n} from '@clerk/types';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useUserContext } from '../contexts';\nimport type { PaginatedHookConfig, PaginatedResources, PaginatedResourcesWithDefault } from '../types';\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 * A boolean that indicates whether Clerk has completed initialization and there is an authenticated user. Initially `false`, becomes `true` once Clerk loads with a user.\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/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/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\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 = useUserContext();\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 GetUserOrganizationMembershipParams,\n ClerkPaginatedResponse<OrganizationMembershipResource>\n >(\n userMembershipsParams || {},\n user?.getOrganizationMemberships,\n {\n keepPreviousData: userMembershipsSafeValues.keepPreviousData,\n infinite: userMembershipsSafeValues.infinite,\n enabled: !!userMembershipsParams,\n },\n {\n type: 'userMemberships',\n userId: user?.id,\n },\n );\n\n const invitations = usePagesOrInfinite<\n GetUserOrganizationInvitationsParams,\n ClerkPaginatedResponse<UserOrganizationInvitationResource>\n >(\n {\n ...userInvitationsParams,\n },\n user?.getOrganizationInvitations,\n {\n keepPreviousData: userInvitationsSafeValues.keepPreviousData,\n infinite: userInvitationsSafeValues.infinite,\n enabled: !!userInvitationsParams,\n },\n {\n type: 'userInvitations',\n userId: user?.id,\n },\n );\n\n const suggestions = usePagesOrInfinite<\n GetUserOrganizationSuggestionsParams,\n ClerkPaginatedResponse<OrganizationSuggestionResource>\n >(\n {\n ...userSuggestionsParams,\n },\n user?.getOrganizationSuggestions,\n {\n keepPreviousData: userSuggestionsSafeValues.keepPreviousData,\n infinite: userSuggestionsSafeValues.infinite,\n enabled: !!userSuggestionsParams,\n },\n {\n type: 'userSuggestions',\n userId: user?.id,\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 type { UseSessionReturn } from '@clerk/types';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useSessionContext } from '../contexts';\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/references/javascript/session) object, as well as helpers for setting the active session.\n *\n * @unionReturnHeadings\n * [\"Initialization\", \"Signed out\", \"Signed in\"]\n *\n * @function\n *\n * @param [options] - An object containing options for the `useSession()` hook.\n *\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/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 * {@include ../../../docs/use-session.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useSession: UseSession = () => {\n useAssertWrappedByClerkProvider(hookName);\n\n const session = useSessionContext();\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 type { UseSessionListReturn } from '@clerk/types';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useClientContext } from '../contexts';\n\nconst hookName = 'useSessionList';\n/**\n * The `useSessionList()` hook returns an array of [`Session`](https://clerk.com/docs/references/javascript/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/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 * {@include ../../../docs/use-session-list.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useSessionList = (): UseSessionListReturn => {\n useAssertWrappedByClerkProvider(hookName);\n\n const isomorphicClerk = useClerkInstanceContext();\n const client = useClientContext();\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 type { UseUserReturn } from '@clerk/types';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useUserContext } from '../contexts';\n\nconst hookName = 'useUser';\n/**\n * The `useUser()` hook provides access to the current user's [`User`](https://clerk.com/docs/references/javascript/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 and initialized.\n *\n * @unionReturnHeadings\n * [\"Initialization\", \"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/references/javascript/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 * 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/references/javascript/user) object, which calls the [`update()`](https://clerk.com/docs/references/javascript/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/clerk-react'\n *\n * export default function Home() {\n * const { isLoaded, user } = useUser()\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null\n * }\n *\n * if (!user) 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 * {@include ../../../docs/use-user.md#nextjs-01}\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/references/javascript/user) object, which calls the [`reload()`](https://clerk.com/docs/references/javascript/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/clerk-react'\n *\n * export default function Home() {\n * const { isLoaded, user } = useUser()\n *\n * if (!isLoaded) {\n * // Handle loading state\n * return null\n * }\n *\n * if (!user) return null\n *\n * const updateUser = async () => {\n * // Update data via an API endpoint\n * const updateMetadata = await fetch('/api/updateMetadata')\n *\n * // Check if the update was successful\n * if (updateMetadata.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 * {@include ../../../docs/use-user.md#nextjs-02}\n *\n * </Tab>\n * </Tabs>\n */\nexport function useUser(): UseUserReturn {\n useAssertWrappedByClerkProvider(hookName);\n\n const user = useUserContext();\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 type { LoadedClerk } from '@clerk/types';\n\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/references/javascript/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/references/javascript/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/references/javascript/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/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 * {@include ../../../docs/use-clerk.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useClerk = (): LoadedClerk => {\n useAssertWrappedByClerkProvider('useClerk');\n return useClerkInstanceContext();\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 type { Clerk, SessionVerificationLevel } from '@clerk/types';\nimport { 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 { createDeferredPromise } from '../../utils/createDeferredPromise';\nimport { useClerk } from './useClerk';\nimport { useSafeLayoutEffect } from './useSafeLayoutEffect';\n\nconst CLERK_API_REVERIFICATION_ERROR_CODE = 'session_reverification_required';\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 */\ntype NeedsReverificationParameters = {\n cancel: () => void;\n complete: () => void;\n level: SessionVerificationLevel | undefined;\n};\n\n/**\n * The optional options object.\n * @interface\n */\ntype UseReverificationOptions = {\n /**\n * A handler that is called when reverification is needed, this will opt-out of using the default UI when provided.\n *\n * @param cancel - A function that will cancel the reverification process.\n * @param complete - A function that will retry the original request after reverification.\n * @param level - The level returned with the reverification hint.\n *\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 fetcher: Fetcher,\n options?: Options,\n) => UseReverificationResult<Fetcher>;\n\ntype CreateReverificationHandlerParams = UseReverificationOptions & {\n openUIComponent: Clerk['__internal_openReverification'];\n telemetry: Clerk['telemetry'];\n};\n\nfunction createReverificationHandler(params: CreateReverificationHandlerParams) {\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/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/reverification) for more information.\n *\n * ```tsx {{ filename: 'src/components/MyButton.tsx' }}\n * import { useReverification } from '@clerk/clerk-react'\n * import { isReverificationCancelledError } from '@clerk/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 *\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 {\n ActClaim,\n CheckAuthorizationWithCustomPermissions,\n GetToken,\n JwtPayload,\n OrganizationCustomPermissionKey,\n OrganizationCustomRoleKey,\n PendingSessionOptions,\n ReverificationConfig,\n SessionStatusClaim,\n SessionVerificationLevel,\n SessionVerificationTypes,\n SignOut,\n UseAuthReturn,\n} from '@clerk/types';\n\ntype TypesToConfig = Record<SessionVerificationTypes, Exclude<ReverificationConfig, SessionVerificationTypes>>;\ntype AuthorizationOptions = {\n userId: string | null | undefined;\n orgId: string | null | undefined;\n orgRole: string | null | undefined;\n orgPermissions: string[] | null | undefined;\n factorVerificationAge: [number, number] | null;\n features: string | null | undefined;\n plans: string | null | undefined;\n};\n\ntype CheckOrgAuthorization = (\n params: { role?: OrganizationCustomRoleKey; permission?: OrganizationCustomPermissionKey },\n options: Pick<AuthorizationOptions, 'orgId' | 'orgRole' | 'orgPermissions'>,\n) => boolean | null;\n\ntype CheckBillingAuthorization = (\n params: { feature?: string; plan?: string },\n options: Pick<AuthorizationOptions, 'plans' | 'features'>,\n) => boolean | null;\n\ntype CheckReverificationAuthorization = (\n params: {\n reverification?: ReverificationConfig;\n },\n { factorVerificationAge }: AuthorizationOptions,\n) => boolean | null;\n\nconst TYPES_TO_OBJECTS: TypesToConfig = {\n strict_mfa: {\n afterMinutes: 10,\n level: 'multi_factor',\n },\n strict: {\n afterMinutes: 10,\n level: 'second_factor',\n },\n moderate: {\n afterMinutes: 60,\n level: 'second_factor',\n },\n lax: {\n afterMinutes: 1_440,\n level: 'second_factor',\n },\n};\n\nconst ALLOWED_LEVELS = new Set<SessionVerificationLevel>(['first_factor', 'second_factor', 'multi_factor']);\n\nconst ALLOWED_TYPES = new Set<SessionVerificationTypes>(['strict_mfa', 'strict', 'moderate', 'lax']);\n\n// Helper functions\nconst isValidMaxAge = (maxAge: any) => typeof maxAge === 'number' && maxAge > 0;\nconst isValidLevel = (level: any) => ALLOWED_LEVELS.has(level);\nconst isValidVerificationType = (type: any) => ALLOWED_TYPES.has(type);\n\nconst prefixWithOrg = (value: string) => value.replace(/^(org:)*/, 'org:');\n\n/**\n * Checks if a user has the required organization-level authorization.\n * Verifies if the user has the specified role or permission within their organization.\n * @returns null, if unable to determine due to missing data or unspecified role/permission.\n */\nconst checkOrgAuthorization: CheckOrgAuthorization = (params, options) => {\n const { orgId, orgRole, orgPermissions } = options;\n if (!params.role && !params.permission) {\n return null;\n }\n\n if (!orgId || !orgRole || !orgPermissions) {\n return null;\n }\n\n if (params.permission) {\n return orgPermissions.includes(prefixWithOrg(params.permission));\n }\n\n if (params.role) {\n return prefixWithOrg(orgRole) === prefixWithOrg(params.role);\n }\n return null;\n};\n\nconst checkForFeatureOrPlan = (claim: string, featureOrPlan: string) => {\n const { org: orgFeatures, user: userFeatures } = splitByScope(claim);\n const [scope, _id] = featureOrPlan.split(':');\n const id = _id || scope;\n\n if (scope === 'org') {\n return orgFeatures.includes(id);\n } else if (scope === 'user') {\n return userFeatures.includes(id);\n } else {\n // Since org scoped features will not exist if there is not an active org, merging is safe.\n return [...orgFeatures, ...userFeatures].includes(id);\n }\n};\n\nconst checkBillingAuthorization: CheckBillingAuthorization = (params, options) => {\n const { features, plans } = options;\n\n if (params.feature && features) {\n return checkForFeatureOrPlan(features, params.feature);\n }\n\n if (params.plan && plans) {\n return checkForFeatureOrPlan(plans, params.plan);\n }\n return null;\n};\n\nconst splitByScope = (fea: string | null | undefined) => {\n const features = fea ? fea.split(',').map(f => f.trim()) : [];\n\n // TODO: make this more efficient\n return {\n org: features.filter(f => f.split(':')[0].includes('o')).map(f => f.split(':')[1]),\n user: features.filter(f => f.split(':')[0].includes('u')).map(f => f.split(':')[1]),\n };\n};\n\nconst validateReverificationConfig = (config: ReverificationConfig | undefined | null) => {\n if (!config) {\n return false;\n }\n\n const convertConfigToObject = (config: ReverificationConfig) => {\n if (typeof config === 'string') {\n return TYPES_TO_OBJECTS[config];\n }\n return config;\n };\n\n const isValidStringValue = typeof config === 'string' && isValidVerificationType(config);\n const isValidObjectValue =\n typeof config === 'object' && isValidLevel(config.level) && isValidMaxAge(config.afterMinutes);\n\n if (isValidStringValue || isValidObjectValue) {\n return convertConfigToObject.bind(null, config);\n }\n\n return false;\n};\n\n/**\n * Evaluates if the user meets re-verification authentication requirements.\n * Compares the user's factor verification ages against the specified maxAge.\n * Handles different verification levels (first factor, second factor, multi-factor).\n * @returns null, if requirements or verification data are missing.\n */\nconst checkReverificationAuthorization: CheckReverificationAuthorization = (params, { factorVerificationAge }) => {\n if (!params.reverification || !factorVerificationAge) {\n return null;\n }\n\n const isValidReverification = validateReverificationConfig(params.reverification);\n if (!isValidReverification) {\n return null;\n }\n\n const { level, afterMinutes } = isValidReverification();\n const [factor1Age, factor2Age] = factorVerificationAge;\n\n // -1 indicates the factor group (1fa,2fa) is not enabled\n // -1 for 1fa is not a valid scenario, but we need to make sure we handle it properly\n const isValidFactor1 = factor1Age !== -1 ? afterMinutes > factor1Age : null;\n const isValidFactor2 = factor2Age !== -1 ? afterMinutes > factor2Age : null;\n\n switch (level) {\n case 'first_factor':\n return isValidFactor1;\n case 'second_factor':\n return factor2Age !== -1 ? isValidFactor2 : isValidFactor1;\n case 'multi_factor':\n return factor2Age === -1 ? isValidFactor1 : isValidFactor1 && isValidFactor2;\n }\n};\n\n/**\n * Creates a function for comprehensive user authorization checks.\n * Combines organization-level and reverification authentication checks.\n * The returned function authorizes if both checks pass, or if at least one passes\n * when the other is indeterminate. Fails if userId is missing.\n */\nconst createCheckAuthorization = (options: AuthorizationOptions): CheckAuthorizationWithCustomPermissions => {\n return (params): boolean => {\n if (!options.userId) {\n return false;\n }\n\n const billingAuthorization = checkBillingAuthorization(params, options);\n const orgAuthorization = checkOrgAuthorization(params, options);\n const reverificationAuthorization = checkReverificationAuthorization(params, options);\n\n if ([billingAuthorization || orgAuthorization, reverificationAuthorization].some(a => a === null)) {\n return [billingAuthorization || orgAuthorization, reverificationAuthorization].some(a => a === true);\n }\n\n return [billingAuthorization || orgAuthorization, reverificationAuthorization].every(a => a === true);\n };\n};\n\ntype AuthStateOptions = {\n authObject: {\n userId?: string | null;\n sessionId?: string | null;\n sessionStatus?: SessionStatusClaim | null;\n sessionClaims?: JwtPayload | null;\n actor?: ActClaim | null;\n orgId?: string | null;\n orgRole?: OrganizationCustomRoleKey | null;\n orgSlug?: string | null;\n orgPermissions?: OrganizationCustomPermissionKey[] | null;\n getToken: GetToken;\n signOut: SignOut;\n has: (params: Parameters<CheckAuthorizationWithCustomPermissions>[0]) => boolean;\n };\n options: PendingSessionOptions;\n};\n\n/**\n * Shared utility function that centralizes auth state resolution logic,\n * preventing duplication across different packages.\n * @internal\n */\nconst resolveAuthState = ({\n authObject: {\n sessionId,\n sessionStatus,\n userId,\n actor,\n orgId,\n orgRole,\n orgSlug,\n signOut,\n getToken,\n has,\n sessionClaims,\n },\n options: { treatPendingAsSignedOut = true },\n}: AuthStateOptions): UseAuthReturn | undefined => {\n if (sessionId === undefined && userId === undefined) {\n return {\n isLoaded: false,\n isSignedIn: undefined,\n sessionId,\n sessionClaims: undefined,\n userId,\n actor: undefined,\n orgId: undefined,\n orgRole: undefined,\n orgSlug: undefined,\n has: undefined,\n signOut,\n getToken,\n } as const;\n }\n\n if (sessionId === null && userId === null) {\n return {\n isLoaded: true,\n isSignedIn: false,\n sessionId,\n userId,\n sessionClaims: null,\n actor: null,\n orgId: null,\n orgRole: null,\n orgSlug: null,\n has: () => false,\n signOut,\n getToken,\n } as const;\n }\n\n if (treatPendingAsSignedOut && sessionStatus === 'pending') {\n return {\n isLoaded: true,\n isSignedIn: false,\n sessionId: null,\n userId: null,\n sessionClaims: null,\n actor: null,\n orgId: null,\n orgRole: null,\n orgSlug: null,\n has: () => false,\n signOut,\n getToken,\n } as const;\n }\n\n if (!!sessionId && !!sessionClaims && !!userId && !!orgId && !!orgRole) {\n return {\n isLoaded: true,\n isSignedIn: true,\n sessionId,\n sessionClaims,\n userId,\n actor: actor || null,\n orgId,\n orgRole,\n orgSlug: orgSlug || null,\n has,\n signOut,\n getToken,\n } as const;\n }\n\n if (!!sessionId && !!sessionClaims && !!userId && !orgId) {\n return {\n isLoaded: true,\n isSignedIn: true,\n sessionId,\n sessionClaims,\n userId,\n actor: actor || null,\n orgId: null,\n orgRole: null,\n orgSlug: null,\n has,\n signOut,\n getToken,\n } as const;\n }\n};\n\nexport { createCheckAuthorization, validateReverificationConfig, resolveAuthState, splitByScope };\n","import type { ReverificationConfig } from '@clerk/types';\n\ntype ClerkError<T> = {\n clerk_error: T;\n};\n\nconst REVERIFICATION_REASON = 'reverification-error';\n\ntype ReverificationError<M extends { metadata?: any } = { metadata: unknown }> = ClerkError<\n {\n type: 'forbidden';\n reason: typeof REVERIFICATION_REASON;\n } & M\n>;\n\nconst reverificationError = <MC extends ReverificationConfig>(\n missingConfig?: MC,\n): ReverificationError<{\n metadata?: {\n reverification?: MC;\n };\n}> => ({\n clerk_error: {\n type: 'forbidden',\n reason: REVERIFICATION_REASON,\n metadata: {\n reverification: missingConfig,\n },\n },\n});\n\nconst reverificationErrorResponse = (...args: Parameters<typeof reverificationError>) =>\n new Response(JSON.stringify(reverificationError(...args)), {\n status: 403,\n });\n\nconst isReverificationHint = (result: any): result is ReturnType<typeof reverificationError> => {\n return (\n result &&\n typeof result === 'object' &&\n 'clerk_error' in result &&\n result.clerk_error?.type === 'forbidden' &&\n result.clerk_error?.reason === REVERIFICATION_REASON\n );\n};\n\nexport { reverificationError, reverificationErrorResponse, isReverificationHint };\n","import type {\n ClerkAPIError,\n ClerkAPIErrorJSON,\n ClerkAPIResponseError as ClerkAPIResponseErrorInterface,\n} from '@clerk/types';\n\n/**\n * Checks if the provided error object is an unauthorized error.\n *\n * @internal\n *\n * @deprecated This is no longer used, and will be removed in the next major version.\n */\nexport function isUnauthorizedError(e: any): boolean {\n const status = e?.status;\n const code = e?.errors?.[0]?.code;\n return code === 'authentication_invalid' && status === 401;\n}\n\n/**\n * Checks if the provided error object is a captcha error.\n *\n * @internal\n */\nexport function isCaptchaError(e: ClerkAPIResponseError): boolean {\n return ['captcha_invalid', 'captcha_not_enabled', 'captcha_missing_token'].includes(e.errors[0].code);\n}\n\n/**\n * Checks if the provided error is a 4xx error.\n *\n * @internal\n */\nexport function is4xxError(e: any): boolean {\n const status = e?.status;\n return !!status && status >= 400 && status < 500;\n}\n\n/**\n * Checks if the provided error is a network error.\n *\n * @internal\n */\nexport function isNetworkError(e: any): boolean {\n // TODO: revise during error handling epic\n const message = (`${e.message}${e.name}` || '').toLowerCase().replace(/\\s+/g, '');\n return message.includes('networkerror');\n}\n\n/**\n * Options for creating a ClerkAPIResponseError.\n *\n * @internal\n */\ninterface ClerkAPIResponseOptions {\n data: ClerkAPIErrorJSON[];\n status: number;\n clerkTraceId?: string;\n retryAfter?: number;\n}\n\n// For a comprehensive Metamask error list, please see\n// https://docs.metamask.io/guide/ethereum-provider.html#errors\nexport interface MetamaskError extends Error {\n code: 4001 | 32602 | 32603;\n message: string;\n data?: unknown;\n}\n\n/**\n * Checks if the provided error is either a ClerkAPIResponseError, a ClerkRuntimeError, or a MetamaskError.\n *\n * @internal\n */\nexport function isKnownError(error: any): error is ClerkAPIResponseError | ClerkRuntimeError | MetamaskError {\n return isClerkAPIResponseError(error) || isMetamaskError(error) || isClerkRuntimeError(error);\n}\n\n/**\n * Checks if the provided error is a ClerkAPIResponseError.\n *\n * @internal\n */\nexport function isClerkAPIResponseError(err: any): err is ClerkAPIResponseError {\n return err && 'clerkError' in err;\n}\n\n/**\n * Checks if the provided error object is an instance of ClerkRuntimeError.\n *\n * @param err - The error object to check.\n * @returns True if the error is a ClerkRuntimeError, false otherwise.\n *\n * @example\n * const error = new ClerkRuntimeError('An error occurred');\n * if (isClerkRuntimeError(error)) {\n * // Handle ClerkRuntimeError\n * console.error('ClerkRuntimeError:', error.message);\n * } else {\n * // Handle other errors\n * console.error('Other error:', error.message);\n * }\n */\nexport function isClerkRuntimeError(err: any): err is ClerkRuntimeError {\n return 'clerkRuntimeError' in err;\n}\n\n/**\n * Checks if the provided error is a Clerk runtime error indicating a reverification was cancelled.\n *\n * @internal\n */\nexport function isReverificationCancelledError(err: any) {\n return isClerkRuntimeError(err) && err.code === 'reverification_cancelled';\n}\n\n/**\n * Checks if the provided error is a Metamask error.\n *\n * @internal\n */\nexport function isMetamaskError(err: any): err is MetamaskError {\n return 'code' in err && [4001, 32602, 32603].includes(err.code) && 'message' in err;\n}\n\n/**\n * Checks if the provided error is clerk api response error indicating a user is locked.\n *\n * @internal\n */\nexport function isUserLockedError(err: any) {\n return isClerkAPIResponseError(err) && err.errors?.[0]?.code === 'user_locked';\n}\n\n/**\n * Checks if the provided error is a clerk api response error indicating a password was pwned.\n *\n * @internal\n */\nexport function isPasswordPwnedError(err: any) {\n return isClerkAPIResponseError(err) && err.errors?.[0]?.code === 'form_password_pwned';\n}\n\n/**\n * Parses an array of ClerkAPIErrorJSON objects into an array of ClerkAPIError objects.\n *\n * @internal\n */\nexport function parseErrors(data: ClerkAPIErrorJSON[] = []): ClerkAPIError[] {\n return data.length > 0 ? data.map(parseError) : [];\n}\n\n/**\n * Parses a ClerkAPIErrorJSON object into a ClerkAPIError object.\n *\n * @internal\n */\nexport function parseError(error: ClerkAPIErrorJSON): ClerkAPIError {\n return {\n code: error.code,\n message: error.message,\n longMessage: error.long_message,\n meta: {\n paramName: error?.meta?.param_name,\n sessionId: error?.meta?.session_id,\n emailAddresses: error?.meta?.email_addresses,\n identifiers: error?.meta?.identifiers,\n zxcvbn: error?.meta?.zxcvbn,\n plan: error?.meta?.plan,\n isPlanUpgradePossible: error?.meta?.is_plan_upgrade_possible,\n },\n };\n}\n\n/**\n * Converts a ClerkAPIError object into a ClerkAPIErrorJSON object.\n *\n * @internal\n */\nexport function errorToJSON(error: ClerkAPIError | null): ClerkAPIErrorJSON {\n return {\n code: error?.code || '',\n message: error?.message || '',\n long_message: error?.longMessage,\n meta: {\n param_name: error?.meta?.paramName,\n session_id: error?.meta?.sessionId,\n email_addresses: error?.meta?.emailAddresses,\n identifiers: error?.meta?.identifiers,\n zxcvbn: error?.meta?.zxcvbn,\n plan: error?.meta?.plan,\n is_plan_upgrade_possible: error?.meta?.isPlanUpgradePossible,\n },\n };\n}\n\nexport class ClerkAPIResponseError extends Error implements ClerkAPIResponseErrorInterface {\n clerkError: true;\n\n status: number;\n message: string;\n clerkTraceId?: string;\n retryAfter?: number;\n\n errors: ClerkAPIError[];\n\n constructor(message: string, { data, status, clerkTraceId, retryAfter }: ClerkAPIResponseOptions) {\n super(message);\n\n Object.setPrototypeOf(this, ClerkAPIResponseError.prototype);\n\n this.status = status;\n this.message = message;\n this.clerkTraceId = clerkTraceId;\n this.retryAfter = retryAfter;\n this.clerkError = true;\n this.errors = parseErrors(data);\n }\n\n public toString = () => {\n let message = `[${this.name}]\\nMessage:${this.message}\\nStatus:${this.status}\\nSerialized errors: ${this.errors.map(\n e => JSON.stringify(e),\n )}`;\n\n if (this.clerkTraceId) {\n message += `\\nClerk Trace ID: ${this.clerkTraceId}`;\n }\n\n return message;\n };\n}\n\n/**\n * Custom error class for representing Clerk runtime errors.\n *\n * @class ClerkRuntimeError\n *\n * @example\n * throw new ClerkRuntimeError('An error occurred', { code: 'password_invalid' });\n */\nexport class ClerkRuntimeError extends Error {\n clerkRuntimeError: true;\n\n /**\n * The error message.\n *\n * @type {string}\n */\n message: string;\n\n /**\n * A unique code identifying the error, can be used for localization.\n *\n * @type {string}\n */\n code: string;\n\n constructor(message: string, { code }: { code: string }) {\n const prefix = '🔒 Clerk:';\n const regex = new RegExp(prefix.replace(' ', '\\\\s*'), 'i');\n const sanitized = message.replace(regex, '');\n const _message = `${prefix} ${sanitized.trim()}\\n\\n(code=\"${code}\")\\n`;\n super(_message);\n\n Object.setPrototypeOf(this, ClerkRuntimeError.prototype);\n\n this.code = code;\n this.message = _message;\n this.clerkRuntimeError = true;\n this.name = 'ClerkRuntimeError';\n }\n\n /**\n * Returns a string representation of the error.\n *\n * @returns A formatted string with the error name and message.\n */\n public toString = () => {\n return `[${this.name}]\\nMessage:${this.message}`;\n };\n}\n\nexport class EmailLinkError extends Error {\n code: string;\n\n constructor(code: string) {\n super(code);\n this.code = code;\n this.name = 'EmailLinkError' as const;\n Object.setPrototypeOf(this, EmailLinkError.prototype);\n }\n}\n\n/**\n * Checks if the provided error is an EmailLinkError.\n *\n * @internal\n */\nexport function isEmailLinkError(err: Error): err is EmailLinkError {\n return err.name === 'EmailLinkError';\n}\n\n/**\n * @deprecated Use `EmailLinkErrorCodeStatus` instead.\n *\n * @hidden\n */\nexport const EmailLinkErrorCode = {\n Expired: 'expired',\n Failed: 'failed',\n ClientMismatch: 'client_mismatch',\n};\n\nexport const EmailLinkErrorCodeStatus = {\n Expired: 'expired',\n Failed: 'failed',\n ClientMismatch: 'client_mismatch',\n} as const;\n\nconst DefaultMessages = Object.freeze({\n InvalidProxyUrlErrorMessage: `The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})`,\n InvalidPublishableKeyErrorMessage: `The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})`,\n MissingPublishableKeyErrorMessage: `Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.`,\n MissingSecretKeyErrorMessage: `Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.`,\n MissingClerkProvider: `{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider`,\n});\n\ntype MessageKeys = keyof typeof DefaultMessages;\n\ntype Messages = Record<MessageKeys, string>;\n\ntype CustomMessages = Partial<Messages>;\n\nexport type ErrorThrowerOptions = {\n packageName: string;\n customMessages?: CustomMessages;\n};\n\nexport interface ErrorThrower {\n setPackageName(options: ErrorThrowerOptions): ErrorThrower;\n\n setMessages(options: ErrorThrowerOptions): ErrorThrower;\n\n throwInvalidPublishableKeyError(params: { key?: string }): never;\n\n throwInvalidProxyUrl(params: { url?: string }): never;\n\n throwMissingPublishableKeyError(): never;\n\n throwMissingSecretKeyError(): never;\n\n throwMissingClerkProviderError(params: { source?: string }): never;\n\n throw(message: string): never;\n}\n\n/**\n * Builds an error thrower.\n *\n * @internal\n */\nexport function buildErrorThrower({ packageName, customMessages }: ErrorThrowerOptions): ErrorThrower {\n let pkg = packageName;\n\n /**\n * Builds a message from a raw message and replacements.\n *\n * @internal\n */\n function buildMessage(rawMessage: string, replacements?: Record<string, string | number>) {\n if (!replacements) {\n return `${pkg}: ${rawMessage}`;\n }\n\n let msg = rawMessage;\n const matches = rawMessage.matchAll(/{{([a-zA-Z0-9-_]+)}}/g);\n\n for (const match of matches) {\n const replacement = (replacements[match[1]] || '').toString();\n msg = msg.replace(`{{${match[1]}}}`, replacement);\n }\n\n return `${pkg}: ${msg}`;\n }\n\n const messages = {\n ...DefaultMessages,\n ...customMessages,\n };\n\n return {\n setPackageName({ packageName }: ErrorThrowerOptions): ErrorThrower {\n if (typeof packageName === 'string') {\n pkg = packageName;\n }\n return this;\n },\n\n setMessages({ customMessages }: ErrorThrowerOptions): ErrorThrower {\n Object.assign(messages, customMessages || {});\n return this;\n },\n\n throwInvalidPublishableKeyError(params: { key?: string }): never {\n throw new Error(buildMessage(messages.InvalidPublishableKeyErrorMessage, params));\n },\n\n throwInvalidProxyUrl(params: { url?: string }): never {\n throw new Error(buildMessage(messages.InvalidProxyUrlErrorMessage, params));\n },\n\n throwMissingPublishableKeyError(): never {\n throw new Error(buildMessage(messages.MissingPublishableKeyErrorMessage));\n },\n\n throwMissingSecretKeyError(): never {\n throw new Error(buildMessage(messages.MissingSecretKeyErrorMessage));\n },\n\n throwMissingClerkProviderError(params: { source?: string }): never {\n throw new Error(buildMessage(messages.MissingClerkProvider, params));\n },\n\n throw(message: string): never {\n throw new Error(buildMessage(message));\n },\n };\n}\n\ntype ClerkWebAuthnErrorCode =\n // Generic\n | 'passkey_not_supported'\n | 'passkey_pa_not_supported'\n | 'passkey_invalid_rpID_or_domain'\n | 'passkey_already_exists'\n | 'passkey_operation_aborted'\n // Retrieval\n | 'passkey_retrieval_cancelled'\n | 'passkey_retrieval_failed'\n // Registration\n | 'passkey_registration_cancelled'\n | 'passkey_registration_failed';\n\nexport class ClerkWebAuthnError extends ClerkRuntimeError {\n /**\n * A unique code identifying the error, can be used for localization.\n */\n code: ClerkWebAuthnErrorCode;\n\n constructor(message: string, { code }: { code: ClerkWebAuthnErrorCode }) {\n super(message, { code });\n this.code = code;\n }\n}\n","/**\n * Convert words to a sentence.\n *\n * @param items - An array of words to be joined.\n * @returns A string with the items joined by a comma and the last item joined by \", or\".\n */\nexport const toSentence = (items: string[]): string => {\n // TODO: Once Safari supports it, use Intl.ListFormat\n if (items.length == 0) {\n return '';\n }\n if (items.length == 1) {\n return items[0];\n }\n let sentence = items.slice(0, -1).join(', ');\n sentence += `, or ${items.slice(-1)}`;\n return sentence;\n};\n\nconst IP_V4_ADDRESS_REGEX =\n /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;\n\n/**\n * Checks if a string is a valid IPv4 address.\n *\n * @returns True if the string is a valid IPv4 address, false otherwise.\n */\nexport function isIPV4Address(str: string | undefined | null): boolean {\n return IP_V4_ADDRESS_REGEX.test(str || '');\n}\n\n/**\n * Converts the first character of a string to uppercase.\n *\n * @param str - The string to be converted.\n * @returns The modified string with the rest of the string unchanged.\n *\n * @example\n * ```ts\n * titleize('hello world') // 'Hello world'\n * ```\n */\nexport function titleize(str: string | undefined | null): string {\n const s = str || '';\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\n/**\n * Converts a string from snake_case to camelCase.\n */\nexport function snakeToCamel(str: string | undefined): string {\n return str ? str.replace(/([-_][a-z])/g, match => match.toUpperCase().replace(/-|_/, '')) : '';\n}\n\n/**\n * Converts a string from camelCase to snake_case.\n */\nexport function camelToSnake(str: string | undefined): string {\n return str ? str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`) : '';\n}\n\nconst createDeepObjectTransformer = (transform: any) => {\n const deepTransform = (obj: any): any => {\n if (!obj) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(el => {\n if (typeof el === 'object' || Array.isArray(el)) {\n return deepTransform(el);\n }\n return el;\n });\n }\n\n const copy = { ...obj };\n const keys = Object.keys(copy);\n for (const oldName of keys) {\n const newName = transform(oldName.toString());\n if (newName !== oldName) {\n copy[newName] = copy[oldName];\n delete copy[oldName];\n }\n if (typeof copy[newName] === 'object') {\n copy[newName] = deepTransform(copy[newName]);\n }\n }\n return copy;\n };\n\n return deepTransform;\n};\n\n/**\n * Transforms camelCased objects/ arrays to snake_cased.\n * This function recursively traverses all objects and arrays of the passed value\n * camelCased keys are removed.\n *\n * @function\n */\nexport const deepCamelToSnake = createDeepObjectTransformer(camelToSnake);\n\n/**\n * Transforms snake_cased objects/ arrays to camelCased.\n * This function recursively traverses all objects and arrays of the passed value\n * camelCased keys are removed.\n *\n * @function\n */\nexport const deepSnakeToCamel = createDeepObjectTransformer(snakeToCamel);\n\n/**\n * A function to determine if a value is truthy.\n *\n * @returns True for `true`, true, positive numbers. False for `false`, false, 0, negative integers and anything else.\n */\nexport function isTruthy(value: unknown): boolean {\n // Return if Boolean\n if (typeof value === `boolean`) {\n return value;\n }\n\n // Return false if null or undefined\n if (value === undefined || value === null) {\n return false;\n }\n\n // If the String is true or false\n if (typeof value === `string`) {\n if (value.toLowerCase() === `true`) {\n return true;\n }\n\n if (value.toLowerCase() === `false`) {\n return false;\n }\n }\n\n // Now check if it's a number\n const number = parseInt(value as string, 10);\n if (isNaN(number)) {\n return false;\n }\n\n if (number > 0) {\n return true;\n }\n\n // Default to false\n return false;\n}\n\n/**\n * Get all non-undefined values from an object.\n */\nexport function getNonUndefinedValues<T extends object>(obj: T): Partial<T> {\n return Object.entries(obj).reduce((acc, [key, value]) => {\n if (value !== undefined) {\n acc[key as keyof T] = value;\n }\n return acc;\n }, {} as Partial<T>);\n}\n","export const noop = (..._args: any[]): void => {\n // do nothing.\n};\n","import { noop } from './noop';\n\ntype Callback = (val?: any) => void;\n\n/**\n * Create a promise that can be resolved or rejected from\n * outside the Promise constructor callback\n * A ES6 compatible utility that implements `Promise.withResolvers`\n * @internal\n */\nexport const createDeferredPromise = () => {\n let resolve: Callback = noop;\n let reject: Callback = noop;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n};\n","import type { ClerkPaginatedResponse, ClerkResource, ForPayerType } from '@clerk/types';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useUserContext,\n} from '../contexts';\nimport type { PagesOrInfiniteOptions, PaginatedHookConfig, PaginatedResources } from '../types';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @internal\n */\ntype CommerceHookConfig<TResource extends ClerkResource, TParams extends PagesOrInfiniteOptions> = {\n hookName: string;\n resourceType: string;\n useFetcher: (\n param: ForPayerType,\n ) => ((params: TParams & { orgId?: string }) => Promise<ClerkPaginatedResponse<TResource>>) | undefined;\n options?: {\n unauthenticated?: boolean;\n };\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 createCommercePaginatedHook<TResource extends ClerkResource, TParams extends PagesOrInfiniteOptions>({\n hookName,\n resourceType,\n useFetcher,\n options,\n}: CommerceHookConfig<TResource, TParams>) {\n type HookParams = PaginatedHookConfig<PagesOrInfiniteOptions> & {\n for: ForPayerType;\n };\n\n return function useCommerceHook<T extends HookParams>(\n params?: T,\n ): PaginatedResources<TResource, T extends { infinite: true } ? true : false> {\n const { for: _for, ...paginationParams } = params || ({ for: 'user' } as T);\n\n useAssertWrappedByClerkProvider(hookName);\n\n const fetchFn = useFetcher(_for);\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 const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n const hookParams =\n typeof paginationParams === 'undefined'\n ? undefined\n : ({\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n ...(_for === 'organization' ? { orgId: organization?.id } : {}),\n } as TParams);\n\n const isClerkLoaded = !!(clerk.loaded && (options?.unauthenticated ? true : user));\n\n const isEnabled = !!hookParams && isClerkLoaded;\n\n const result = usePagesOrInfinite<TParams, ClerkPaginatedResponse<TResource>>(\n (hookParams || {}) as TParams,\n fetchFn,\n {\n keepPreviousData: safeValues.keepPreviousData,\n infinite: safeValues.infinite,\n enabled: isEnabled,\n __experimental_mode: safeValues.__experimental_mode,\n },\n {\n type: resourceType,\n userId: user?.id,\n ...(_for === 'organization' ? { orgId: organization?.id } : {}),\n },\n );\n\n return result;\n };\n}\n","import type { CommerceStatementResource, GetStatementsParams } from '@clerk/types';\n\nimport { useClerkInstanceContext } from '../contexts';\nimport { createCommercePaginatedHook } from './createCommerceHook';\n\n/**\n * @internal\n */\nexport const useStatements = createCommercePaginatedHook<CommerceStatementResource, GetStatementsParams>({\n hookName: 'useStatements',\n resourceType: 'commerce-statements',\n useFetcher: () => {\n const clerk = useClerkInstanceContext();\n return clerk.billing.getStatements;\n },\n});\n","import type { CommercePaymentResource, GetPaymentAttemptsParams } from '@clerk/types';\n\nimport { useClerkInstanceContext } from '../contexts';\nimport { createCommercePaginatedHook } from './createCommerceHook';\n\n/**\n * @internal\n */\nexport const usePaymentAttempts = createCommercePaginatedHook<CommercePaymentResource, GetPaymentAttemptsParams>({\n hookName: 'usePaymentAttempts',\n resourceType: 'commerce-payment-attempts',\n useFetcher: () => {\n const clerk = useClerkInstanceContext();\n return clerk.billing.getPaymentAttempts;\n },\n});\n","import type { CommercePaymentSourceResource, GetPaymentSourcesParams } from '@clerk/types';\n\nimport { useOrganizationContext, useUserContext } from '../contexts';\nimport { createCommercePaginatedHook } from './createCommerceHook';\n\n/**\n * @internal\n */\nexport const usePaymentMethods = createCommercePaginatedHook<CommercePaymentSourceResource, GetPaymentSourcesParams>({\n hookName: 'usePaymentMethods',\n resourceType: 'commerce-payment-methods',\n useFetcher: resource => {\n const { organization } = useOrganizationContext();\n const user = useUserContext();\n\n if (resource === 'organization') {\n return organization?.getPaymentSources;\n }\n return user?.getPaymentSources;\n },\n});\n","import type { CommercePlanResource, GetPlansParams } from '@clerk/types';\n\nimport { useClerkInstanceContext } from '../contexts';\nimport { createCommercePaginatedHook } from './createCommerceHook';\n\n/**\n * @internal\n */\nexport const usePlans = createCommercePaginatedHook<CommercePlanResource, GetPlansParams>({\n hookName: 'usePlans',\n resourceType: 'commerce-plans',\n useFetcher: _for => {\n const clerk = useClerkInstanceContext();\n return ({ orgId, ...rest }) => {\n // Cleanup `orgId` from the params\n return clerk.billing.getPlans({ ...rest, for: _for });\n };\n },\n options: {\n unauthenticated: true,\n },\n});\n","import type { ForPayerType } from '@clerk/types';\nimport { useCallback } from 'react';\n\nimport { eventMethodCalled } from '../../telemetry/events';\nimport { useSWR } from '../clerk-swr';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useUserContext,\n} from '../contexts';\n\nconst hookName = 'useSubscription';\n\ntype UseSubscriptionParams = {\n for?: ForPayerType;\n /**\n * If `true`, the previous data will be kept in the cache until new data is fetched.\n *\n * @default false\n */\n keepPreviousData?: boolean;\n};\n\n/**\n * @internal\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change.\n *\n * Fetches subscription data for the current user or organization.\n */\nexport const useSubscription = (params?: UseSubscriptionParams) => {\n useAssertWrappedByClerkProvider(hookName);\n\n const clerk = useClerkInstanceContext();\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n const swr = useSWR(\n user?.id\n ? {\n type: 'commerce-subscription',\n userId: user.id,\n args: { orgId: params?.for === 'organization' ? organization?.id : undefined },\n }\n : null,\n ({ args }) => clerk.billing.getSubscription(args),\n {\n dedupingInterval: 1_000 * 60,\n keepPreviousData: params?.keepPreviousData,\n },\n );\n\n const revalidate = useCallback(() => swr.mutate(), [swr.mutate]);\n\n return {\n data: swr.data,\n error: swr.error,\n isLoading: swr.isLoading,\n isFetching: swr.isValidating,\n revalidate,\n };\n};\n","import type {\n __experimental_CheckoutCacheState,\n __experimental_CheckoutInstance,\n CommerceCheckoutResource,\n SetActiveNavigate,\n} from '@clerk/types';\nimport { useMemo, useSyncExternalStore } from 'react';\n\nimport type { ClerkAPIResponseError } from '../..';\nimport type { __experimental_CheckoutProvider } from '../contexts';\nimport { useCheckoutContext } from '../contexts';\nimport { useClerk } from './useClerk';\nimport { useOrganization } from './useOrganization';\nimport { useUser } from './useUser';\n\n/**\n * Utility type that removes function properties from a type.\n */\ntype RemoveFunctions<T> = {\n [K in keyof T as T[K] extends (...args: any[]) => any ? never : K]: T[K];\n};\n\n/**\n * Utility type that makes all properties `null`.\n */\ntype ForceNull<T> = {\n [K in keyof T]: null;\n};\n\ntype CheckoutProperties = Omit<RemoveFunctions<CommerceCheckoutResource>, 'pathRoot' | 'status'>;\n\ntype FetchStatusAndError =\n | {\n error: ClerkAPIResponseError;\n fetchStatus: 'error';\n }\n | {\n error: null;\n fetchStatus: 'idle' | 'fetching';\n };\n\n/**\n * @internal\n * On status === 'needs_initialization', all properties are null.\n * On status === 'needs_confirmation' or 'completed', all properties are defined the same as the CommerceCheckoutResource.\n */\ntype CheckoutPropertiesPerStatus =\n | ({\n status: Extract<__experimental_CheckoutCacheState['status'], 'needs_initialization'>;\n } & ForceNull<CheckoutProperties>)\n | ({\n status: Extract<__experimental_CheckoutCacheState['status'], 'needs_confirmation' | 'completed'>;\n } & CheckoutProperties);\n\ntype __experimental_UseCheckoutReturn = {\n checkout: FetchStatusAndError &\n CheckoutPropertiesPerStatus & {\n confirm: __experimental_CheckoutInstance['confirm'];\n start: __experimental_CheckoutInstance['start'];\n clear: () => void;\n finalize: (params?: { navigate?: SetActiveNavigate }) => void;\n getState: () => __experimental_CheckoutCacheState;\n isStarting: boolean;\n isConfirming: boolean;\n };\n};\n\ntype Params = Parameters<typeof __experimental_CheckoutProvider>[0];\n\nexport const useCheckout = (options?: Params): __experimental_UseCheckoutReturn => {\n const contextOptions = useCheckoutContext();\n const { for: forOrganization, planId, planPeriod } = options || contextOptions;\n\n const clerk = useClerk();\n const { organization } = useOrganization();\n const { isLoaded, user } = useUser();\n\n if (!isLoaded) {\n throw new Error('Clerk: Ensure that `useCheckout` is inside a component wrapped with `<ClerkLoaded />`.');\n }\n\n if (!user) {\n throw new Error('Clerk: Ensure that `useCheckout` is inside a component wrapped with `<SignedIn />`.');\n }\n\n if (forOrganization === 'organization' && !organization) {\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/references/backend/types/auth-object#how-to-access-the-auth-object',\n );\n }\n\n const manager = useMemo(\n () => clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization }),\n [user.id, organization?.id, planId, planPeriod, forOrganization],\n );\n\n const managerProperties = useSyncExternalStore(\n cb => manager.subscribe(cb),\n () => manager.getState(),\n () => manager.getState(),\n );\n\n const properties = useMemo<CheckoutProperties | ForceNull<CheckoutProperties>>(() => {\n if (!managerProperties.checkout) {\n return {\n id: null,\n externalClientSecret: null,\n externalGatewayId: null,\n status: null,\n totals: null,\n isImmediatePlanChange: null,\n planPeriod: null,\n plan: null,\n paymentSource: null,\n freeTrialEndsAt: null,\n };\n }\n const {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n reload,\n confirm,\n pathRoot,\n // All the above need to be removed from the properties\n ...rest\n } = managerProperties.checkout;\n return rest;\n }, [managerProperties.checkout]);\n\n const checkout = {\n ...properties,\n getState: manager.getState,\n start: manager.start,\n confirm: manager.confirm,\n clear: manager.clear,\n finalize: manager.finalize,\n isStarting: managerProperties.isStarting,\n isConfirming: managerProperties.isConfirming,\n error: managerProperties.error,\n status: managerProperties.status,\n fetchStatus: managerProperties.fetchStatus,\n };\n\n return {\n checkout,\n } as __experimental_UseCheckoutReturn;\n};\n","/* eslint-disable @typescript-eslint/consistent-type-imports */\nimport type { CommerceCheckoutResource, EnvironmentResource, ForPayerType } from '@clerk/types';\nimport type { Stripe, StripeElements } from '@stripe/stripe-js';\nimport { type PropsWithChildren, ReactNode, useCallback, useEffect, useMemo, useState } from 'react';\nimport React from 'react';\nimport useSWR from 'swr';\nimport useSWRMutation from 'swr/mutation';\n\nimport { createContextAndHook } from './hooks/createContextAndHook';\nimport type { useCheckout } from './hooks/useCheckout';\nimport { useClerk } from './hooks/useClerk';\nimport { useOrganization } from './hooks/useOrganization';\nimport { useUser } from './hooks/useUser';\nimport { Elements, PaymentElement as StripePaymentElement, useElements, useStripe } from './stripe-react';\n\ntype LoadStripeFn = typeof import('@stripe/stripe-js').loadStripe;\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 [StripeLibsContext, useStripeLibsContext] = createContextAndHook<{\n loadStripe: LoadStripeFn;\n} | null>('StripeLibsContext');\n\nconst StripeLibsProvider = ({ children }: PropsWithChildren) => {\n const clerk = useClerk();\n const { data: stripeClerkLibs } = useSWR(\n 'clerk-stripe-sdk',\n async () => {\n const loadStripe = (await clerk.__internal_loadStripeJs()) as LoadStripeFn;\n return { loadStripe };\n },\n {\n keepPreviousData: true,\n revalidateOnFocus: false,\n dedupingInterval: Infinity,\n },\n );\n\n return (\n <StripeLibsContext.Provider\n value={{\n value: stripeClerkLibs || null,\n }}\n >\n {children}\n </StripeLibsContext.Provider>\n );\n};\n\nconst useInternalEnvironment = () => {\n const clerk = useClerk();\n // @ts-expect-error `__unstable__environment` is not typed\n return clerk.__unstable__environment as unknown as EnvironmentResource | null | undefined;\n};\n\nconst usePaymentSourceUtils = (forResource: ForPayerType = 'user') => {\n const { organization } = useOrganization();\n const { user } = useUser();\n const resource = forResource === 'organization' ? organization : user;\n const stripeClerkLibs = useStripeLibsContext();\n\n const { data: initializedPaymentSource, trigger: initializePaymentSource } = useSWRMutation(\n {\n key: 'commerce-payment-source-initialize',\n resourceId: resource?.id,\n },\n () => {\n return resource?.initializePaymentSource({\n gateway: 'stripe',\n });\n },\n );\n\n const environment = useInternalEnvironment();\n\n useEffect(() => {\n if (!resource?.id) return;\n initializePaymentSource().catch(() => {\n // ignore errors\n });\n }, [resource?.id]);\n\n const externalGatewayId = initializedPaymentSource?.externalGatewayId;\n const externalClientSecret = initializedPaymentSource?.externalClientSecret;\n const paymentMethodOrder = initializedPaymentSource?.paymentMethodOrder;\n const stripePublishableKey = environment?.commerceSettings.billing.stripePublishableKey;\n\n const { data: stripe } = useSWR(\n stripeClerkLibs && externalGatewayId && stripePublishableKey\n ? { key: 'stripe-sdk', externalGatewayId, stripePublishableKey }\n : null,\n ({ stripePublishableKey, externalGatewayId }) => {\n return stripeClerkLibs?.loadStripe(stripePublishableKey, {\n stripeAccount: externalGatewayId,\n });\n },\n {\n keepPreviousData: true,\n revalidateOnFocus: false,\n dedupingInterval: 1_000 * 60, // 1 minute\n },\n );\n\n return {\n stripe,\n initializePaymentSource,\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\ntype PaymentElementProviderProps = {\n checkout?: CommerceCheckoutResource | ReturnType<typeof useCheckout>['checkout'];\n stripeAppearance?: internalStripeAppearance;\n /**\n * Default to `user` if not provided.\n *\n * @default 'user'\n */\n for?: ForPayerType;\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 <StripeLibsProvider>\n <PropsProvider {...props}>\n <PaymentElementInternalRoot>{children}</PaymentElementInternalRoot>\n </PropsProvider>\n </StripeLibsProvider>\n );\n};\n\nconst PaymentElementInternalRoot = (props: PropsWithChildren) => {\n const { stripe, externalClientSecret, stripeAppearance } = usePaymentElementContext();\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 }}\n >\n <ValidateStripeUtils>{props.children}</ValidateStripeUtils>\n </Elements>\n );\n }\n\n return <DummyStripeUtils>{props.children}</DummyStripeUtils>;\n};\n\nconst PaymentElement = ({ fallback }: { fallback?: ReactNode }) => {\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\ntype UsePaymentElementReturn = {\n submit: () => Promise<\n | {\n data: { gateway: 'stripe'; paymentToken: string };\n error: null;\n }\n | {\n data: null;\n error: PaymentElementError;\n }\n >;\n reset: () => Promise<void>;\n isFormReady: boolean;\n} & (\n | {\n provider: {\n name: 'stripe';\n };\n isProviderReady: true;\n }\n | {\n provider: undefined;\n isProviderReady: false;\n }\n);\n\nconst usePaymentElement = (): UsePaymentElementReturn => {\n const { isPaymentElementReady, initializePaymentSource } = 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 initializePaymentSource();\n }, [stripe, elements, initializePaymentSource]);\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 PaymentElementProvider as __experimental_PaymentElementProvider,\n PaymentElement as __experimental_PaymentElement,\n usePaymentElement as __experimental_usePaymentElement,\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) return ctx;\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) return false;\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) return false;\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) return left === right;\n\n const leftKeys = Object.keys(left);\n const rightKeys = Object.keys(right);\n\n if (leftKeys.length !== rightKeys.length) return false;\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, useElements, useStripe, PaymentElement };\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,mBAAkB;AAOX,SAAS,oBAAoB,YAAqB,UAA2D;AAClH,MAAI,CAAC,YAAY;AACf,UAAM,OAAO,aAAa,WAAW,IAAI,MAAM,QAAQ,IAAI,IAAI,MAAM,GAAG,SAAS,WAAW,YAAY;AAAA,EA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yBAAyB;AAE1D,QAAM,aAAS,4BAAY,YAAY;AACrC,QAAI,CAAC,UAAU,CAAC,UAAU;AACxB,aAAO,sBAAsB;AAAA,IAC/B;AAEA,UAAM,EAAE,aAAa,MAAM,IAAI,MAAM,OAAO,aAAa;AAAA,MACvD;AAAA,MACA,eAAe;AAAA,QACb,YAAY,OAAO,SAAS;AAAA,MAC9B;AAAA,MACA,UAAU;AAAA,IACZ,CAAC;AACD,QAAI,OAAO;AACT,aAAO;AAAA,QACL,MAAM;AAAA,QACN,OAAO;AAAA,UACL,SAAS;AAAA,UACT,OAAO;AAAA,YACL,MAAM,MAAM;AAAA,YACZ,SAAS,MAAM;AAAA,YACf,MAAM,MAAM;AAAA,UACd;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,MACL,MAAM,EAAE,SAAS,UAAU,cAAc,YAAY,eAAyB;AAAA,MAC9E,OAAO;AAAA,IACT;AAAA,EACF,GAAG,CAAC,QAAQ,QAAQ,CAAC;AAErB,QAAM,YAAQ,4BAAY,YAAY;AACpC,QAAI,CAAC,UAAU,CAAC,UAAU;AACxB,aAAO,sBAAsB;AAAA,IAC/B;AAEA,UAAM,wBAAwB;AAAA,EAChC,GAAG,CAAC,QAAQ,UAAU,uBAAuB,CAAC;AAE9C,QAAM,kBAAkB,QAAQ,UAAU,oBAAoB;AAE9D,MAAI,CAAC,iBAAiB;AACpB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,aAAa;AAAA,MACb,UAAU;AAAA,MACV,iBAAiB;AAAA,IACnB;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,aAAa;AAAA,IACb,UAAU;AAAA,MACR,MAAM;AAAA,IACR;AAAA,IACA;AAAA,EACF;AACF;","names":["PaymentElement","React","import_react","React","import_react","undefinedPaginatedResource","import_react","React","hookName","hookName","import_react","React","deepEqual","import_react","config","hookName","import_react","hookName","import_react","import_react","import_swr","import_react","import_react","React","ctx","isServer","useSWR","React","useSWRMutation","stripePublishableKey","externalGatewayId","PaymentElement"]}
1
+ {"version":3,"sources":["../../src/react/index.ts","../../src/react/hooks/createContextAndHook.ts","../../src/organization.ts","../../src/telemetry/events/method-called.ts","../../src/react/contexts.tsx","../../src/react/clerk-swr.ts","../../src/react/hooks/usePagesOrInfinite.ts","../../src/react/hooks/useOrganization.tsx","../../src/react/hooks/useOrganizationList.tsx","../../src/react/hooks/useSafeLayoutEffect.tsx","../../src/react/hooks/useSession.ts","../../src/react/hooks/useSessionList.ts","../../src/react/hooks/useUser.ts","../../src/react/hooks/useClerk.ts","../../src/react/hooks/useDeepEqualMemo.ts","../../src/react/hooks/useReverification.ts","../../src/authorization.ts","../../src/authorization-errors.ts","../../src/error.ts","../../src/underscore.ts","../../src/utils/noop.ts","../../src/utils/createDeferredPromise.ts","../../src/react/hooks/createCommerceHook.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.tsx","../../src/react/hooks/useCheckout.ts","../../src/react/commerce.tsx","../../src/react/stripe-react/index.tsx","../../src/react/stripe-react/utils.ts"],"sourcesContent":["export * from './hooks';\n\nexport {\n ClerkInstanceContext,\n ClientContext,\n OptionsContext,\n OrganizationProvider,\n SessionContext,\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useClientContext,\n useOptionsContext,\n useOrganizationContext,\n UserContext,\n useSessionContext,\n useUserContext,\n __experimental_CheckoutProvider,\n} from './contexts';\n\nexport * from './commerce';\n","'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","import type { OrganizationMembershipResource } from '@clerk/types';\n\n/**\n * Finds the organization membership for a given organization ID from a list of memberships\n * @param organizationMemberships - Array of organization memberships to search through\n * @param organizationId - ID of the organization to find the membership for\n * @returns The matching organization membership or undefined if not found\n */\nexport function getCurrentOrganizationMembership(\n organizationMemberships: OrganizationMembershipResource[],\n organizationId: string,\n) {\n return organizationMemberships.find(\n organizationMembership => organizationMembership.organization.id === organizationId,\n );\n}\n","import type { TelemetryEventRaw } from '@clerk/types';\n\nconst EVENT_METHOD_CALLED = 'METHOD_CALLED';\nconst EVENT_SAMPLING_RATE = 0.1;\n\ntype EventMethodCalled = {\n method: string;\n} & Record<string, string | number | boolean>;\n\n/**\n * Fired when a helper method is called from a Clerk SDK.\n */\nexport function eventMethodCalled(\n method: string,\n payload?: Record<string, unknown>,\n): TelemetryEventRaw<EventMethodCalled> {\n return {\n event: EVENT_METHOD_CALLED,\n eventSamplingRate: EVENT_SAMPLING_RATE,\n payload: {\n method,\n ...payload,\n },\n };\n}\n","'use client';\n\nimport type {\n ClerkOptions,\n ClientResource,\n CommerceSubscriptionPlanPeriod,\n ForPayerType,\n LoadedClerk,\n OrganizationResource,\n SignedInSessionResource,\n UserResource,\n} from '@clerk/types';\nimport type { PropsWithChildren } from 'react';\nimport React from 'react';\n\nimport { SWRConfig } from './clerk-swr';\nimport { createContextAndHook } from './hooks/createContextAndHook';\n\nconst [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook<LoadedClerk>('ClerkInstanceContext');\nconst [UserContext, useUserContext] = createContextAndHook<UserResource | null | undefined>('UserContext');\nconst [ClientContext, useClientContext] = createContextAndHook<ClientResource | null | undefined>('ClientContext');\nconst [SessionContext, useSessionContext] = createContextAndHook<SignedInSessionResource | null | undefined>(\n 'SessionContext',\n);\n\nconst OptionsContext = React.createContext<ClerkOptions>({});\n\ntype UseCheckoutOptions = {\n for?: ForPayerType;\n planPeriod: CommerceSubscriptionPlanPeriod;\n planId: 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\ntype OrganizationContextProps = {\n organization: OrganizationResource | null | undefined;\n};\nconst [OrganizationContextInternal, useOrganizationContext] = createContextAndHook<{\n organization: OrganizationResource | null | undefined;\n}>('OrganizationContext');\n\nconst OrganizationProvider = ({\n children,\n organization,\n swrConfig,\n}: PropsWithChildren<\n OrganizationContextProps & {\n // Exporting inferred types directly from SWR will result in error while building declarations\n swrConfig?: any;\n }\n>) => {\n return (\n <SWRConfig value={swrConfig}>\n <OrganizationContextInternal.Provider\n value={{\n value: { organization },\n }}\n >\n {children}\n </OrganizationContextInternal.Provider>\n </SWRConfig>\n );\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 ClientContext,\n useClientContext,\n OrganizationProvider,\n useOrganizationContext,\n UserContext,\n OptionsContext,\n useOptionsContext,\n useUserContext,\n SessionContext,\n useSessionContext,\n ClerkInstanceContext,\n useClerkInstanceContext,\n useCheckoutContext,\n __experimental_CheckoutProvider,\n useAssertWrappedByClerkProvider,\n};\n","'use client';\n\nexport * from 'swr';\n\nexport { default as useSWR } from 'swr';\nexport { default as useSWRInfinite } from 'swr/infinite';\n","'use client';\n\nimport { useCallback, useMemo, useRef, useState } from 'react';\n\nimport { useSWR, useSWRInfinite } from '../clerk-swr';\nimport type {\n CacheSetter,\n PagesOrInfiniteConfig,\n PagesOrInfiniteOptions,\n PaginatedResources,\n ValueOrSetter,\n} from '../types';\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 */\nfunction getDifferentKeys(obj1: Record<string, unknown>, obj2: Record<string, unknown>): 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 * 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\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\nconst cachingSWROptions = {\n dedupingInterval: 1000 * 60,\n focusThrottleInterval: 1000 * 60 * 2,\n} satisfies Parameters<typeof useSWR>[2];\n\ntype ArrayType<DataArray> = DataArray extends Array<infer ElementType> ? ElementType : never;\ntype ExtractData<Type> = Type extends { data: infer Data } ? ArrayType<Data> : Type;\n\ntype UsePagesOrInfinite = <\n Params extends PagesOrInfiniteOptions,\n FetcherReturnData extends Record<string, any>,\n CacheKeys extends Record<string, unknown> = Record<string, unknown>,\n TConfig extends PagesOrInfiniteConfig = PagesOrInfiniteConfig,\n>(\n /**\n * The parameters will be passed to the fetcher.\n */\n params: Params,\n /**\n * A Promise returning function to fetch your data.\n */\n fetcher: ((p: Params) => FetcherReturnData | Promise<FetcherReturnData>) | undefined,\n /**\n * Internal configuration of the hook.\n */\n config: TConfig,\n cacheKeys: CacheKeys,\n) => PaginatedResources<ExtractData<FetcherReturnData>, TConfig['infinite']>;\n\n/**\n * A flexible pagination hook that supports both traditional pagination and infinite loading.\n * It provides a unified API for handling paginated data fetching, with built-in caching through SWR.\n * The hook can operate in two modes:\n * - Traditional pagination: Fetches one page at a time with page navigation\n * - Infinite loading: Accumulates data as more pages are loaded.\n *\n * Features:\n * - Cache management with SWR\n * - Loading and error states\n * - Page navigation helpers\n * - Data revalidation and updates\n * - Support for keeping previous data while loading.\n *\n * @internal\n */\nexport const usePagesOrInfinite: UsePagesOrInfinite = (params, fetcher, config, cacheKeys) => {\n const [paginatedPage, setPaginatedPage] = useState(params.initialPage ?? 1);\n\n // Cache initialPage and initialPageSize until unmount\n const initialPageRef = useRef(params.initialPage ?? 1);\n const pageSizeRef = useRef(params.pageSize ?? 10);\n\n const enabled = config.enabled ?? true;\n const cacheMode = config.__experimental_mode === 'cache';\n const triggerInfinite = config.infinite ?? false;\n const keepPreviousData = config.keepPreviousData ?? false;\n\n const pagesCacheKey = {\n ...cacheKeys,\n ...params,\n initialPage: paginatedPage,\n pageSize: pageSizeRef.current,\n };\n\n // cacheMode being `true` indicates that the cache key is defined, but the fetcher is not.\n // This allows to ready the cache instead of firing a request.\n const shouldFetch = !triggerInfinite && enabled && (!cacheMode ? !!fetcher : true);\n const swrKey = shouldFetch ? pagesCacheKey : null;\n const swrFetcher =\n !cacheMode && !!fetcher\n ? (cacheKeyParams: Record<string, unknown>) => {\n const requestParams = getDifferentKeys(cacheKeyParams, cacheKeys);\n return fetcher({ ...params, ...requestParams });\n }\n : null;\n\n const {\n data: swrData,\n isValidating: swrIsValidating,\n isLoading: swrIsLoading,\n error: swrError,\n mutate: swrMutate,\n } = useSWR(swrKey, swrFetcher, { keepPreviousData, ...cachingSWROptions });\n\n const {\n data: swrInfiniteData,\n isLoading: swrInfiniteIsLoading,\n isValidating: swrInfiniteIsValidating,\n error: swrInfiniteError,\n size,\n setSize,\n mutate: swrInfiniteMutate,\n } = useSWRInfinite(\n pageIndex => {\n if (!triggerInfinite || !enabled) {\n return null;\n }\n\n return {\n ...params,\n ...cacheKeys,\n initialPage: initialPageRef.current + pageIndex,\n pageSize: pageSizeRef.current,\n };\n },\n cacheKeyParams => {\n // @ts-ignore\n const requestParams = getDifferentKeys(cacheKeyParams, cacheKeys);\n // @ts-ignore\n return fetcher?.(requestParams);\n },\n cachingSWROptions,\n );\n\n const page = useMemo(() => {\n if (triggerInfinite) {\n return size;\n }\n return paginatedPage;\n }, [triggerInfinite, size, paginatedPage]);\n\n const fetchPage: ValueOrSetter<number> = useCallback(\n numberOrgFn => {\n if (triggerInfinite) {\n void setSize(numberOrgFn);\n return;\n }\n return setPaginatedPage(numberOrgFn);\n },\n [setSize],\n );\n\n const data = useMemo(() => {\n if (triggerInfinite) {\n return swrInfiniteData?.map(a => a?.data).flat() ?? [];\n }\n return swrData?.data ?? [];\n }, [triggerInfinite, swrData, swrInfiniteData]);\n\n const count = useMemo(() => {\n if (triggerInfinite) {\n return swrInfiniteData?.[swrInfiniteData?.length - 1]?.total_count || 0;\n }\n return swrData?.total_count ?? 0;\n }, [triggerInfinite, swrData, swrInfiniteData]);\n\n const isLoading = triggerInfinite ? swrInfiniteIsLoading : swrIsLoading;\n const isFetching = triggerInfinite ? swrInfiniteIsValidating : swrIsValidating;\n const error = (triggerInfinite ? swrInfiniteError : swrError) ?? null;\n const isError = !!error;\n /**\n * Helpers.\n */\n const fetchNext = useCallback(() => {\n fetchPage(n => Math.max(0, n + 1));\n }, [fetchPage]);\n\n const fetchPrevious = useCallback(() => {\n fetchPage(n => Math.max(0, n - 1));\n }, [fetchPage]);\n\n const offsetCount = (initialPageRef.current - 1) * pageSizeRef.current;\n\n const pageCount = Math.ceil((count - offsetCount) / pageSizeRef.current);\n const hasNextPage = count - offsetCount * pageSizeRef.current > page * pageSizeRef.current;\n const hasPreviousPage = (page - 1) * pageSizeRef.current > offsetCount * pageSizeRef.current;\n\n const setData: CacheSetter = triggerInfinite\n ? value =>\n swrInfiniteMutate(value, {\n revalidate: false,\n })\n : value =>\n swrMutate(value, {\n revalidate: false,\n });\n\n const revalidate = triggerInfinite ? () => swrInfiniteMutate() : () => swrMutate();\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 // Let the hook return type define this type\n revalidate: revalidate as any,\n // Let the hook return type define this type\n setData: setData as any,\n };\n};\n","/* eslint-disable jsdoc/require-description-complete-sentence */\nimport type {\n ClerkPaginatedResponse,\n CommerceSubscriptionItemResource,\n GetDomainsParams,\n GetInvitationsParams,\n GetMembershipRequestParams,\n GetMembersParams,\n GetSubscriptionsParams,\n OrganizationDomainResource,\n OrganizationInvitationResource,\n OrganizationMembershipRequestResource,\n OrganizationMembershipResource,\n OrganizationResource,\n} from '@clerk/types';\n\nimport { getCurrentOrganizationMembership } from '../../organization';\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useSessionContext,\n} from '../contexts';\nimport type { PaginatedHookConfig, PaginatedResources, PaginatedResourcesWithDefault } from '../types';\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/organizations/verified-domains#enrollment-mode).</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/references/javascript/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 * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change.\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>`orgId`: A string that filters the subscriptions by the provided organization ID.</li>\n * <li>Any of the properties described in [Shared properties](#shared-properties).</li>\n * </ul>\n */\n subscriptions?: true | PaginatedHookConfig<GetSubscriptionsParams>;\n};\n\n/**\n * @interface\n */\nexport type UseOrganizationReturn<T extends UseOrganizationParams> =\n | {\n /**\n * A boolean that indicates whether Clerk has completed initialization. Initially `false`, becomes `true` once Clerk loads.\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 * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change.\n * Includes a paginated list of the organization's subscriptions.\n */\n subscriptions: PaginatedResourcesWithDefault<CommerceSubscriptionItemResource>;\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 subscriptions: PaginatedResourcesWithDefault<CommerceSubscriptionItemResource>;\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 subscriptions: PaginatedResources<\n CommerceSubscriptionItemResource,\n T['subscriptions'] 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/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/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 subscriptions: subscriptionsListParams,\n } = params || {};\n\n useAssertWrappedByClerkProvider('useOrganization');\n\n const { organization } = useOrganizationContext();\n const session = useSessionContext();\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 subscriptionsSafeValues = useWithSafeValues(subscriptionsListParams, {\n initialPage: 1,\n pageSize: 10,\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 subscriptionsParams =\n typeof subscriptionsListParams === 'undefined'\n ? undefined\n : {\n initialPage: subscriptionsSafeValues.initialPage,\n pageSize: subscriptionsSafeValues.pageSize,\n orgId: organization?.id,\n };\n\n const domains = usePagesOrInfinite<GetDomainsParams, ClerkPaginatedResponse<OrganizationDomainResource>>(\n {\n ...domainParams,\n },\n organization?.getDomains,\n {\n keepPreviousData: domainSafeValues.keepPreviousData,\n infinite: domainSafeValues.infinite,\n enabled: !!domainParams,\n },\n {\n type: 'domains',\n organizationId: organization?.id,\n },\n );\n\n const membershipRequests = usePagesOrInfinite<\n GetMembershipRequestParams,\n ClerkPaginatedResponse<OrganizationMembershipRequestResource>\n >(\n {\n ...membershipRequestParams,\n },\n organization?.getMembershipRequests,\n {\n keepPreviousData: membershipRequestSafeValues.keepPreviousData,\n infinite: membershipRequestSafeValues.infinite,\n enabled: !!membershipRequestParams,\n },\n {\n type: 'membershipRequests',\n organizationId: organization?.id,\n },\n );\n\n const memberships = usePagesOrInfinite<GetMembersParams, ClerkPaginatedResponse<OrganizationMembershipResource>>(\n membersParams || {},\n organization?.getMemberships,\n {\n keepPreviousData: membersSafeValues.keepPreviousData,\n infinite: membersSafeValues.infinite,\n enabled: !!membersParams,\n },\n {\n type: 'members',\n organizationId: organization?.id,\n },\n );\n\n const invitations = usePagesOrInfinite<GetInvitationsParams, ClerkPaginatedResponse<OrganizationInvitationResource>>(\n {\n ...invitationsParams,\n },\n organization?.getInvitations,\n {\n keepPreviousData: invitationsSafeValues.keepPreviousData,\n infinite: invitationsSafeValues.infinite,\n enabled: !!invitationsParams,\n },\n {\n type: 'invitations',\n organizationId: organization?.id,\n },\n );\n\n const subscriptions = usePagesOrInfinite<\n GetSubscriptionsParams,\n ClerkPaginatedResponse<CommerceSubscriptionItemResource>\n >(\n {\n ...subscriptionsParams,\n },\n organization?.getSubscriptions,\n {\n keepPreviousData: subscriptionsSafeValues.keepPreviousData,\n infinite: subscriptionsSafeValues.infinite,\n enabled: !!subscriptionsParams,\n },\n {\n type: 'subscriptions',\n organizationId: organization?.id,\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 subscriptions: 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 subscriptions: 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 subscriptions: 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 subscriptions,\n };\n}\n","/* eslint-disable jsdoc/require-description-complete-sentence */\nimport type {\n ClerkPaginatedResponse,\n CreateOrganizationParams,\n GetUserOrganizationInvitationsParams,\n GetUserOrganizationMembershipParams,\n GetUserOrganizationSuggestionsParams,\n OrganizationMembershipResource,\n OrganizationResource,\n OrganizationSuggestionResource,\n SetActive,\n UserOrganizationInvitationResource,\n} from '@clerk/types';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useUserContext } from '../contexts';\nimport type { PaginatedHookConfig, PaginatedResources, PaginatedResourcesWithDefault } from '../types';\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 * A boolean that indicates whether Clerk has completed initialization and there is an authenticated user. Initially `false`, becomes `true` once Clerk loads with a user.\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/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/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\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 = useUserContext();\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 GetUserOrganizationMembershipParams,\n ClerkPaginatedResponse<OrganizationMembershipResource>\n >(\n userMembershipsParams || {},\n user?.getOrganizationMemberships,\n {\n keepPreviousData: userMembershipsSafeValues.keepPreviousData,\n infinite: userMembershipsSafeValues.infinite,\n enabled: !!userMembershipsParams,\n },\n {\n type: 'userMemberships',\n userId: user?.id,\n },\n );\n\n const invitations = usePagesOrInfinite<\n GetUserOrganizationInvitationsParams,\n ClerkPaginatedResponse<UserOrganizationInvitationResource>\n >(\n {\n ...userInvitationsParams,\n },\n user?.getOrganizationInvitations,\n {\n keepPreviousData: userInvitationsSafeValues.keepPreviousData,\n infinite: userInvitationsSafeValues.infinite,\n enabled: !!userInvitationsParams,\n },\n {\n type: 'userInvitations',\n userId: user?.id,\n },\n );\n\n const suggestions = usePagesOrInfinite<\n GetUserOrganizationSuggestionsParams,\n ClerkPaginatedResponse<OrganizationSuggestionResource>\n >(\n {\n ...userSuggestionsParams,\n },\n user?.getOrganizationSuggestions,\n {\n keepPreviousData: userSuggestionsSafeValues.keepPreviousData,\n infinite: userSuggestionsSafeValues.infinite,\n enabled: !!userSuggestionsParams,\n },\n {\n type: 'userSuggestions',\n userId: user?.id,\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 type { UseSessionReturn } from '@clerk/types';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useSessionContext } from '../contexts';\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/references/javascript/session) object, as well as helpers for setting the active session.\n *\n * @unionReturnHeadings\n * [\"Initialization\", \"Signed out\", \"Signed in\"]\n *\n * @function\n *\n * @param [options] - An object containing options for the `useSession()` hook.\n *\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/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 * {@include ../../../docs/use-session.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useSession: UseSession = () => {\n useAssertWrappedByClerkProvider(hookName);\n\n const session = useSessionContext();\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 type { UseSessionListReturn } from '@clerk/types';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useClientContext } from '../contexts';\n\nconst hookName = 'useSessionList';\n/**\n * The `useSessionList()` hook returns an array of [`Session`](https://clerk.com/docs/references/javascript/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/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 * {@include ../../../docs/use-session-list.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useSessionList = (): UseSessionListReturn => {\n useAssertWrappedByClerkProvider(hookName);\n\n const isomorphicClerk = useClerkInstanceContext();\n const client = useClientContext();\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 type { UseUserReturn } from '@clerk/types';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport { useAssertWrappedByClerkProvider, useClerkInstanceContext, useUserContext } from '../contexts';\n\nconst hookName = 'useUser';\n/**\n * The `useUser()` hook provides access to the current user's [`User`](https://clerk.com/docs/references/javascript/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 and initialized.\n *\n * @unionReturnHeadings\n * [\"Initialization\", \"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/references/javascript/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/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/references/javascript/user) object, which calls the [`update()`](https://clerk.com/docs/references/javascript/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/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 * {@include ../../../docs/use-user.md#nextjs-01}\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/references/javascript/user) object, which calls the [`reload()`](https://clerk.com/docs/references/javascript/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/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 * {@include ../../../docs/use-user.md#nextjs-02}\n *\n * </Tab>\n * </Tabs>\n */\nexport function useUser(): UseUserReturn {\n useAssertWrappedByClerkProvider(hookName);\n\n const user = useUserContext();\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 type { LoadedClerk } from '@clerk/types';\n\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/references/javascript/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/references/javascript/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/references/javascript/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/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 * {@include ../../../docs/use-clerk.md#nextjs-01}\n *\n * </Tab>\n * </Tabs>\n */\nexport const useClerk = (): LoadedClerk => {\n useAssertWrappedByClerkProvider('useClerk');\n return useClerkInstanceContext();\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 type { Clerk, SessionVerificationLevel } from '@clerk/types';\nimport { 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 { createDeferredPromise } from '../../utils/createDeferredPromise';\nimport { useClerk } from './useClerk';\nimport { useSafeLayoutEffect } from './useSafeLayoutEffect';\n\nconst CLERK_API_REVERIFICATION_ERROR_CODE = 'session_reverification_required';\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 */\ntype NeedsReverificationParameters = {\n cancel: () => void;\n complete: () => void;\n level: SessionVerificationLevel | undefined;\n};\n\n/**\n * The optional options object.\n * @interface\n */\ntype UseReverificationOptions = {\n /**\n * A handler that is called when reverification is needed, this will opt-out of using the default UI when provided.\n *\n * @param cancel - A function that will cancel the reverification process.\n * @param complete - A function that will retry the original request after reverification.\n * @param level - The level returned with the reverification hint.\n *\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 fetcher: Fetcher,\n options?: Options,\n) => UseReverificationResult<Fetcher>;\n\ntype CreateReverificationHandlerParams = UseReverificationOptions & {\n openUIComponent: Clerk['__internal_openReverification'];\n telemetry: Clerk['telemetry'];\n};\n\nfunction createReverificationHandler(params: CreateReverificationHandlerParams) {\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/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/reverification) for more information.\n *\n * ```tsx {{ filename: 'src/components/MyButton.tsx' }}\n * import { useReverification } from '@clerk/clerk-react'\n * import { isReverificationCancelledError } from '@clerk/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 *\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 {\n ActClaim,\n CheckAuthorizationWithCustomPermissions,\n GetToken,\n JwtPayload,\n OrganizationCustomPermissionKey,\n OrganizationCustomRoleKey,\n PendingSessionOptions,\n ReverificationConfig,\n SessionStatusClaim,\n SessionVerificationLevel,\n SessionVerificationTypes,\n SignOut,\n UseAuthReturn,\n} from '@clerk/types';\n\ntype TypesToConfig = Record<SessionVerificationTypes, Exclude<ReverificationConfig, SessionVerificationTypes>>;\ntype AuthorizationOptions = {\n userId: string | null | undefined;\n orgId: string | null | undefined;\n orgRole: string | null | undefined;\n orgPermissions: string[] | null | undefined;\n factorVerificationAge: [number, number] | null;\n features: string | null | undefined;\n plans: string | null | undefined;\n};\n\ntype CheckOrgAuthorization = (\n params: { role?: OrganizationCustomRoleKey; permission?: OrganizationCustomPermissionKey },\n options: Pick<AuthorizationOptions, 'orgId' | 'orgRole' | 'orgPermissions'>,\n) => boolean | null;\n\ntype CheckBillingAuthorization = (\n params: { feature?: string; plan?: string },\n options: Pick<AuthorizationOptions, 'plans' | 'features'>,\n) => boolean | null;\n\ntype CheckReverificationAuthorization = (\n params: {\n reverification?: ReverificationConfig;\n },\n { factorVerificationAge }: AuthorizationOptions,\n) => boolean | null;\n\nconst TYPES_TO_OBJECTS: TypesToConfig = {\n strict_mfa: {\n afterMinutes: 10,\n level: 'multi_factor',\n },\n strict: {\n afterMinutes: 10,\n level: 'second_factor',\n },\n moderate: {\n afterMinutes: 60,\n level: 'second_factor',\n },\n lax: {\n afterMinutes: 1_440,\n level: 'second_factor',\n },\n};\n\nconst ALLOWED_LEVELS = new Set<SessionVerificationLevel>(['first_factor', 'second_factor', 'multi_factor']);\n\nconst ALLOWED_TYPES = new Set<SessionVerificationTypes>(['strict_mfa', 'strict', 'moderate', 'lax']);\n\n// Helper functions\nconst isValidMaxAge = (maxAge: any) => typeof maxAge === 'number' && maxAge > 0;\nconst isValidLevel = (level: any) => ALLOWED_LEVELS.has(level);\nconst isValidVerificationType = (type: any) => ALLOWED_TYPES.has(type);\n\nconst prefixWithOrg = (value: string) => value.replace(/^(org:)*/, 'org:');\n\n/**\n * Checks if a user has the required organization-level authorization.\n * Verifies if the user has the specified role or permission within their organization.\n * @returns null, if unable to determine due to missing data or unspecified role/permission.\n */\nconst checkOrgAuthorization: CheckOrgAuthorization = (params, options) => {\n const { orgId, orgRole, orgPermissions } = options;\n if (!params.role && !params.permission) {\n return null;\n }\n\n if (!orgId || !orgRole || !orgPermissions) {\n return null;\n }\n\n if (params.permission) {\n return orgPermissions.includes(prefixWithOrg(params.permission));\n }\n\n if (params.role) {\n return prefixWithOrg(orgRole) === prefixWithOrg(params.role);\n }\n return null;\n};\n\nconst checkForFeatureOrPlan = (claim: string, featureOrPlan: string) => {\n const { org: orgFeatures, user: userFeatures } = splitByScope(claim);\n const [scope, _id] = featureOrPlan.split(':');\n const id = _id || scope;\n\n if (scope === 'org') {\n return orgFeatures.includes(id);\n } else if (scope === 'user') {\n return userFeatures.includes(id);\n } else {\n // Since org scoped features will not exist if there is not an active org, merging is safe.\n return [...orgFeatures, ...userFeatures].includes(id);\n }\n};\n\nconst checkBillingAuthorization: CheckBillingAuthorization = (params, options) => {\n const { features, plans } = options;\n\n if (params.feature && features) {\n return checkForFeatureOrPlan(features, params.feature);\n }\n\n if (params.plan && plans) {\n return checkForFeatureOrPlan(plans, params.plan);\n }\n return null;\n};\n\nconst splitByScope = (fea: string | null | undefined) => {\n const features = fea ? fea.split(',').map(f => f.trim()) : [];\n\n // TODO: make this more efficient\n return {\n org: features.filter(f => f.split(':')[0].includes('o')).map(f => f.split(':')[1]),\n user: features.filter(f => f.split(':')[0].includes('u')).map(f => f.split(':')[1]),\n };\n};\n\nconst validateReverificationConfig = (config: ReverificationConfig | undefined | null) => {\n if (!config) {\n return false;\n }\n\n const convertConfigToObject = (config: ReverificationConfig) => {\n if (typeof config === 'string') {\n return TYPES_TO_OBJECTS[config];\n }\n return config;\n };\n\n const isValidStringValue = typeof config === 'string' && isValidVerificationType(config);\n const isValidObjectValue =\n typeof config === 'object' && isValidLevel(config.level) && isValidMaxAge(config.afterMinutes);\n\n if (isValidStringValue || isValidObjectValue) {\n return convertConfigToObject.bind(null, config);\n }\n\n return false;\n};\n\n/**\n * Evaluates if the user meets re-verification authentication requirements.\n * Compares the user's factor verification ages against the specified maxAge.\n * Handles different verification levels (first factor, second factor, multi-factor).\n * @returns null, if requirements or verification data are missing.\n */\nconst checkReverificationAuthorization: CheckReverificationAuthorization = (params, { factorVerificationAge }) => {\n if (!params.reverification || !factorVerificationAge) {\n return null;\n }\n\n const isValidReverification = validateReverificationConfig(params.reverification);\n if (!isValidReverification) {\n return null;\n }\n\n const { level, afterMinutes } = isValidReverification();\n const [factor1Age, factor2Age] = factorVerificationAge;\n\n // -1 indicates the factor group (1fa,2fa) is not enabled\n // -1 for 1fa is not a valid scenario, but we need to make sure we handle it properly\n const isValidFactor1 = factor1Age !== -1 ? afterMinutes > factor1Age : null;\n const isValidFactor2 = factor2Age !== -1 ? afterMinutes > factor2Age : null;\n\n switch (level) {\n case 'first_factor':\n return isValidFactor1;\n case 'second_factor':\n return factor2Age !== -1 ? isValidFactor2 : isValidFactor1;\n case 'multi_factor':\n return factor2Age === -1 ? isValidFactor1 : isValidFactor1 && isValidFactor2;\n }\n};\n\n/**\n * Creates a function for comprehensive user authorization checks.\n * Combines organization-level and reverification authentication checks.\n * The returned function authorizes if both checks pass, or if at least one passes\n * when the other is indeterminate. Fails if userId is missing.\n */\nconst createCheckAuthorization = (options: AuthorizationOptions): CheckAuthorizationWithCustomPermissions => {\n return (params): boolean => {\n if (!options.userId) {\n return false;\n }\n\n const billingAuthorization = checkBillingAuthorization(params, options);\n const orgAuthorization = checkOrgAuthorization(params, options);\n const reverificationAuthorization = checkReverificationAuthorization(params, options);\n\n if ([billingAuthorization || orgAuthorization, reverificationAuthorization].some(a => a === null)) {\n return [billingAuthorization || orgAuthorization, reverificationAuthorization].some(a => a === true);\n }\n\n return [billingAuthorization || orgAuthorization, reverificationAuthorization].every(a => a === true);\n };\n};\n\ntype AuthStateOptions = {\n authObject: {\n userId?: string | null;\n sessionId?: string | null;\n sessionStatus?: SessionStatusClaim | null;\n sessionClaims?: JwtPayload | null;\n actor?: ActClaim | null;\n orgId?: string | null;\n orgRole?: OrganizationCustomRoleKey | null;\n orgSlug?: string | null;\n orgPermissions?: OrganizationCustomPermissionKey[] | null;\n getToken: GetToken;\n signOut: SignOut;\n has: (params: Parameters<CheckAuthorizationWithCustomPermissions>[0]) => boolean;\n };\n options: PendingSessionOptions;\n};\n\n/**\n * Shared utility function that centralizes auth state resolution logic,\n * preventing duplication across different packages.\n * @internal\n */\nconst resolveAuthState = ({\n authObject: {\n sessionId,\n sessionStatus,\n userId,\n actor,\n orgId,\n orgRole,\n orgSlug,\n signOut,\n getToken,\n has,\n sessionClaims,\n },\n options: { treatPendingAsSignedOut = true },\n}: AuthStateOptions): UseAuthReturn | undefined => {\n if (sessionId === undefined && userId === undefined) {\n return {\n isLoaded: false,\n isSignedIn: undefined,\n sessionId,\n sessionClaims: undefined,\n userId,\n actor: undefined,\n orgId: undefined,\n orgRole: undefined,\n orgSlug: undefined,\n has: undefined,\n signOut,\n getToken,\n } as const;\n }\n\n if (sessionId === null && userId === null) {\n return {\n isLoaded: true,\n isSignedIn: false,\n sessionId,\n userId,\n sessionClaims: null,\n actor: null,\n orgId: null,\n orgRole: null,\n orgSlug: null,\n has: () => false,\n signOut,\n getToken,\n } as const;\n }\n\n if (treatPendingAsSignedOut && sessionStatus === 'pending') {\n return {\n isLoaded: true,\n isSignedIn: false,\n sessionId: null,\n userId: null,\n sessionClaims: null,\n actor: null,\n orgId: null,\n orgRole: null,\n orgSlug: null,\n has: () => false,\n signOut,\n getToken,\n } as const;\n }\n\n if (!!sessionId && !!sessionClaims && !!userId && !!orgId && !!orgRole) {\n return {\n isLoaded: true,\n isSignedIn: true,\n sessionId,\n sessionClaims,\n userId,\n actor: actor || null,\n orgId,\n orgRole,\n orgSlug: orgSlug || null,\n has,\n signOut,\n getToken,\n } as const;\n }\n\n if (!!sessionId && !!sessionClaims && !!userId && !orgId) {\n return {\n isLoaded: true,\n isSignedIn: true,\n sessionId,\n sessionClaims,\n userId,\n actor: actor || null,\n orgId: null,\n orgRole: null,\n orgSlug: null,\n has,\n signOut,\n getToken,\n } as const;\n }\n};\n\nexport { createCheckAuthorization, validateReverificationConfig, resolveAuthState, splitByScope };\n","import type { ReverificationConfig } from '@clerk/types';\n\ntype ClerkError<T> = {\n clerk_error: T;\n};\n\nconst REVERIFICATION_REASON = 'reverification-error';\n\ntype ReverificationError<M extends { metadata?: any } = { metadata: unknown }> = ClerkError<\n {\n type: 'forbidden';\n reason: typeof REVERIFICATION_REASON;\n } & M\n>;\n\nconst reverificationError = <MC extends ReverificationConfig>(\n missingConfig?: MC,\n): ReverificationError<{\n metadata?: {\n reverification?: MC;\n };\n}> => ({\n clerk_error: {\n type: 'forbidden',\n reason: REVERIFICATION_REASON,\n metadata: {\n reverification: missingConfig,\n },\n },\n});\n\nconst reverificationErrorResponse = (...args: Parameters<typeof reverificationError>) =>\n new Response(JSON.stringify(reverificationError(...args)), {\n status: 403,\n });\n\nconst isReverificationHint = (result: any): result is ReturnType<typeof reverificationError> => {\n return (\n result &&\n typeof result === 'object' &&\n 'clerk_error' in result &&\n result.clerk_error?.type === 'forbidden' &&\n result.clerk_error?.reason === REVERIFICATION_REASON\n );\n};\n\nexport { reverificationError, reverificationErrorResponse, isReverificationHint };\n","import type {\n ClerkAPIError,\n ClerkAPIErrorJSON,\n ClerkAPIResponseError as ClerkAPIResponseErrorInterface,\n} from '@clerk/types';\n\n/**\n * Checks if the provided error object is an unauthorized error.\n *\n * @internal\n *\n * @deprecated This is no longer used, and will be removed in the next major version.\n */\nexport function isUnauthorizedError(e: any): boolean {\n const status = e?.status;\n const code = e?.errors?.[0]?.code;\n return code === 'authentication_invalid' && status === 401;\n}\n\n/**\n * Checks if the provided error object is a captcha error.\n *\n * @internal\n */\nexport function isCaptchaError(e: ClerkAPIResponseError): boolean {\n return ['captcha_invalid', 'captcha_not_enabled', 'captcha_missing_token'].includes(e.errors[0].code);\n}\n\n/**\n * Checks if the provided error is a 4xx error.\n *\n * @internal\n */\nexport function is4xxError(e: any): boolean {\n const status = e?.status;\n return !!status && status >= 400 && status < 500;\n}\n\n/**\n * Checks if the provided error is a network error.\n *\n * @internal\n */\nexport function isNetworkError(e: any): boolean {\n // TODO: revise during error handling epic\n const message = (`${e.message}${e.name}` || '').toLowerCase().replace(/\\s+/g, '');\n return message.includes('networkerror');\n}\n\n/**\n * Options for creating a ClerkAPIResponseError.\n *\n * @internal\n */\ninterface ClerkAPIResponseOptions {\n data: ClerkAPIErrorJSON[];\n status: number;\n clerkTraceId?: string;\n retryAfter?: number;\n}\n\n// For a comprehensive Metamask error list, please see\n// https://docs.metamask.io/guide/ethereum-provider.html#errors\nexport interface MetamaskError extends Error {\n code: 4001 | 32602 | 32603;\n message: string;\n data?: unknown;\n}\n\n/**\n * Checks if the provided error is either a ClerkAPIResponseError, a ClerkRuntimeError, or a MetamaskError.\n *\n * @internal\n */\nexport function isKnownError(error: any): error is ClerkAPIResponseError | ClerkRuntimeError | MetamaskError {\n return isClerkAPIResponseError(error) || isMetamaskError(error) || isClerkRuntimeError(error);\n}\n\n/**\n * Checks if the provided error is a ClerkAPIResponseError.\n *\n * @internal\n */\nexport function isClerkAPIResponseError(err: any): err is ClerkAPIResponseError {\n return err && 'clerkError' in err;\n}\n\n/**\n * Checks if the provided error object is an instance of ClerkRuntimeError.\n *\n * @param err - The error object to check.\n * @returns True if the error is a ClerkRuntimeError, false otherwise.\n *\n * @example\n * const error = new ClerkRuntimeError('An error occurred');\n * if (isClerkRuntimeError(error)) {\n * // Handle ClerkRuntimeError\n * console.error('ClerkRuntimeError:', error.message);\n * } else {\n * // Handle other errors\n * console.error('Other error:', error.message);\n * }\n */\nexport function isClerkRuntimeError(err: any): err is ClerkRuntimeError {\n return 'clerkRuntimeError' in err;\n}\n\n/**\n * Checks if the provided error is a Clerk runtime error indicating a reverification was cancelled.\n *\n * @internal\n */\nexport function isReverificationCancelledError(err: any) {\n return isClerkRuntimeError(err) && err.code === 'reverification_cancelled';\n}\n\n/**\n * Checks if the provided error is a Metamask error.\n *\n * @internal\n */\nexport function isMetamaskError(err: any): err is MetamaskError {\n return 'code' in err && [4001, 32602, 32603].includes(err.code) && 'message' in err;\n}\n\n/**\n * Checks if the provided error is clerk api response error indicating a user is locked.\n *\n * @internal\n */\nexport function isUserLockedError(err: any) {\n return isClerkAPIResponseError(err) && err.errors?.[0]?.code === 'user_locked';\n}\n\n/**\n * Checks if the provided error is a clerk api response error indicating a password was pwned.\n *\n * @internal\n */\nexport function isPasswordPwnedError(err: any) {\n return isClerkAPIResponseError(err) && err.errors?.[0]?.code === 'form_password_pwned';\n}\n\n/**\n * Parses an array of ClerkAPIErrorJSON objects into an array of ClerkAPIError objects.\n *\n * @internal\n */\nexport function parseErrors(data: ClerkAPIErrorJSON[] = []): ClerkAPIError[] {\n return data.length > 0 ? data.map(parseError) : [];\n}\n\n/**\n * Parses a ClerkAPIErrorJSON object into a ClerkAPIError object.\n *\n * @internal\n */\nexport function parseError(error: ClerkAPIErrorJSON): ClerkAPIError {\n return {\n code: error.code,\n message: error.message,\n longMessage: error.long_message,\n meta: {\n paramName: error?.meta?.param_name,\n sessionId: error?.meta?.session_id,\n emailAddresses: error?.meta?.email_addresses,\n identifiers: error?.meta?.identifiers,\n zxcvbn: error?.meta?.zxcvbn,\n plan: error?.meta?.plan,\n isPlanUpgradePossible: error?.meta?.is_plan_upgrade_possible,\n },\n };\n}\n\n/**\n * Converts a ClerkAPIError object into a ClerkAPIErrorJSON object.\n *\n * @internal\n */\nexport function errorToJSON(error: ClerkAPIError | null): ClerkAPIErrorJSON {\n return {\n code: error?.code || '',\n message: error?.message || '',\n long_message: error?.longMessage,\n meta: {\n param_name: error?.meta?.paramName,\n session_id: error?.meta?.sessionId,\n email_addresses: error?.meta?.emailAddresses,\n identifiers: error?.meta?.identifiers,\n zxcvbn: error?.meta?.zxcvbn,\n plan: error?.meta?.plan,\n is_plan_upgrade_possible: error?.meta?.isPlanUpgradePossible,\n },\n };\n}\n\nexport class ClerkAPIResponseError extends Error implements ClerkAPIResponseErrorInterface {\n clerkError: true;\n\n status: number;\n message: string;\n clerkTraceId?: string;\n retryAfter?: number;\n\n errors: ClerkAPIError[];\n\n constructor(message: string, { data, status, clerkTraceId, retryAfter }: ClerkAPIResponseOptions) {\n super(message);\n\n Object.setPrototypeOf(this, ClerkAPIResponseError.prototype);\n\n this.status = status;\n this.message = message;\n this.clerkTraceId = clerkTraceId;\n this.retryAfter = retryAfter;\n this.clerkError = true;\n this.errors = parseErrors(data);\n }\n\n public toString = () => {\n let message = `[${this.name}]\\nMessage:${this.message}\\nStatus:${this.status}\\nSerialized errors: ${this.errors.map(\n e => JSON.stringify(e),\n )}`;\n\n if (this.clerkTraceId) {\n message += `\\nClerk Trace ID: ${this.clerkTraceId}`;\n }\n\n return message;\n };\n}\n\n/**\n * Custom error class for representing Clerk runtime errors.\n *\n * @class ClerkRuntimeError\n *\n * @example\n * throw new ClerkRuntimeError('An error occurred', { code: 'password_invalid' });\n */\nexport class ClerkRuntimeError extends Error {\n clerkRuntimeError: true;\n\n /**\n * The error message.\n *\n * @type {string}\n */\n message: string;\n\n /**\n * A unique code identifying the error, can be used for localization.\n *\n * @type {string}\n */\n code: string;\n\n constructor(message: string, { code }: { code: string }) {\n const prefix = '🔒 Clerk:';\n const regex = new RegExp(prefix.replace(' ', '\\\\s*'), 'i');\n const sanitized = message.replace(regex, '');\n const _message = `${prefix} ${sanitized.trim()}\\n\\n(code=\"${code}\")\\n`;\n super(_message);\n\n Object.setPrototypeOf(this, ClerkRuntimeError.prototype);\n\n this.code = code;\n this.message = _message;\n this.clerkRuntimeError = true;\n this.name = 'ClerkRuntimeError';\n }\n\n /**\n * Returns a string representation of the error.\n *\n * @returns A formatted string with the error name and message.\n */\n public toString = () => {\n return `[${this.name}]\\nMessage:${this.message}`;\n };\n}\n\nexport class EmailLinkError extends Error {\n code: string;\n\n constructor(code: string) {\n super(code);\n this.code = code;\n this.name = 'EmailLinkError' as const;\n Object.setPrototypeOf(this, EmailLinkError.prototype);\n }\n}\n\n/**\n * Checks if the provided error is an EmailLinkError.\n *\n * @internal\n */\nexport function isEmailLinkError(err: Error): err is EmailLinkError {\n return err.name === 'EmailLinkError';\n}\n\n/**\n * @deprecated Use `EmailLinkErrorCodeStatus` instead.\n *\n * @hidden\n */\nexport const EmailLinkErrorCode = {\n Expired: 'expired',\n Failed: 'failed',\n ClientMismatch: 'client_mismatch',\n};\n\nexport const EmailLinkErrorCodeStatus = {\n Expired: 'expired',\n Failed: 'failed',\n ClientMismatch: 'client_mismatch',\n} as const;\n\nconst DefaultMessages = Object.freeze({\n InvalidProxyUrlErrorMessage: `The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})`,\n InvalidPublishableKeyErrorMessage: `The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})`,\n MissingPublishableKeyErrorMessage: `Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.`,\n MissingSecretKeyErrorMessage: `Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.`,\n MissingClerkProvider: `{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider`,\n});\n\ntype MessageKeys = keyof typeof DefaultMessages;\n\ntype Messages = Record<MessageKeys, string>;\n\ntype CustomMessages = Partial<Messages>;\n\nexport type ErrorThrowerOptions = {\n packageName: string;\n customMessages?: CustomMessages;\n};\n\nexport interface ErrorThrower {\n setPackageName(options: ErrorThrowerOptions): ErrorThrower;\n\n setMessages(options: ErrorThrowerOptions): ErrorThrower;\n\n throwInvalidPublishableKeyError(params: { key?: string }): never;\n\n throwInvalidProxyUrl(params: { url?: string }): never;\n\n throwMissingPublishableKeyError(): never;\n\n throwMissingSecretKeyError(): never;\n\n throwMissingClerkProviderError(params: { source?: string }): never;\n\n throw(message: string): never;\n}\n\n/**\n * Builds an error thrower.\n *\n * @internal\n */\nexport function buildErrorThrower({ packageName, customMessages }: ErrorThrowerOptions): ErrorThrower {\n let pkg = packageName;\n\n /**\n * Builds a message from a raw message and replacements.\n *\n * @internal\n */\n function buildMessage(rawMessage: string, replacements?: Record<string, string | number>) {\n if (!replacements) {\n return `${pkg}: ${rawMessage}`;\n }\n\n let msg = rawMessage;\n const matches = rawMessage.matchAll(/{{([a-zA-Z0-9-_]+)}}/g);\n\n for (const match of matches) {\n const replacement = (replacements[match[1]] || '').toString();\n msg = msg.replace(`{{${match[1]}}}`, replacement);\n }\n\n return `${pkg}: ${msg}`;\n }\n\n const messages = {\n ...DefaultMessages,\n ...customMessages,\n };\n\n return {\n setPackageName({ packageName }: ErrorThrowerOptions): ErrorThrower {\n if (typeof packageName === 'string') {\n pkg = packageName;\n }\n return this;\n },\n\n setMessages({ customMessages }: ErrorThrowerOptions): ErrorThrower {\n Object.assign(messages, customMessages || {});\n return this;\n },\n\n throwInvalidPublishableKeyError(params: { key?: string }): never {\n throw new Error(buildMessage(messages.InvalidPublishableKeyErrorMessage, params));\n },\n\n throwInvalidProxyUrl(params: { url?: string }): never {\n throw new Error(buildMessage(messages.InvalidProxyUrlErrorMessage, params));\n },\n\n throwMissingPublishableKeyError(): never {\n throw new Error(buildMessage(messages.MissingPublishableKeyErrorMessage));\n },\n\n throwMissingSecretKeyError(): never {\n throw new Error(buildMessage(messages.MissingSecretKeyErrorMessage));\n },\n\n throwMissingClerkProviderError(params: { source?: string }): never {\n throw new Error(buildMessage(messages.MissingClerkProvider, params));\n },\n\n throw(message: string): never {\n throw new Error(buildMessage(message));\n },\n };\n}\n\ntype ClerkWebAuthnErrorCode =\n // Generic\n | 'passkey_not_supported'\n | 'passkey_pa_not_supported'\n | 'passkey_invalid_rpID_or_domain'\n | 'passkey_already_exists'\n | 'passkey_operation_aborted'\n // Retrieval\n | 'passkey_retrieval_cancelled'\n | 'passkey_retrieval_failed'\n // Registration\n | 'passkey_registration_cancelled'\n | 'passkey_registration_failed';\n\nexport class ClerkWebAuthnError extends ClerkRuntimeError {\n /**\n * A unique code identifying the error, can be used for localization.\n */\n code: ClerkWebAuthnErrorCode;\n\n constructor(message: string, { code }: { code: ClerkWebAuthnErrorCode }) {\n super(message, { code });\n this.code = code;\n }\n}\n","/**\n * Convert words to a sentence.\n *\n * @param items - An array of words to be joined.\n * @returns A string with the items joined by a comma and the last item joined by \", or\".\n */\nexport const toSentence = (items: string[]): string => {\n // TODO: Once Safari supports it, use Intl.ListFormat\n if (items.length == 0) {\n return '';\n }\n if (items.length == 1) {\n return items[0];\n }\n let sentence = items.slice(0, -1).join(', ');\n sentence += `, or ${items.slice(-1)}`;\n return sentence;\n};\n\nconst IP_V4_ADDRESS_REGEX =\n /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;\n\n/**\n * Checks if a string is a valid IPv4 address.\n *\n * @returns True if the string is a valid IPv4 address, false otherwise.\n */\nexport function isIPV4Address(str: string | undefined | null): boolean {\n return IP_V4_ADDRESS_REGEX.test(str || '');\n}\n\n/**\n * Converts the first character of a string to uppercase.\n *\n * @param str - The string to be converted.\n * @returns The modified string with the rest of the string unchanged.\n *\n * @example\n * ```ts\n * titleize('hello world') // 'Hello world'\n * ```\n */\nexport function titleize(str: string | undefined | null): string {\n const s = str || '';\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\n/**\n * Converts a string from snake_case to camelCase.\n */\nexport function snakeToCamel(str: string | undefined): string {\n return str ? str.replace(/([-_][a-z])/g, match => match.toUpperCase().replace(/-|_/, '')) : '';\n}\n\n/**\n * Converts a string from camelCase to snake_case.\n */\nexport function camelToSnake(str: string | undefined): string {\n return str ? str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`) : '';\n}\n\nconst createDeepObjectTransformer = (transform: any) => {\n const deepTransform = (obj: any): any => {\n if (!obj) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(el => {\n if (typeof el === 'object' || Array.isArray(el)) {\n return deepTransform(el);\n }\n return el;\n });\n }\n\n const copy = { ...obj };\n const keys = Object.keys(copy);\n for (const oldName of keys) {\n const newName = transform(oldName.toString());\n if (newName !== oldName) {\n copy[newName] = copy[oldName];\n delete copy[oldName];\n }\n if (typeof copy[newName] === 'object') {\n copy[newName] = deepTransform(copy[newName]);\n }\n }\n return copy;\n };\n\n return deepTransform;\n};\n\n/**\n * Transforms camelCased objects/ arrays to snake_cased.\n * This function recursively traverses all objects and arrays of the passed value\n * camelCased keys are removed.\n *\n * @function\n */\nexport const deepCamelToSnake = createDeepObjectTransformer(camelToSnake);\n\n/**\n * Transforms snake_cased objects/ arrays to camelCased.\n * This function recursively traverses all objects and arrays of the passed value\n * camelCased keys are removed.\n *\n * @function\n */\nexport const deepSnakeToCamel = createDeepObjectTransformer(snakeToCamel);\n\n/**\n * A function to determine if a value is truthy.\n *\n * @returns True for `true`, true, positive numbers. False for `false`, false, 0, negative integers and anything else.\n */\nexport function isTruthy(value: unknown): boolean {\n // Return if Boolean\n if (typeof value === `boolean`) {\n return value;\n }\n\n // Return false if null or undefined\n if (value === undefined || value === null) {\n return false;\n }\n\n // If the String is true or false\n if (typeof value === `string`) {\n if (value.toLowerCase() === `true`) {\n return true;\n }\n\n if (value.toLowerCase() === `false`) {\n return false;\n }\n }\n\n // Now check if it's a number\n const number = parseInt(value as string, 10);\n if (isNaN(number)) {\n return false;\n }\n\n if (number > 0) {\n return true;\n }\n\n // Default to false\n return false;\n}\n\n/**\n * Get all non-undefined values from an object.\n */\nexport function getNonUndefinedValues<T extends object>(obj: T): Partial<T> {\n return Object.entries(obj).reduce((acc, [key, value]) => {\n if (value !== undefined) {\n acc[key as keyof T] = value;\n }\n return acc;\n }, {} as Partial<T>);\n}\n","export const noop = (..._args: any[]): void => {\n // do nothing.\n};\n","import { noop } from './noop';\n\ntype Callback = (val?: any) => void;\n\n/**\n * Create a promise that can be resolved or rejected from\n * outside the Promise constructor callback\n * A ES6 compatible utility that implements `Promise.withResolvers`\n * @internal\n */\nexport const createDeferredPromise = () => {\n let resolve: Callback = noop;\n let reject: Callback = noop;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n};\n","import type { ClerkPaginatedResponse, ClerkResource, ForPayerType } from '@clerk/types';\n\nimport { eventMethodCalled } from '../../telemetry/events/method-called';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useUserContext,\n} from '../contexts';\nimport type { PagesOrInfiniteOptions, PaginatedHookConfig, PaginatedResources } from '../types';\nimport { usePagesOrInfinite, useWithSafeValues } from './usePagesOrInfinite';\n\n/**\n * @internal\n */\ntype CommerceHookConfig<TResource extends ClerkResource, TParams extends PagesOrInfiniteOptions> = {\n hookName: string;\n resourceType: string;\n useFetcher: (\n param: ForPayerType,\n ) => ((params: TParams & { orgId?: string }) => Promise<ClerkPaginatedResponse<TResource>>) | undefined;\n options?: {\n unauthenticated?: boolean;\n };\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 createCommercePaginatedHook<TResource extends ClerkResource, TParams extends PagesOrInfiniteOptions>({\n hookName,\n resourceType,\n useFetcher,\n options,\n}: CommerceHookConfig<TResource, TParams>) {\n type HookParams = PaginatedHookConfig<PagesOrInfiniteOptions> & {\n for: ForPayerType;\n };\n\n return function useCommerceHook<T extends HookParams>(\n params?: T,\n ): PaginatedResources<TResource, T extends { infinite: true } ? true : false> {\n const { for: _for, ...paginationParams } = params || ({ for: 'user' } as T);\n\n useAssertWrappedByClerkProvider(hookName);\n\n const fetchFn = useFetcher(_for);\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 const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n const hookParams =\n typeof paginationParams === 'undefined'\n ? undefined\n : ({\n initialPage: safeValues.initialPage,\n pageSize: safeValues.pageSize,\n ...(_for === 'organization' ? { orgId: organization?.id } : {}),\n } as TParams);\n\n const isClerkLoaded = !!(clerk.loaded && (options?.unauthenticated ? true : user));\n\n const isEnabled = !!hookParams && isClerkLoaded;\n\n const result = usePagesOrInfinite<TParams, ClerkPaginatedResponse<TResource>>(\n (hookParams || {}) as TParams,\n fetchFn,\n {\n keepPreviousData: safeValues.keepPreviousData,\n infinite: safeValues.infinite,\n enabled: isEnabled,\n __experimental_mode: safeValues.__experimental_mode,\n },\n {\n type: resourceType,\n userId: user?.id,\n ...(_for === 'organization' ? { orgId: organization?.id } : {}),\n },\n );\n\n return result;\n };\n}\n","import type { CommerceStatementResource, GetStatementsParams } from '@clerk/types';\n\nimport { useClerkInstanceContext } from '../contexts';\nimport { createCommercePaginatedHook } from './createCommerceHook';\n\n/**\n * @internal\n */\nexport const useStatements = createCommercePaginatedHook<CommerceStatementResource, GetStatementsParams>({\n hookName: 'useStatements',\n resourceType: 'commerce-statements',\n useFetcher: () => {\n const clerk = useClerkInstanceContext();\n return clerk.billing.getStatements;\n },\n});\n","import type { CommercePaymentResource, GetPaymentAttemptsParams } from '@clerk/types';\n\nimport { useClerkInstanceContext } from '../contexts';\nimport { createCommercePaginatedHook } from './createCommerceHook';\n\n/**\n * @internal\n */\nexport const usePaymentAttempts = createCommercePaginatedHook<CommercePaymentResource, GetPaymentAttemptsParams>({\n hookName: 'usePaymentAttempts',\n resourceType: 'commerce-payment-attempts',\n useFetcher: () => {\n const clerk = useClerkInstanceContext();\n return clerk.billing.getPaymentAttempts;\n },\n});\n","import type { CommercePaymentSourceResource, GetPaymentSourcesParams } from '@clerk/types';\n\nimport { useOrganizationContext, useUserContext } from '../contexts';\nimport { createCommercePaginatedHook } from './createCommerceHook';\n\n/**\n * @internal\n */\nexport const usePaymentMethods = createCommercePaginatedHook<CommercePaymentSourceResource, GetPaymentSourcesParams>({\n hookName: 'usePaymentMethods',\n resourceType: 'commerce-payment-methods',\n useFetcher: resource => {\n const { organization } = useOrganizationContext();\n const user = useUserContext();\n\n if (resource === 'organization') {\n return organization?.getPaymentSources;\n }\n return user?.getPaymentSources;\n },\n});\n","import type { CommercePlanResource, GetPlansParams } from '@clerk/types';\n\nimport { useClerkInstanceContext } from '../contexts';\nimport { createCommercePaginatedHook } from './createCommerceHook';\n\n/**\n * @internal\n */\nexport const usePlans = createCommercePaginatedHook<CommercePlanResource, GetPlansParams>({\n hookName: 'usePlans',\n resourceType: 'commerce-plans',\n useFetcher: _for => {\n const clerk = useClerkInstanceContext();\n return ({ orgId, ...rest }) => {\n // Cleanup `orgId` from the params\n return clerk.billing.getPlans({ ...rest, for: _for });\n };\n },\n options: {\n unauthenticated: true,\n },\n});\n","import type { ForPayerType } from '@clerk/types';\nimport { useCallback } from 'react';\n\nimport { eventMethodCalled } from '../../telemetry/events';\nimport { useSWR } from '../clerk-swr';\nimport {\n useAssertWrappedByClerkProvider,\n useClerkInstanceContext,\n useOrganizationContext,\n useUserContext,\n} from '../contexts';\n\nconst hookName = 'useSubscription';\n\ntype UseSubscriptionParams = {\n for?: ForPayerType;\n /**\n * If `true`, the previous data will be kept in the cache until new data is fetched.\n *\n * @default false\n */\n keepPreviousData?: boolean;\n};\n\n/**\n * @internal\n *\n * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change.\n *\n * Fetches subscription data for the current user or organization.\n */\nexport const useSubscription = (params?: UseSubscriptionParams) => {\n useAssertWrappedByClerkProvider(hookName);\n\n const clerk = useClerkInstanceContext();\n const user = useUserContext();\n const { organization } = useOrganizationContext();\n\n clerk.telemetry?.record(eventMethodCalled(hookName));\n\n const swr = useSWR(\n user?.id\n ? {\n type: 'commerce-subscription',\n userId: user.id,\n args: { orgId: params?.for === 'organization' ? organization?.id : undefined },\n }\n : null,\n ({ args }) => clerk.billing.getSubscription(args),\n {\n dedupingInterval: 1_000 * 60,\n keepPreviousData: params?.keepPreviousData,\n },\n );\n\n const revalidate = useCallback(() => swr.mutate(), [swr.mutate]);\n\n return {\n data: swr.data,\n error: swr.error,\n isLoading: swr.isLoading,\n isFetching: swr.isValidating,\n revalidate,\n };\n};\n","import type {\n __experimental_CheckoutCacheState,\n __experimental_CheckoutInstance,\n CommerceCheckoutResource,\n SetActiveNavigate,\n} from '@clerk/types';\nimport { useMemo, useSyncExternalStore } from 'react';\n\nimport type { ClerkAPIResponseError } from '../..';\nimport type { __experimental_CheckoutProvider } from '../contexts';\nimport { useCheckoutContext } from '../contexts';\nimport { useClerk } from './useClerk';\nimport { useOrganization } from './useOrganization';\nimport { useUser } from './useUser';\n\n/**\n * Utility type that removes function properties from a type.\n */\ntype RemoveFunctions<T> = {\n [K in keyof T as T[K] extends (...args: any[]) => any ? never : K]: T[K];\n};\n\n/**\n * Utility type that makes all properties `null`.\n */\ntype ForceNull<T> = {\n [K in keyof T]: null;\n};\n\ntype CheckoutProperties = Omit<RemoveFunctions<CommerceCheckoutResource>, 'pathRoot' | 'status'>;\n\ntype FetchStatusAndError =\n | {\n error: ClerkAPIResponseError;\n fetchStatus: 'error';\n }\n | {\n error: null;\n fetchStatus: 'idle' | 'fetching';\n };\n\n/**\n * @internal\n * On status === 'needs_initialization', all properties are null.\n * On status === 'needs_confirmation' or 'completed', all properties are defined the same as the CommerceCheckoutResource.\n */\ntype CheckoutPropertiesPerStatus =\n | ({\n status: Extract<__experimental_CheckoutCacheState['status'], 'needs_initialization'>;\n } & ForceNull<CheckoutProperties>)\n | ({\n status: Extract<__experimental_CheckoutCacheState['status'], 'needs_confirmation' | 'completed'>;\n } & CheckoutProperties);\n\ntype __experimental_UseCheckoutReturn = {\n checkout: FetchStatusAndError &\n CheckoutPropertiesPerStatus & {\n confirm: __experimental_CheckoutInstance['confirm'];\n start: __experimental_CheckoutInstance['start'];\n clear: () => void;\n finalize: (params?: { navigate?: SetActiveNavigate }) => void;\n getState: () => __experimental_CheckoutCacheState;\n isStarting: boolean;\n isConfirming: boolean;\n };\n};\n\ntype Params = Parameters<typeof __experimental_CheckoutProvider>[0];\n\nexport const useCheckout = (options?: Params): __experimental_UseCheckoutReturn => {\n const contextOptions = useCheckoutContext();\n const { for: forOrganization, planId, planPeriod } = options || contextOptions;\n\n const clerk = useClerk();\n const { organization } = useOrganization();\n const { isLoaded, user } = useUser();\n\n if (!isLoaded) {\n throw new Error('Clerk: Ensure that `useCheckout` is inside a component wrapped with `<ClerkLoaded />`.');\n }\n\n if (!user) {\n throw new Error('Clerk: Ensure that `useCheckout` is inside a component wrapped with `<SignedIn />`.');\n }\n\n if (forOrganization === 'organization' && !organization) {\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/references/backend/types/auth-object#how-to-access-the-auth-object',\n );\n }\n\n const manager = useMemo(\n () => clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization }),\n [user.id, organization?.id, planId, planPeriod, forOrganization],\n );\n\n const managerProperties = useSyncExternalStore(\n cb => manager.subscribe(cb),\n () => manager.getState(),\n () => manager.getState(),\n );\n\n const properties = useMemo<CheckoutProperties | ForceNull<CheckoutProperties>>(() => {\n if (!managerProperties.checkout) {\n return {\n id: null,\n externalClientSecret: null,\n externalGatewayId: null,\n status: null,\n totals: null,\n isImmediatePlanChange: null,\n planPeriod: null,\n plan: null,\n paymentSource: null,\n freeTrialEndsAt: null,\n };\n }\n const {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n reload,\n confirm,\n pathRoot,\n // All the above need to be removed from the properties\n ...rest\n } = managerProperties.checkout;\n return rest;\n }, [managerProperties.checkout]);\n\n const checkout = {\n ...properties,\n getState: manager.getState,\n start: manager.start,\n confirm: manager.confirm,\n clear: manager.clear,\n finalize: manager.finalize,\n isStarting: managerProperties.isStarting,\n isConfirming: managerProperties.isConfirming,\n error: managerProperties.error,\n status: managerProperties.status,\n fetchStatus: managerProperties.fetchStatus,\n };\n\n return {\n checkout,\n } as __experimental_UseCheckoutReturn;\n};\n","/* eslint-disable @typescript-eslint/consistent-type-imports */\nimport type { CommerceCheckoutResource, EnvironmentResource, ForPayerType } from '@clerk/types';\nimport type { Stripe, StripeElements } from '@stripe/stripe-js';\nimport { type PropsWithChildren, ReactNode, useCallback, useEffect, useMemo, useState } from 'react';\nimport React from 'react';\nimport useSWR from 'swr';\nimport useSWRMutation from 'swr/mutation';\n\nimport { createContextAndHook } from './hooks/createContextAndHook';\nimport type { useCheckout } from './hooks/useCheckout';\nimport { useClerk } from './hooks/useClerk';\nimport { useOrganization } from './hooks/useOrganization';\nimport { useUser } from './hooks/useUser';\nimport { Elements, PaymentElement as StripePaymentElement, useElements, useStripe } from './stripe-react';\n\ntype LoadStripeFn = typeof import('@stripe/stripe-js').loadStripe;\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 [StripeLibsContext, useStripeLibsContext] = createContextAndHook<{\n loadStripe: LoadStripeFn;\n} | null>('StripeLibsContext');\n\nconst StripeLibsProvider = ({ children }: PropsWithChildren) => {\n const clerk = useClerk();\n const { data: stripeClerkLibs } = useSWR(\n 'clerk-stripe-sdk',\n async () => {\n const loadStripe = (await clerk.__internal_loadStripeJs()) as LoadStripeFn;\n return { loadStripe };\n },\n {\n keepPreviousData: true,\n revalidateOnFocus: false,\n dedupingInterval: Infinity,\n },\n );\n\n return (\n <StripeLibsContext.Provider\n value={{\n value: stripeClerkLibs || null,\n }}\n >\n {children}\n </StripeLibsContext.Provider>\n );\n};\n\nconst useInternalEnvironment = () => {\n const clerk = useClerk();\n // @ts-expect-error `__unstable__environment` is not typed\n return clerk.__unstable__environment as unknown as EnvironmentResource | null | undefined;\n};\n\nconst usePaymentSourceUtils = (forResource: ForPayerType = 'user') => {\n const { organization } = useOrganization();\n const { user } = useUser();\n const resource = forResource === 'organization' ? organization : user;\n const stripeClerkLibs = useStripeLibsContext();\n\n const { data: initializedPaymentSource, trigger: initializePaymentSource } = useSWRMutation(\n {\n key: 'commerce-payment-source-initialize',\n resourceId: resource?.id,\n },\n () => {\n return resource?.initializePaymentSource({\n gateway: 'stripe',\n });\n },\n );\n\n const environment = useInternalEnvironment();\n\n useEffect(() => {\n if (!resource?.id) return;\n initializePaymentSource().catch(() => {\n // ignore errors\n });\n }, [resource?.id]);\n\n const externalGatewayId = initializedPaymentSource?.externalGatewayId;\n const externalClientSecret = initializedPaymentSource?.externalClientSecret;\n const paymentMethodOrder = initializedPaymentSource?.paymentMethodOrder;\n const stripePublishableKey = environment?.commerceSettings.billing.stripePublishableKey;\n\n const { data: stripe } = useSWR(\n stripeClerkLibs && externalGatewayId && stripePublishableKey\n ? { key: 'stripe-sdk', externalGatewayId, stripePublishableKey }\n : null,\n ({ stripePublishableKey, externalGatewayId }) => {\n return stripeClerkLibs?.loadStripe(stripePublishableKey, {\n stripeAccount: externalGatewayId,\n });\n },\n {\n keepPreviousData: true,\n revalidateOnFocus: false,\n dedupingInterval: 1_000 * 60, // 1 minute\n },\n );\n\n return {\n stripe,\n initializePaymentSource,\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\ntype PaymentElementProviderProps = {\n checkout?: CommerceCheckoutResource | ReturnType<typeof useCheckout>['checkout'];\n stripeAppearance?: internalStripeAppearance;\n /**\n * Default to `user` if not provided.\n *\n * @default 'user'\n */\n for?: ForPayerType;\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 <StripeLibsProvider>\n <PropsProvider {...props}>\n <PaymentElementInternalRoot>{children}</PaymentElementInternalRoot>\n </PropsProvider>\n </StripeLibsProvider>\n );\n};\n\nconst PaymentElementInternalRoot = (props: PropsWithChildren) => {\n const { stripe, externalClientSecret, stripeAppearance } = usePaymentElementContext();\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 }}\n >\n <ValidateStripeUtils>{props.children}</ValidateStripeUtils>\n </Elements>\n );\n }\n\n return <DummyStripeUtils>{props.children}</DummyStripeUtils>;\n};\n\nconst PaymentElement = ({ fallback }: { fallback?: ReactNode }) => {\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\ntype UsePaymentElementReturn = {\n submit: () => Promise<\n | {\n data: { gateway: 'stripe'; paymentToken: string };\n error: null;\n }\n | {\n data: null;\n error: PaymentElementError;\n }\n >;\n reset: () => Promise<void>;\n isFormReady: boolean;\n} & (\n | {\n provider: {\n name: 'stripe';\n };\n isProviderReady: true;\n }\n | {\n provider: undefined;\n isProviderReady: false;\n }\n);\n\nconst usePaymentElement = (): UsePaymentElementReturn => {\n const { isPaymentElementReady, initializePaymentSource } = 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 initializePaymentSource();\n }, [stripe, elements, initializePaymentSource]);\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 PaymentElementProvider as __experimental_PaymentElementProvider,\n PaymentElement as __experimental_PaymentElement,\n usePaymentElement as __experimental_usePaymentElement,\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) return ctx;\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) return false;\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) return false;\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) return left === right;\n\n const leftKeys = Object.keys(left);\n const rightKeys = Object.keys(right);\n\n if (leftKeys.length !== rightKeys.length) return false;\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, useElements, useStripe, PaymentElement };\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,mBAAkB;AAOX,SAAS,oBAAoB,YAAqB,UAA2D;AAClH,MAAI,CAAC,YAAY;AACf,UAAM,OAAO,aAAa,WAAW,IAAI,MAAM,QAAQ,IA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IAAI,sBAAsB;AACnD,QAAM,EAAE,qBAAqB,IAAI,yBAAyB;AAE1D,QAAM,aAAS,4BAAY,YAAY;AACrC,QAAI,CAAC,UAAU,CAAC,UAAU;AACxB,aAAO,sBAAsB;AAAA,IAC/B;AAEA,UAAM,EAAE,aAAa,MAAM,IAAI,MAAM,OAAO,aAAa;AAAA,MACvD;AAAA,MACA,eAAe;AAAA,QACb,YAAY,OAAO,SAAS;AAAA,MAC9B;AAAA,MACA,UAAU;AAAA,IACZ,CAAC;AACD,QAAI,OAAO;AACT,aAAO;AAAA,QACL,MAAM;AAAA,QACN,OAAO;AAAA,UACL,SAAS;AAAA,UACT,OAAO;AAAA,YACL,MAAM,MAAM;AAAA,YACZ,SAAS,MAAM;AAAA,YACf,MAAM,MAAM;AAAA,UACd;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,MACL,MAAM,EAAE,SAAS,UAAU,cAAc,YAAY,eAAyB;AAAA,MAC9E,OAAO;AAAA,IACT;AAAA,EACF,GAAG,CAAC,QAAQ,QAAQ,CAAC;AAErB,QAAM,YAAQ,4BAAY,YAAY;AACpC,QAAI,CAAC,UAAU,CAAC,UAAU;AACxB,aAAO,sBAAsB;AAAA,IAC/B;AAEA,UAAM,wBAAwB;AAAA,EAChC,GAAG,CAAC,QAAQ,UAAU,uBAAuB,CAAC;AAE9C,QAAM,kBAAkB,QAAQ,UAAU,oBAAoB;AAE9D,MAAI,CAAC,iBAAiB;AACpB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,aAAa;AAAA,MACb,UAAU;AAAA,MACV,iBAAiB;AAAA,IACnB;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,aAAa;AAAA,IACb,UAAU;AAAA,MACR,MAAM;AAAA,IACR;AAAA,IACA;AAAA,EACF;AACF;","names":["PaymentElement","React","import_react","React","import_react","undefinedPaginatedResource","import_react","React","hookName","hookName","import_react","React","deepEqual","import_react","config","hookName","import_react","hookName","import_react","import_react","import_swr","import_react","import_react","React","ctx","isServer","useSWR","React","useSWRMutation","stripePublishableKey","externalGatewayId","PaymentElement"]}