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

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