@clerk/shared 4.0.0-canary.v20260108181859 → 4.0.0-canary.v20260108183840

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.
@@ -13,8 +13,13 @@ const require_telemetry = require('../telemetry-CXXDXYfo.js');
13
13
  const require_createDeferredPromise = require('../createDeferredPromise-CFgXzt9g.js');
14
14
  let react = require("react");
15
15
  react = require_chunk.__toESM(react);
16
- let __tanstack_query_core = require("@tanstack/query-core");
16
+ let swr = require("swr");
17
+ swr = require_chunk.__toESM(swr);
18
+ let swr_infinite = require("swr/infinite");
19
+ swr_infinite = require_chunk.__toESM(swr_infinite);
17
20
  let dequal = require("dequal");
21
+ let swr_mutation = require("swr/mutation");
22
+ swr_mutation = require_chunk.__toESM(swr_mutation);
18
23
 
19
24
  //#region src/react/hooks/createContextAndHook.ts
20
25
  /**
@@ -54,6 +59,15 @@ const createContextAndHook = (displayName, options) => {
54
59
  ];
55
60
  };
56
61
 
62
+ //#endregion
63
+ //#region src/react/providers/SWRConfigCompat.swr.tsx
64
+ /**
65
+ * @internal
66
+ */
67
+ function SWRConfigCompat({ swrConfig, children }) {
68
+ return /* @__PURE__ */ react.default.createElement(swr.SWRConfig, { value: swrConfig }, children);
69
+ }
70
+
57
71
  //#endregion
58
72
  //#region src/react/contexts.tsx
59
73
  const [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook("ClerkInstanceContext");
@@ -74,8 +88,8 @@ function useOptionsContext() {
74
88
  return context;
75
89
  }
76
90
  const [OrganizationContextInternal, useOrganizationContext] = createContextAndHook("OrganizationContext");
77
- const OrganizationProvider = ({ children, organization }) => {
78
- return /* @__PURE__ */ react.default.createElement(OrganizationContextInternal.Provider, { value: { value: { organization } } }, children);
91
+ const OrganizationProvider = ({ children, organization, swrConfig }) => {
92
+ return /* @__PURE__ */ react.default.createElement(SWRConfigCompat, { swrConfig }, /* @__PURE__ */ react.default.createElement(OrganizationContextInternal.Provider, { value: { value: { organization } } }, children));
79
93
  };
80
94
  /**
81
95
  * @internal
@@ -161,123 +175,83 @@ function createCacheKeys(params) {
161
175
  authenticated: params.authenticated
162
176
  };
163
177
  }
164
-
165
- //#endregion
166
- //#region src/react/clerk-rq/keep-previous-data.ts
167
178
  /**
168
179
  * @internal
169
180
  */
170
- function defineKeepPreviousDataFn(enabled) {
171
- if (enabled) return function KeepPreviousDataFn(previousData) {
172
- return previousData;
181
+ function toSWRQuery(keys) {
182
+ const { queryKey } = keys;
183
+ return {
184
+ type: queryKey[0],
185
+ ...queryKey[2],
186
+ ...queryKey[3].args
173
187
  };
174
188
  }
175
189
 
176
190
  //#endregion
177
- //#region src/react/clerk-rq/use-clerk-query-client.ts
178
- /**
179
- * Creates a recursively self-referential Proxy that safely handles:
180
- * - Arbitrary property access (e.g., obj.any.prop.path)
181
- * - Function calls at any level (e.g., obj.a().b.c())
182
- * - Construction (e.g., new obj.a.b())
183
- *
184
- * Always returns itself to allow infinite chaining without throwing.
185
- */
186
- function createRecursiveProxy(label) {
187
- const callableTarget = function noop$1() {};
188
- let self;
189
- self = new Proxy(callableTarget, {
190
- get(_target, prop) {
191
- if (prop === "then") return;
192
- if (prop === "toString") return () => `[${label}]`;
193
- if (prop === Symbol.toPrimitive) return () => 0;
194
- return self;
195
- },
196
- apply() {
197
- return self;
198
- },
199
- construct() {
200
- return self;
201
- },
202
- has() {
203
- return false;
204
- },
205
- set() {
206
- return false;
207
- }
208
- });
209
- return self;
210
- }
211
- const mockQueryClient = createRecursiveProxy("ClerkMockQueryClient");
212
- const useClerkQueryClient = () => {
213
- const clerk = useClerkInstanceContext();
214
- const queryClient = clerk.__internal_queryClient;
215
- const [, setQueryClientLoaded] = (0, react.useState)(typeof queryClient === "object" && "__tag" in queryClient && queryClient.__tag === "clerk-rq-client");
216
- (0, react.useEffect)(() => {
217
- const _setQueryClientLoaded = () => setQueryClientLoaded(true);
218
- clerk.on("queryClientStatus", _setQueryClientLoaded);
219
- return () => {
220
- clerk.off("queryClientStatus", _setQueryClientLoaded);
221
- };
222
- }, [clerk, setQueryClientLoaded]);
223
- const isLoaded = typeof queryClient === "object" && "__tag" in queryClient && queryClient.__tag === "clerk-rq-client";
224
- return [queryClient?.client || mockQueryClient, isLoaded];
225
- };
226
-
227
- //#endregion
228
- //#region src/react/clerk-rq/useBaseQuery.ts
229
- /**
230
- * Stripped down version of useBaseQuery from @tanstack/query-core.
231
- * This implementation allows for an observer to be created every time a query client changes.
232
- */
191
+ //#region src/react/hooks/usePagesOrInfinite.shared.ts
233
192
  /**
234
- * An alternative `useBaseQuery` implementation that allows for an observer to be created every time a query client changes.
193
+ * A hook that safely merges user-provided pagination options with default values.
194
+ * It caches initial pagination values (page and size) until component unmount to prevent unwanted rerenders.
235
195
  *
236
196
  * @internal
197
+ *
198
+ * @example
199
+ * ```typescript
200
+ * // Example 1: With user-provided options
201
+ * const userOptions = { initialPage: 2, pageSize: 20, infinite: true };
202
+ * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
203
+ * useWithSafeValues(userOptions, defaults);
204
+ * // Returns { initialPage: 2, pageSize: 20, infinite: true }
205
+ *
206
+ * // Example 2: With boolean true (use defaults)
207
+ * const params = true;
208
+ * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
209
+ * useWithSafeValues(params, defaults);
210
+ * // Returns { initialPage: 1, pageSize: 10, infinite: false }
211
+ *
212
+ * // Example 3: With undefined options (fallback to defaults)
213
+ * const params = undefined;
214
+ * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
215
+ * useWithSafeValues(params, defaults);
216
+ * // Returns { initialPage: 1, pageSize: 10, infinite: false }
217
+ * ```
237
218
  */
238
- function useBaseQuery(options, Observer) {
239
- const [client, isQueryClientLoaded] = useClerkQueryClient();
240
- const defaultedOptions = isQueryClientLoaded ? client.defaultQueryOptions(options) : options;
241
- defaultedOptions._optimisticResults = "optimistic";
242
- const observer = react.useMemo(() => {
243
- return new Observer(client, defaultedOptions);
244
- }, [client]);
245
- const result = observer.getOptimisticResult(defaultedOptions);
246
- const shouldSubscribe = options.subscribed !== false;
247
- react.useSyncExternalStore(react.useCallback((onStoreChange) => {
248
- const unsubscribe = shouldSubscribe ? observer.subscribe(__tanstack_query_core.notifyManager.batchCalls(onStoreChange)) : __tanstack_query_core.noop;
249
- observer.updateResult();
250
- return unsubscribe;
251
- }, [observer, shouldSubscribe]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
252
- react.useEffect(() => {
253
- observer.setOptions(defaultedOptions);
254
- }, [defaultedOptions, observer]);
255
- if (!isQueryClientLoaded) return {
256
- data: void 0,
257
- error: null,
258
- isLoading: false,
259
- isFetching: false,
260
- status: "pending"
219
+ const useWithSafeValues = (params, defaultValues) => {
220
+ const shouldUseDefaults = typeof params === "boolean" && params;
221
+ const initialPageRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.initialPage : params?.initialPage ?? defaultValues.initialPage);
222
+ const pageSizeRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.pageSize : params?.pageSize ?? defaultValues.pageSize);
223
+ const newObj = {};
224
+ for (const key of Object.keys(defaultValues)) newObj[key] = shouldUseDefaults ? defaultValues[key] : params?.[key] ?? defaultValues[key];
225
+ return {
226
+ ...newObj,
227
+ initialPage: initialPageRef.current,
228
+ pageSize: pageSizeRef.current
261
229
  };
262
- return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
263
- }
264
-
265
- //#endregion
266
- //#region src/react/clerk-rq/useInfiniteQuery.ts
230
+ };
267
231
  /**
232
+ * Returns an object containing only the keys from the first object that are not present in the second object.
233
+ * Useful for extracting unique parameters that should be passed to a request while excluding common cache keys.
268
234
  *
269
- */
270
- function useClerkInfiniteQuery(options) {
271
- return useBaseQuery(options, __tanstack_query_core.InfiniteQueryObserver);
272
- }
273
-
274
- //#endregion
275
- //#region src/react/clerk-rq/useQuery.ts
276
- /**
235
+ * @internal
277
236
  *
237
+ * @example
238
+ * ```typescript
239
+ * // Example 1: Basic usage
240
+ * const obj1 = { name: 'John', age: 30, city: 'NY' };
241
+ * const obj2 = { name: 'John', age: 30 };
242
+ * getDifferentKeys(obj1, obj2); // Returns { city: 'NY' }
243
+ *
244
+ * // Example 2: With cache keys
245
+ * const requestParams = { page: 1, limit: 10, userId: '123' };
246
+ * const cacheKeys = { userId: '123' };
247
+ * getDifferentKeys(requestParams, cacheKeys); // Returns { page: 1, limit: 10 }
248
+ * ```
278
249
  */
279
- function useClerkQuery(options) {
280
- return useBaseQuery(options, __tanstack_query_core.QueryObserver);
250
+ function getDifferentKeys(obj1, obj2) {
251
+ const keysSet = new Set(Object.keys(obj2));
252
+ const differentKeysObject = {};
253
+ for (const key1 of Object.keys(obj1)) if (!keysSet.has(key1)) differentKeysObject[key1] = obj1[key1];
254
+ return differentKeysObject;
281
255
  }
282
256
 
283
257
  //#endregion
@@ -308,249 +282,114 @@ function usePreviousValue(value) {
308
282
  }
309
283
 
310
284
  //#endregion
311
- //#region src/react/hooks/useClearQueriesOnSignOut.ts
312
- const withInfiniteKey = (key) => [key, `${key}-inf`];
313
- /**
314
- * Clears React Query caches associated with the given stable prefixes when
315
- * the authenticated state transitions from signed-in to signed-out.
316
- *
317
- * @internal
318
- */
319
- function useClearQueriesOnSignOut(options) {
320
- const { isSignedOut, stableKeys, authenticated = true, onCleanup } = options;
321
- const stableKeysRef = (0, react.useRef)(stableKeys);
322
- const [queryClient] = useClerkQueryClient();
323
- const previousIsSignedIn = usePreviousValue(!isSignedOut);
324
- if (authenticated !== true) return;
325
- (0, react.useEffect)(() => {
326
- if (previousIsSignedIn && isSignedOut === true) {
327
- queryClient.removeQueries({ predicate: (query) => {
328
- const [cachedStableKey, queryAuthenticated] = query.queryKey;
329
- return queryAuthenticated === true && typeof cachedStableKey === "string" && (Array.isArray(stableKeysRef.current) ? stableKeysRef.current.includes(cachedStableKey) : stableKeysRef.current === cachedStableKey);
330
- } });
331
- onCleanup?.();
332
- }
333
- }, [
334
- isSignedOut,
335
- previousIsSignedIn,
336
- queryClient
337
- ]);
338
- }
339
-
340
- //#endregion
341
- //#region src/react/hooks/usePagesOrInfinite.shared.ts
285
+ //#region src/react/hooks/usePagesOrInfinite.swr.tsx
286
+ const cachingSWROptions = {
287
+ dedupingInterval: 1e3 * 60,
288
+ focusThrottleInterval: 1e3 * 60 * 2
289
+ };
290
+ const cachingSWRInfiniteOptions = {
291
+ ...cachingSWROptions,
292
+ revalidateFirstPage: false
293
+ };
342
294
  /**
343
- * A hook that safely merges user-provided pagination options with default values.
344
- * It caches initial pagination values (page and size) until component unmount to prevent unwanted rerenders.
295
+ * A flexible pagination hook that supports both traditional pagination and infinite loading.
296
+ * It provides a unified API for handling paginated data fetching, with built-in caching through SWR.
297
+ * The hook can operate in two modes:
298
+ * - Traditional pagination: Fetches one page at a time with page navigation
299
+ * - Infinite loading: Accumulates data as more pages are loaded.
300
+ *
301
+ * Features:
302
+ * - Cache management with SWR
303
+ * - Loading and error states
304
+ * - Page navigation helpers
305
+ * - Data revalidation and updates
306
+ * - Support for keeping previous data while loading.
345
307
  *
346
308
  * @internal
347
- *
348
- * @example
349
- * ```typescript
350
- * // Example 1: With user-provided options
351
- * const userOptions = { initialPage: 2, pageSize: 20, infinite: true };
352
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
353
- * useWithSafeValues(userOptions, defaults);
354
- * // Returns { initialPage: 2, pageSize: 20, infinite: true }
355
- *
356
- * // Example 2: With boolean true (use defaults)
357
- * const params = true;
358
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
359
- * useWithSafeValues(params, defaults);
360
- * // Returns { initialPage: 1, pageSize: 10, infinite: false }
361
- *
362
- * // Example 3: With undefined options (fallback to defaults)
363
- * const params = undefined;
364
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
365
- * useWithSafeValues(params, defaults);
366
- * // Returns { initialPage: 1, pageSize: 10, infinite: false }
367
- * ```
368
309
  */
369
- const useWithSafeValues = (params, defaultValues) => {
370
- const shouldUseDefaults = typeof params === "boolean" && params;
371
- const initialPageRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.initialPage : params?.initialPage ?? defaultValues.initialPage);
372
- const pageSizeRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.pageSize : params?.pageSize ?? defaultValues.pageSize);
373
- const newObj = {};
374
- for (const key of Object.keys(defaultValues)) newObj[key] = shouldUseDefaults ? defaultValues[key] : params?.[key] ?? defaultValues[key];
375
- return {
376
- ...newObj,
377
- initialPage: initialPageRef.current,
378
- pageSize: pageSizeRef.current
379
- };
380
- };
381
-
382
- //#endregion
383
- //#region src/react/hooks/usePagesOrInfinite.tsx
384
310
  const usePagesOrInfinite = (params) => {
385
311
  const { fetcher, config, keys } = params;
386
312
  const [paginatedPage, setPaginatedPage] = (0, react.useState)(config.initialPage ?? 1);
387
313
  const initialPageRef = (0, react.useRef)(config.initialPage ?? 1);
388
314
  const pageSizeRef = (0, react.useRef)(config.pageSize ?? 10);
389
315
  const enabled = config.enabled ?? true;
390
- const isSignedIn = config.isSignedIn;
391
- const triggerInfinite = config.infinite ?? false;
392
316
  const cacheMode = config.__experimental_mode === "cache";
317
+ const triggerInfinite = config.infinite ?? false;
393
318
  const keepPreviousData = config.keepPreviousData ?? false;
394
- const [queryClient] = useClerkQueryClient();
395
- const queriesEnabled = enabled && Boolean(fetcher) && !cacheMode && isSignedIn !== false;
396
- const [forceUpdateCounter, setForceUpdateCounter] = (0, react.useState)(0);
397
- const forceUpdate = (0, react.useCallback)((updater) => {
398
- setForceUpdateCounter(updater);
399
- }, []);
400
- const pagesQueryKey = (0, react.useMemo)(() => {
401
- const [stablePrefix, authenticated, tracked, untracked] = keys.queryKey;
402
- return [
403
- stablePrefix,
404
- authenticated,
405
- tracked,
406
- {
407
- ...untracked,
408
- args: {
409
- ...untracked.args,
410
- initialPage: paginatedPage,
411
- pageSize: pageSizeRef.current
412
- }
413
- }
414
- ];
415
- }, [keys.queryKey, paginatedPage]);
416
- const singlePageQuery = useClerkQuery({
417
- queryKey: pagesQueryKey,
418
- queryFn: ({ queryKey }) => {
419
- const { args } = queryKey[3];
420
- if (!fetcher) return;
421
- return fetcher(args);
422
- },
423
- staleTime: 6e4,
424
- enabled: queriesEnabled && !triggerInfinite,
425
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
426
- });
427
- const infiniteQueryKey = (0, react.useMemo)(() => {
428
- const [stablePrefix, authenticated, tracked, untracked] = keys.queryKey;
429
- return [
430
- stablePrefix + "-inf",
431
- authenticated,
432
- tracked,
433
- untracked
434
- ];
435
- }, [keys.queryKey]);
436
- const infiniteQuery = useClerkInfiniteQuery({
437
- queryKey: infiniteQueryKey,
438
- initialPageParam: config.initialPage ?? 1,
439
- getNextPageParam: (lastPage, allPages, lastPageParam) => {
440
- const total = lastPage?.total_count ?? 0;
441
- return (allPages.length + (config.initialPage ? config.initialPage - 1 : 0)) * (config.pageSize ?? 10) < total ? lastPageParam + 1 : void 0;
442
- },
443
- queryFn: ({ pageParam, queryKey }) => {
444
- const { args } = queryKey[3];
445
- if (!fetcher) return;
446
- return fetcher({
447
- ...args,
448
- initialPage: pageParam,
449
- pageSize: pageSizeRef.current
450
- });
451
- },
452
- staleTime: 6e4,
453
- enabled: queriesEnabled && triggerInfinite
454
- });
455
- useClearQueriesOnSignOut({
456
- isSignedOut: isSignedIn === false,
457
- authenticated: keys.authenticated,
458
- stableKeys: withInfiniteKey(keys.stableKey),
459
- onCleanup: () => {
460
- setPaginatedPage(initialPageRef.current);
461
- Promise.resolve().then(() => forceUpdate((n) => n + 1));
462
- }
319
+ const isSignedIn = config.isSignedIn;
320
+ const pagesCacheKey = {
321
+ ...toSWRQuery(keys),
322
+ initialPage: paginatedPage,
323
+ pageSize: pageSizeRef.current
324
+ };
325
+ const previousIsSignedIn = usePreviousValue(isSignedIn);
326
+ const shouldFetch = !triggerInfinite && enabled && (!cacheMode ? !!fetcher : true);
327
+ const { data: swrData, isValidating: swrIsValidating, isLoading: swrIsLoading, error: swrError, mutate: swrMutate } = (0, swr.default)(typeof isSignedIn === "boolean" ? previousIsSignedIn === true && isSignedIn === false ? pagesCacheKey : isSignedIn ? shouldFetch ? pagesCacheKey : null : null : shouldFetch ? pagesCacheKey : null, !cacheMode && !!fetcher ? (cacheKeyParams) => {
328
+ if (isSignedIn === false || shouldFetch === false) return null;
329
+ return fetcher(getDifferentKeys(cacheKeyParams, {
330
+ type: keys.queryKey[0],
331
+ ...keys.queryKey[2]
332
+ }));
333
+ } : null, {
334
+ keepPreviousData,
335
+ ...cachingSWROptions
463
336
  });
464
- const { data, count, page } = (0, react.useMemo)(() => {
465
- if (triggerInfinite) {
466
- const cachedData = queryClient.getQueryData(infiniteQueryKey);
467
- const pages = queriesEnabled ? infiniteQuery.data?.pages ?? cachedData?.pages ?? [] : cachedData?.pages ?? [];
468
- const validPages = Array.isArray(pages) ? pages.filter(Boolean) : [];
469
- return {
470
- data: validPages.map((a) => a?.data).flat().filter(Boolean) ?? [],
471
- count: validPages[validPages.length - 1]?.total_count ?? 0,
472
- page: validPages.length > 0 ? validPages.length : initialPageRef.current
473
- };
474
- }
475
- const pageData = queriesEnabled ? singlePageQuery.data ?? queryClient.getQueryData(pagesQueryKey) : queryClient.getQueryData(pagesQueryKey);
337
+ const { data: swrInfiniteData, isLoading: swrInfiniteIsLoading, isValidating: swrInfiniteIsValidating, error: swrInfiniteError, size, setSize, mutate: swrInfiniteMutate } = (0, swr_infinite.default)((pageIndex) => {
338
+ if (!triggerInfinite || !enabled || isSignedIn === false) return null;
476
339
  return {
477
- data: Array.isArray(pageData?.data) ? pageData.data : [],
478
- count: typeof pageData?.total_count === "number" ? pageData.total_count : 0,
479
- page: paginatedPage
340
+ ...toSWRQuery(keys),
341
+ initialPage: initialPageRef.current + pageIndex,
342
+ pageSize: pageSizeRef.current
480
343
  };
344
+ }, (cacheKeyParams) => {
345
+ const requestParams = getDifferentKeys(cacheKeyParams, {
346
+ type: keys.queryKey[0],
347
+ ...keys.queryKey[2]
348
+ });
349
+ return fetcher?.(requestParams);
350
+ }, cachingSWRInfiniteOptions);
351
+ const page = (0, react.useMemo)(() => {
352
+ if (triggerInfinite) return size;
353
+ return paginatedPage;
481
354
  }, [
482
- queriesEnabled,
483
- forceUpdateCounter,
484
355
  triggerInfinite,
485
- infiniteQuery.data?.pages,
486
- singlePageQuery.data,
487
- queryClient,
488
- infiniteQueryKey,
489
- pagesQueryKey,
356
+ size,
490
357
  paginatedPage
491
358
  ]);
492
359
  const fetchPage = (0, react.useCallback)((numberOrgFn) => {
493
360
  if (triggerInfinite) {
494
- const next = typeof numberOrgFn === "function" ? numberOrgFn(page) : numberOrgFn;
495
- const targetCount = Math.max(0, next);
496
- const cachedData = queryClient.getQueryData(infiniteQueryKey);
497
- if (targetCount - (infiniteQuery.data?.pages ?? cachedData?.pages ?? []).length > 0) infiniteQuery.fetchNextPage({ cancelRefetch: false });
361
+ setSize(numberOrgFn);
498
362
  return;
499
363
  }
500
364
  return setPaginatedPage(numberOrgFn);
365
+ }, [setSize, triggerInfinite]);
366
+ const data = (0, react.useMemo)(() => {
367
+ if (triggerInfinite) return swrInfiniteData?.map((a) => a?.data).flat() ?? [];
368
+ return swrData?.data ?? [];
369
+ }, [
370
+ triggerInfinite,
371
+ swrData,
372
+ swrInfiniteData
373
+ ]);
374
+ const count = (0, react.useMemo)(() => {
375
+ if (triggerInfinite) return swrInfiniteData?.[swrInfiniteData?.length - 1]?.total_count || 0;
376
+ return swrData?.total_count ?? 0;
501
377
  }, [
502
- infiniteQuery,
503
- page,
504
378
  triggerInfinite,
505
- queryClient,
506
- infiniteQueryKey
379
+ swrData,
380
+ swrInfiniteData
507
381
  ]);
508
- const isLoading = triggerInfinite ? infiniteQuery.isLoading : singlePageQuery.isLoading;
509
- const isFetching = triggerInfinite ? infiniteQuery.isFetching : singlePageQuery.isFetching;
510
- const error = (triggerInfinite ? infiniteQuery.error : singlePageQuery.error) ?? null;
382
+ const isLoading = triggerInfinite ? swrInfiniteIsLoading : swrIsLoading;
383
+ const isFetching = triggerInfinite ? swrInfiniteIsValidating : swrIsValidating;
384
+ const error = (triggerInfinite ? swrInfiniteError : swrError) ?? null;
511
385
  const isError = !!error;
512
386
  const fetchNext = (0, react.useCallback)(() => {
513
- if (triggerInfinite) {
514
- infiniteQuery.fetchNextPage({ cancelRefetch: false });
515
- return;
516
- }
517
- setPaginatedPage((n) => Math.max(0, n + 1));
518
- }, [infiniteQuery, triggerInfinite]);
387
+ fetchPage((n) => Math.max(0, n + 1));
388
+ }, [fetchPage]);
519
389
  const fetchPrevious = (0, react.useCallback)(() => {
520
- if (triggerInfinite) return;
521
- setPaginatedPage((n) => Math.max(0, n - 1));
522
- }, [triggerInfinite]);
390
+ fetchPage((n) => Math.max(0, n - 1));
391
+ }, [fetchPage]);
523
392
  const offsetCount = (initialPageRef.current - 1) * pageSizeRef.current;
524
- const pageCount = Math.ceil((count - offsetCount) / pageSizeRef.current);
525
- const hasNextPage = triggerInfinite ? Boolean(infiniteQuery.hasNextPage) : count - offsetCount * pageSizeRef.current > page * pageSizeRef.current;
526
- const hasPreviousPage = triggerInfinite ? Boolean(infiniteQuery.hasPreviousPage) : (page - 1) * pageSizeRef.current > offsetCount * pageSizeRef.current;
527
- const setData = (value) => {
528
- if (triggerInfinite) {
529
- queryClient.setQueryData(infiniteQueryKey, (prevValue = {}) => {
530
- const prevPages = Array.isArray(prevValue?.pages) ? prevValue.pages : [];
531
- const nextPages = typeof value === "function" ? value(prevPages) : value;
532
- return {
533
- ...prevValue,
534
- pages: nextPages
535
- };
536
- });
537
- forceUpdate((n) => n + 1);
538
- return Promise.resolve();
539
- }
540
- queryClient.setQueryData(pagesQueryKey, (prevValue = {
541
- data: [],
542
- total_count: 0
543
- }) => {
544
- return typeof value === "function" ? value(prevValue) : value;
545
- });
546
- forceUpdate((n) => n + 1);
547
- return Promise.resolve();
548
- };
549
- const revalidate = async () => {
550
- await queryClient.invalidateQueries({ queryKey: keys.invalidationKey });
551
- const [stablePrefix, ...rest] = keys.invalidationKey;
552
- return queryClient.invalidateQueries({ queryKey: [stablePrefix + "-inf", ...rest] });
553
- };
554
393
  return {
555
394
  data,
556
395
  count,
@@ -559,19 +398,19 @@ const usePagesOrInfinite = (params) => {
559
398
  isFetching,
560
399
  isError,
561
400
  page,
562
- pageCount,
401
+ pageCount: Math.ceil((count - offsetCount) / pageSizeRef.current),
563
402
  fetchPage,
564
403
  fetchNext,
565
404
  fetchPrevious,
566
- hasNextPage,
567
- hasPreviousPage,
568
- revalidate,
569
- setData
405
+ hasNextPage: count - offsetCount * pageSizeRef.current > page * pageSizeRef.current,
406
+ hasPreviousPage: (page - 1) * pageSizeRef.current > offsetCount * pageSizeRef.current,
407
+ revalidate: triggerInfinite ? () => swrInfiniteMutate() : () => swrMutate(),
408
+ setData: triggerInfinite ? (value) => swrInfiniteMutate(value, { revalidate: false }) : (value) => swrMutate(value, { revalidate: false })
570
409
  };
571
410
  };
572
411
 
573
412
  //#endregion
574
- //#region src/react/hooks/useAPIKeys.tsx
413
+ //#region src/react/hooks/useAPIKeys.swr.tsx
575
414
  /**
576
415
  * @internal
577
416
  *
@@ -632,7 +471,7 @@ function useAPIKeys(params) {
632
471
  ...safeValues.query ? { query: safeValues.query } : {}
633
472
  };
634
473
  const isEnabled = (safeValues.enabled ?? true) && clerk.loaded;
635
- return usePagesOrInfinite({
474
+ const result = usePagesOrInfinite({
636
475
  fetcher: clerk.apiKeys?.getAll ? (params$1) => clerk.apiKeys.getAll({
637
476
  ...params$1,
638
477
  subject: safeValues.subject
@@ -652,6 +491,17 @@ function useAPIKeys(params) {
652
491
  untracked: { args: hookParams }
653
492
  })
654
493
  });
494
+ const { mutate } = (0, swr.useSWRConfig)();
495
+ const invalidateAll = (0, react.useCallback)(() => {
496
+ return mutate((key) => {
497
+ if (!key || typeof key !== "object") return false;
498
+ return "type" in key && key.type === "apiKeys" && "subject" in key && key.subject === safeValues.subject;
499
+ });
500
+ }, [mutate, safeValues.subject]);
501
+ return {
502
+ ...result,
503
+ revalidate: invalidateAll
504
+ };
655
505
  }
656
506
 
657
507
  //#endregion
@@ -1292,7 +1142,7 @@ const useSafeLayoutEffect = typeof window !== "undefined" ? react.default.useLay
1292
1142
 
1293
1143
  //#endregion
1294
1144
  //#region src/react/hooks/useSession.ts
1295
- const hookName$2 = `useSession`;
1145
+ const hookName$3 = `useSession`;
1296
1146
  /**
1297
1147
  * The `useSession()` hook provides access to the current user's [`Session`](https://clerk.com/docs/reference/javascript/session) object, as well as helpers for setting the active session.
1298
1148
  *
@@ -1342,10 +1192,10 @@ const hookName$2 = `useSession`;
1342
1192
  * </Tabs>
1343
1193
  */
1344
1194
  const useSession = () => {
1345
- useAssertWrappedByClerkProvider(hookName$2);
1195
+ useAssertWrappedByClerkProvider(hookName$3);
1346
1196
  const session = useSessionContext();
1347
1197
  const clerk = useClerkInstanceContext();
1348
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName$2));
1198
+ clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName$3));
1349
1199
  if (session === void 0) return {
1350
1200
  isLoaded: false,
1351
1201
  isSignedIn: void 0,
@@ -1365,7 +1215,7 @@ const useSession = () => {
1365
1215
 
1366
1216
  //#endregion
1367
1217
  //#region src/react/hooks/useSessionList.ts
1368
- const hookName$1 = "useSessionList";
1218
+ const hookName$2 = "useSessionList";
1369
1219
  /**
1370
1220
  * The `useSessionList()` hook returns an array of [`Session`](https://clerk.com/docs/reference/javascript/session) objects that have been registered on the client device.
1371
1221
  *
@@ -1410,10 +1260,10 @@ const hookName$1 = "useSessionList";
1410
1260
  * </Tabs>
1411
1261
  */
1412
1262
  const useSessionList = () => {
1413
- useAssertWrappedByClerkProvider(hookName$1);
1263
+ useAssertWrappedByClerkProvider(hookName$2);
1414
1264
  const isomorphicClerk = useClerkInstanceContext();
1415
1265
  const client = useClientContext();
1416
- useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName$1));
1266
+ useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName$2));
1417
1267
  if (!client) return {
1418
1268
  isLoaded: false,
1419
1269
  sessions: void 0,
@@ -1428,7 +1278,7 @@ const useSessionList = () => {
1428
1278
 
1429
1279
  //#endregion
1430
1280
  //#region src/react/hooks/useUser.ts
1431
- const hookName = "useUser";
1281
+ const hookName$1 = "useUser";
1432
1282
  /**
1433
1283
  * The `useUser()` hook provides access to the current user's [`User`](https://clerk.com/docs/reference/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.
1434
1284
  *
@@ -1560,9 +1410,9 @@ const hookName = "useUser";
1560
1410
  * </Tabs>
1561
1411
  */
1562
1412
  function useUser() {
1563
- useAssertWrappedByClerkProvider(hookName);
1413
+ useAssertWrappedByClerkProvider(hookName$1);
1564
1414
  const user = useUserContext();
1565
- useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName));
1415
+ useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName$1));
1566
1416
  if (user === void 0) return {
1567
1417
  isLoaded: false,
1568
1418
  isSignedIn: void 0,
@@ -1765,11 +1615,11 @@ function useBillingHookEnabled(params) {
1765
1615
  *
1766
1616
  * @internal
1767
1617
  */
1768
- function createBillingPaginatedHook({ hookName: hookName$3, resourceType, useFetcher, options }) {
1618
+ function createBillingPaginatedHook({ hookName: hookName$4, resourceType, useFetcher, options }) {
1769
1619
  return function useBillingHook(params) {
1770
1620
  const { for: _for, enabled: externalEnabled,...paginationParams } = params || {};
1771
1621
  const safeFor = _for || "user";
1772
- useAssertWrappedByClerkProvider(hookName$3);
1622
+ useAssertWrappedByClerkProvider(hookName$4);
1773
1623
  const fetchFn = useFetcher(safeFor);
1774
1624
  const safeValues = useWithSafeValues(paginationParams, {
1775
1625
  initialPage: 1,
@@ -1781,7 +1631,7 @@ function createBillingPaginatedHook({ hookName: hookName$3, resourceType, useFet
1781
1631
  const clerk = useClerkInstanceContext();
1782
1632
  const user = useUserContext();
1783
1633
  const { organization } = useOrganizationContext();
1784
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName$3));
1634
+ clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName$4));
1785
1635
  const isForOrganization = safeFor === "organization";
1786
1636
  const billingEnabled = useBillingHookEnabled({
1787
1637
  for: safeFor,
@@ -1810,7 +1660,7 @@ function createBillingPaginatedHook({ hookName: hookName$3, resourceType, useFet
1810
1660
  authenticated: !options?.unauthenticated,
1811
1661
  tracked: options?.unauthenticated ? { for: safeFor } : {
1812
1662
  userId: user?.id,
1813
- ...isForOrganization ? { orgId: organization?.id } : {}
1663
+ ...isForOrganization ? { ["_orgId"]: organization?.id } : {}
1814
1664
  },
1815
1665
  untracked: { args: hookParams }
1816
1666
  })
@@ -1904,53 +1754,44 @@ function useSubscriptionCacheKeys(params) {
1904
1754
  }
1905
1755
 
1906
1756
  //#endregion
1907
- //#region src/react/hooks/useSubscription.tsx
1908
- const HOOK_NAME = "useSubscription";
1757
+ //#region src/react/hooks/useSubscription.swr.tsx
1758
+ const hookName = "useSubscription";
1909
1759
  /**
1760
+ * This is the existing implementation of useSubscription using SWR.
1761
+ * It is kept here for backwards compatibility until our next major version.
1762
+ *
1910
1763
  * @internal
1911
1764
  */
1912
1765
  function useSubscription(params) {
1913
- useAssertWrappedByClerkProvider(HOOK_NAME);
1766
+ useAssertWrappedByClerkProvider(hookName);
1914
1767
  const clerk = useClerkInstanceContext();
1915
1768
  const user = useUserContext();
1916
1769
  const { organization } = useOrganizationContext();
1917
- const billingEnabled = useBillingHookEnabled(params);
1918
- const recordedRef = (0, react.useRef)(false);
1919
- (0, react.useEffect)(() => {
1920
- if (!recordedRef.current && clerk?.telemetry) {
1921
- clerk.telemetry.record(require_telemetry.eventMethodCalled(HOOK_NAME));
1922
- recordedRef.current = true;
1923
- }
1924
- }, [clerk]);
1925
- const keepPreviousData = params?.keepPreviousData ?? false;
1926
- const [queryClient] = useClerkQueryClient();
1927
- const { queryKey, invalidationKey, stableKey, authenticated } = useSubscriptionCacheKeys({
1770
+ const environment = clerk.__internal_environment;
1771
+ clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName));
1772
+ const billingEnabled = params?.for === "organization" ? environment?.commerceSettings.billing.organization.enabled : environment?.commerceSettings.billing.user.enabled;
1773
+ const isEnabled = (params?.enabled ?? true) && billingEnabled;
1774
+ const { queryKey } = useSubscriptionCacheKeys({
1928
1775
  userId: user?.id,
1929
1776
  orgId: organization?.id,
1930
1777
  for: params?.for
1931
1778
  });
1932
- const queriesEnabled = Boolean(user?.id && billingEnabled);
1933
- useClearQueriesOnSignOut({
1934
- isSignedOut: user === null,
1935
- authenticated,
1936
- stableKeys: stableKey
1937
- });
1938
- const query = useClerkQuery({
1939
- queryKey,
1940
- queryFn: ({ queryKey: queryKey$1 }) => {
1941
- const obj = queryKey$1[3];
1942
- return clerk.billing.getSubscription(obj.args);
1943
- },
1944
- staleTime: 1e3 * 60,
1945
- enabled: queriesEnabled,
1946
- placeholderData: defineKeepPreviousDataFn(keepPreviousData && queriesEnabled)
1779
+ const swr$1 = (0, swr.default)(isEnabled ? { queryKey } : null, ({ queryKey: queryKey$1 }) => {
1780
+ const args = queryKey$1[3].args;
1781
+ if (queryKey$1[2].userId) return clerk.billing.getSubscription(args);
1782
+ return null;
1783
+ }, {
1784
+ dedupingInterval: 1e3 * 60,
1785
+ keepPreviousData: params?.keepPreviousData
1947
1786
  });
1948
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: invalidationKey }), [queryClient, invalidationKey]);
1787
+ const revalidate = (0, react.useCallback)(() => {
1788
+ swr$1.mutate();
1789
+ }, [swr$1]);
1949
1790
  return {
1950
- data: query.data,
1951
- error: query.error ?? void 0,
1952
- isLoading: query.isLoading,
1953
- isFetching: query.isFetching,
1791
+ data: swr$1.data,
1792
+ error: swr$1.error,
1793
+ isLoading: swr$1.isLoading,
1794
+ isFetching: swr$1.isValidating,
1954
1795
  revalidate
1955
1796
  };
1956
1797
  }
@@ -2030,47 +1871,40 @@ function useStatementQueryCacheKeys(params) {
2030
1871
  }
2031
1872
 
2032
1873
  //#endregion
2033
- //#region src/react/hooks/useStatementQuery.tsx
1874
+ //#region src/react/hooks/useStatementQuery.swr.tsx
2034
1875
  /**
1876
+ * This is the existing implementation of useStatementQuery using SWR.
1877
+ * It is kept here for backwards compatibility until our next major version.
1878
+ *
2035
1879
  * @internal
2036
1880
  */
2037
- function useStatementQuery(params = {}) {
2038
- const { statementId = null, keepPreviousData = false, for: forType = "user" } = params;
1881
+ function __internal_useStatementQuery(params = {}) {
1882
+ const { statementId = null, enabled = true, keepPreviousData = false, for: forType = "user" } = params;
2039
1883
  const clerk = useClerkInstanceContext();
2040
1884
  const user = useUserContext();
2041
1885
  const { organization } = useOrganizationContext();
2042
1886
  const organizationId = forType === "organization" ? organization?.id ?? null : null;
2043
- const { queryKey, stableKey, authenticated } = useStatementQueryCacheKeys({
1887
+ const { queryKey } = useStatementQueryCacheKeys({
2044
1888
  statementId,
2045
1889
  userId: user?.id ?? null,
2046
1890
  orgId: organizationId,
2047
1891
  for: forType
2048
1892
  });
2049
- const billingEnabled = useBillingHookEnabled(params);
2050
- const queryEnabled = Boolean(statementId) && billingEnabled;
2051
- useClearQueriesOnSignOut({
2052
- isSignedOut: user === null,
2053
- authenticated,
2054
- stableKeys: stableKey
2055
- });
2056
- const query = useClerkQuery({
2057
- queryKey,
2058
- queryFn: () => {
2059
- if (!statementId) throw new Error("statementId is required to fetch a statement");
2060
- return clerk.billing.getStatement({
2061
- id: statementId,
2062
- orgId: organizationId ?? void 0
2063
- });
2064
- },
2065
- enabled: queryEnabled,
2066
- placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2067
- staleTime: 1e3 * 60
1893
+ const swr$1 = (0, swr.default)(Boolean(statementId) && enabled && (forType !== "organization" || Boolean(organizationId)) ? queryKey : null, () => {
1894
+ if (!statementId) throw new Error("statementId is required to fetch a statement");
1895
+ return clerk.billing.getStatement({
1896
+ id: statementId,
1897
+ orgId: organizationId ?? void 0
1898
+ });
1899
+ }, {
1900
+ dedupingInterval: 1e3 * 60,
1901
+ keepPreviousData
2068
1902
  });
2069
1903
  return {
2070
- data: query.data,
2071
- error: query.error ?? null,
2072
- isLoading: query.isLoading,
2073
- isFetching: query.isFetching
1904
+ data: swr$1.data,
1905
+ error: swr$1.error ?? null,
1906
+ isLoading: swr$1.isLoading,
1907
+ isFetching: swr$1.isValidating
2074
1908
  };
2075
1909
  }
2076
1910
 
@@ -2089,32 +1923,31 @@ function usePlanDetailsQueryCacheKeys(params) {
2089
1923
  }
2090
1924
 
2091
1925
  //#endregion
2092
- //#region src/react/hooks/usePlanDetailsQuery.tsx
1926
+ //#region src/react/hooks/usePlanDetailsQuery.swr.tsx
2093
1927
  /**
1928
+ * This is the existing implementation of usePlanDetailsQuery using SWR.
1929
+ * It is kept here for backwards compatibility until our next major version.
1930
+ *
2094
1931
  * @internal
2095
1932
  */
2096
- function __internal_usePlanDetailsQuery(params = {}) {
2097
- const { planId, initialPlan = null, keepPreviousData = true } = params;
1933
+ function usePlanDetailsQuery(params = {}) {
1934
+ const { planId, initialPlan = null, enabled = true, keepPreviousData = true } = params;
2098
1935
  const clerk = useClerkInstanceContext();
2099
1936
  const targetPlanId = planId ?? initialPlan?.id ?? null;
2100
1937
  const { queryKey } = usePlanDetailsQueryCacheKeys({ planId: targetPlanId });
2101
- const billingEnabled = useBillingHookEnabled({ authenticated: false });
2102
- const query = useClerkQuery({
2103
- queryKey,
2104
- queryFn: () => {
2105
- if (!targetPlanId) throw new Error("planId is required to fetch plan details");
2106
- return clerk.billing.getPlan({ id: targetPlanId });
2107
- },
2108
- enabled: Boolean(targetPlanId) && billingEnabled,
2109
- initialData: initialPlan ?? void 0,
2110
- placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2111
- initialDataUpdatedAt: 0
1938
+ const swr$1 = (0, swr.default)(Boolean(targetPlanId) && enabled ? queryKey : null, () => {
1939
+ if (!targetPlanId) throw new Error("planId is required to fetch plan details");
1940
+ return clerk.billing.getPlan({ id: targetPlanId });
1941
+ }, {
1942
+ dedupingInterval: 1e3 * 60,
1943
+ keepPreviousData,
1944
+ fallbackData: initialPlan ?? void 0
2112
1945
  });
2113
1946
  return {
2114
- data: query.data,
2115
- error: query.error ?? null,
2116
- isLoading: query.isLoading,
2117
- isFetching: query.isFetching
1947
+ data: swr$1.data,
1948
+ error: swr$1.error ?? null,
1949
+ isLoading: swr$1.isLoading,
1950
+ isFetching: swr$1.isValidating
2118
1951
  };
2119
1952
  }
2120
1953
 
@@ -2146,44 +1979,37 @@ function usePaymentAttemptQueryCacheKeys(params) {
2146
1979
  }
2147
1980
 
2148
1981
  //#endregion
2149
- //#region src/react/hooks/usePaymentAttemptQuery.tsx
1982
+ //#region src/react/hooks/usePaymentAttemptQuery.swr.tsx
2150
1983
  /**
1984
+ * This is the existing implementation of usePaymentAttemptQuery using SWR.
1985
+ * It is kept here for backwards compatibility until our next major version.
1986
+ *
2151
1987
  * @internal
2152
1988
  */
2153
- function usePaymentAttemptQuery(params) {
2154
- const { paymentAttemptId, keepPreviousData = false, for: forType = "user" } = params;
1989
+ function __internal_usePaymentAttemptQuery(params) {
1990
+ const { paymentAttemptId, enabled = true, keepPreviousData = false, for: forType = "user" } = params;
2155
1991
  const clerk = useClerkInstanceContext();
2156
1992
  const user = useUserContext();
2157
1993
  const { organization } = useOrganizationContext();
2158
1994
  const organizationId = forType === "organization" ? organization?.id ?? null : null;
2159
- const { queryKey, stableKey, authenticated } = usePaymentAttemptQueryCacheKeys({
1995
+ const { queryKey } = usePaymentAttemptQueryCacheKeys({
2160
1996
  paymentAttemptId,
2161
1997
  userId: user?.id ?? null,
2162
1998
  orgId: organizationId,
2163
1999
  for: forType
2164
2000
  });
2165
- const billingEnabled = useBillingHookEnabled(params);
2166
- const queryEnabled = Boolean(paymentAttemptId) && billingEnabled;
2167
- useClearQueriesOnSignOut({
2168
- isSignedOut: user === null,
2169
- authenticated,
2170
- stableKeys: stableKey
2171
- });
2172
- const query = useClerkQuery({
2173
- queryKey,
2174
- queryFn: ({ queryKey: queryKey$1 }) => {
2175
- const args = queryKey$1[3].args;
2176
- return clerk.billing.getPaymentAttempt(args);
2177
- },
2178
- enabled: queryEnabled,
2179
- placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2180
- staleTime: 1e3 * 60
2001
+ const swr$1 = (0, swr.default)(Boolean(paymentAttemptId) && enabled && (forType !== "organization" || Boolean(organizationId)) ? { queryKey } : null, ({ queryKey: queryKey$1 }) => {
2002
+ const args = queryKey$1[3].args;
2003
+ return clerk.billing.getPaymentAttempt(args);
2004
+ }, {
2005
+ dedupingInterval: 1e3 * 60,
2006
+ keepPreviousData
2181
2007
  });
2182
2008
  return {
2183
- data: query.data,
2184
- error: query.error ?? null,
2185
- isLoading: query.isLoading,
2186
- isFetching: query.isFetching
2009
+ data: swr$1.data,
2010
+ error: swr$1.error ?? null,
2011
+ isLoading: swr$1.isLoading,
2012
+ isFetching: swr$1.isValidating
2187
2013
  };
2188
2014
  }
2189
2015
 
@@ -2437,90 +2263,74 @@ const createElementComponent = (type, isServer) => {
2437
2263
  const PaymentElement$1 = createElementComponent("payment", typeof window === "undefined");
2438
2264
 
2439
2265
  //#endregion
2440
- //#region src/react/billing/useInitializePaymentMethod.tsx
2266
+ //#region src/react/billing/useInitializePaymentMethod.swr.tsx
2441
2267
  /**
2268
+ * This is the existing implementation of the payment method initializer using SWR.
2269
+ * It is kept here for backwards compatibility until our next major version.
2270
+ *
2442
2271
  * @internal
2443
2272
  */
2444
2273
  function useInitializePaymentMethod(options) {
2445
- const { for: forType } = options ?? {};
2274
+ const { for: forType = "user" } = options ?? {};
2446
2275
  const { organization } = useOrganizationContext();
2447
2276
  const user = useUserContext();
2448
2277
  const resource = forType === "organization" ? organization : user;
2449
- const billingEnabled = useBillingHookEnabled(options);
2450
- const queryKey = (0, react.useMemo)(() => {
2451
- return ["billing-payment-method-initialize", { resourceId: resource?.id }];
2452
- }, [resource?.id]);
2453
- const query = useClerkQuery({
2454
- queryKey,
2455
- queryFn: async () => {
2456
- if (!resource) return;
2457
- return resource.initializePaymentMethod({ gateway: "stripe" });
2458
- },
2459
- enabled: Boolean(resource?.id) && billingEnabled,
2460
- staleTime: 1e3 * 60,
2461
- refetchOnWindowFocus: false,
2462
- placeholderData: defineKeepPreviousDataFn(true)
2278
+ const { data, trigger } = (0, swr_mutation.default)(resource?.id ? {
2279
+ key: "billing-payment-method-initialize",
2280
+ resourceId: resource.id,
2281
+ for: forType
2282
+ } : null, () => {
2283
+ return resource?.initializePaymentMethod({ gateway: "stripe" });
2463
2284
  });
2464
- const [queryClient] = useClerkQueryClient();
2465
- const initializePaymentMethod = (0, react.useCallback)(async () => {
2466
- if (!resource) return;
2467
- const result = await resource.initializePaymentMethod({ gateway: "stripe" });
2468
- queryClient.setQueryData(queryKey, result);
2469
- return result;
2470
- }, [
2471
- queryClient,
2472
- queryKey,
2473
- resource
2474
- ]);
2285
+ (0, react.useEffect)(() => {
2286
+ if (!resource?.id) return;
2287
+ trigger().catch(() => {});
2288
+ }, [resource?.id, trigger]);
2475
2289
  return {
2476
- initializedPaymentMethod: query.data ?? void 0,
2477
- initializePaymentMethod
2290
+ initializedPaymentMethod: data,
2291
+ initializePaymentMethod: trigger
2478
2292
  };
2479
2293
  }
2480
2294
 
2481
2295
  //#endregion
2482
- //#region src/react/billing/useStripeClerkLibs.tsx
2296
+ //#region src/react/billing/useStripeClerkLibs.swr.tsx
2483
2297
  /**
2298
+ * This is the existing implementation of the Stripe libraries loader using SWR.
2299
+ * It is kept here for backwards compatibility until our next major version.
2300
+ *
2484
2301
  * @internal
2485
2302
  */
2486
2303
  function useStripeClerkLibs() {
2487
2304
  const clerk = useClerk();
2488
- return useClerkQuery({
2489
- queryKey: ["clerk-stripe-sdk"],
2490
- queryFn: async () => {
2491
- return { loadStripe: await clerk.__internal_loadStripeJs() };
2492
- },
2493
- enabled: useBillingHookEnabled(),
2494
- staleTime: Infinity,
2495
- refetchOnWindowFocus: false,
2496
- placeholderData: defineKeepPreviousDataFn(true)
2305
+ return (0, swr.default)("clerk-stripe-sdk", async () => {
2306
+ return { loadStripe: await clerk.__internal_loadStripeJs() };
2307
+ }, {
2308
+ keepPreviousData: true,
2309
+ revalidateOnFocus: false,
2310
+ dedupingInterval: Infinity
2497
2311
  }).data ?? null;
2498
2312
  }
2499
2313
 
2500
2314
  //#endregion
2501
- //#region src/react/billing/useStripeLoader.tsx
2315
+ //#region src/react/billing/useStripeLoader.swr.tsx
2502
2316
  /**
2317
+ * This is the existing implementation of the Stripe instance loader using SWR.
2318
+ * It is kept here for backwards compatibility until our next major version.
2319
+ *
2503
2320
  * @internal
2504
2321
  */
2505
2322
  function useStripeLoader(options) {
2506
2323
  const { stripeClerkLibs, externalGatewayId, stripePublishableKey } = options;
2507
- const queryKey = (0, react.useMemo)(() => {
2508
- return ["stripe-sdk", {
2509
- externalGatewayId,
2510
- stripePublishableKey
2511
- }];
2512
- }, [externalGatewayId, stripePublishableKey]);
2513
- const billingEnabled = useBillingHookEnabled({ authenticated: true });
2514
- return useClerkQuery({
2515
- queryKey,
2516
- queryFn: () => {
2517
- if (!stripeClerkLibs || !externalGatewayId || !stripePublishableKey) return null;
2518
- return stripeClerkLibs.loadStripe(stripePublishableKey, { stripeAccount: externalGatewayId });
2519
- },
2520
- enabled: Boolean(stripeClerkLibs && externalGatewayId && stripePublishableKey) && billingEnabled,
2521
- staleTime: 1e3 * 60,
2522
- refetchOnWindowFocus: false,
2523
- placeholderData: defineKeepPreviousDataFn(true)
2324
+ return (0, swr.default)(stripeClerkLibs && externalGatewayId && stripePublishableKey ? {
2325
+ key: "stripe-sdk",
2326
+ externalGatewayId,
2327
+ stripePublishableKey
2328
+ } : null, ({ stripePublishableKey: stripePublishableKey$1, externalGatewayId: externalGatewayId$1 }) => {
2329
+ return stripeClerkLibs?.loadStripe(stripePublishableKey$1, { stripeAccount: externalGatewayId$1 });
2330
+ }, {
2331
+ keepPreviousData: true,
2332
+ revalidateOnFocus: false,
2333
+ dedupingInterval: 1e3 * 60
2524
2334
  }).data;
2525
2335
  }
2526
2336
 
@@ -2710,9 +2520,9 @@ exports.__experimental_usePaymentMethods = usePaymentMethods;
2710
2520
  exports.__experimental_usePlans = usePlans;
2711
2521
  exports.__experimental_useStatements = useStatements;
2712
2522
  exports.__experimental_useSubscription = useSubscription;
2713
- exports.__internal_usePaymentAttemptQuery = usePaymentAttemptQuery;
2714
- exports.__internal_usePlanDetailsQuery = __internal_usePlanDetailsQuery;
2715
- exports.__internal_useStatementQuery = useStatementQuery;
2523
+ exports.__internal_usePaymentAttemptQuery = __internal_usePaymentAttemptQuery;
2524
+ exports.__internal_usePlanDetailsQuery = usePlanDetailsQuery;
2525
+ exports.__internal_useStatementQuery = __internal_useStatementQuery;
2716
2526
  exports.assertContextExists = assertContextExists;
2717
2527
  exports.createContextAndHook = createContextAndHook;
2718
2528
  exports.isDeeplyEqual = isDeeplyEqual;