// Shared internals for the binding hooks. import { shouldThrowError } from '@tanstack/query-core'; import { subSlot, use, useMemo } from 'octane'; export { subSlot }; // Split the compiler-injected trailing slot off a hook's runtime args, returning // the user args (everything before it) and the slot. export function splitSlot(args: any[]): [any[], symbol | undefined] { const tail = args[args.length - 1]; const slot = typeof tail === 'symbol' ? (tail as symbol) : undefined; return [slot !== undefined ? args.slice(0, -1) : args, slot]; } // react-query's default suspense throwOnError: only throw if there's no data. export const defaultThrowOnError = (_error: unknown, query: any): boolean => query.state.data === undefined; // react-query's ensureSuspenseTimers: a suspense query gets a >=1s staleTime/gcTime // floor so it can't immediately refetch and re-trigger the fallback in a loop. export function ensureSuspenseTimers(defaultedOptions: any): void { if (defaultedOptions.suspense) { const MIN = 1000; const clamp = (value: any) => (value === 'static' ? value : Math.max(value ?? MIN, MIN)); const orig = defaultedOptions.staleTime; defaultedOptions.staleTime = typeof orig === 'function' ? (...args: any[]) => clamp(orig(...args)) : clamp(orig); if (typeof defaultedOptions.gcTime === 'number') { defaultedOptions.gcTime = Math.max(defaultedOptions.gcTime, MIN); } } } // prevent-error-boundary-retry: when a query opts into throwing, don't retry on // mount so an already-errored cached query re-throws immediately — UNLESS the // reset boundary has been reset, in which case a retry is expected. export function ensurePreventErrorBoundaryRetry( options: any, errorResetBoundary: { isReset: () => boolean }, query: any, ): void { const throwOnError = query?.state.error && typeof options.throwOnError === 'function' ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError; if (options.suspense || throwOnError) { if (!errorResetBoundary.isReset()) { options.retryOnMount = false; } } } export const shouldSuspend = (defaultedOptions: any, result: any): boolean => defaultedOptions?.suspense && result.isPending; // react-query's suspense fetch: kick the optimistic fetch and — CRUCIALLY — clear // the reset boundary on error. Without the clearReset, a boundary reset→retry // that fails AGAIN leaves `isReset()` true at replay, `getHasError` returns // false, and a suspense component falls through to render with undefined data // instead of re-throwing to the boundary. The returned promise resolves even on // error (the replay surfaces the error through the error-boundary throw). export function fetchOptimistic( defaultedOptions: any, observer: any, errorResetBoundary: { clearReset: () => void }, ): Promise { return observer.fetchOptimistic(defaultedOptions).catch(() => { errorResetBoundary.clearReset(); }); } type SuspensePromise = PromiseLike & { status?: 'pending' | 'fulfilled' | 'rejected'; }; interface SuspensePromiseCache { promise: SuspensePromise | undefined; } /** * Octane suspense divergence (see audit/test-classifications.json): * Suspend through a stable `use()` occurrence for one query-hook call site. * * `use()` tracks thenables by dynamic call order. A component with two * sequential suspense queries initially reaches only the first query; when it * resolves, the first query no longer needs to suspend and the second query is * reached for the first time. If the first call simply skips `use()`, the * second query takes its call-order position and replay reuses the first * query's fulfilled promise, exposing the second query's still-pending result. * * Retain the promise that suspended this query hook and keep reading it after * it settles. That reserves the query hook's call-order position throughout * the replay episode. A key-specific memo lets a held transition restore the * committed key's promise when publishing its pending cue. A mutable ref would * make that old-key render read the new key's pending promise and show fallback. * Re-renders during the same pending fetch reuse the in-flight promise. * * `key` must identify the queries this call site suspends on, never only the * ones still pending: settling must not change it, or the memo drops the * settled promise mid-episode and the call site stops reserving its position. */ export function useSuspensePromise( shouldSuspend: boolean, key: unknown, createPromise: () => PromiseLike, slot: symbol | undefined, ): void { const cache = useMemo(() => ({ promise: undefined }), [key], slot); if (shouldSuspend && (cache.promise === undefined || cache.promise.status !== 'pending')) { cache.promise = createPromise() as SuspensePromise; } if (cache.promise !== undefined) use(cache.promise); } // react-query's getHasError: only throw if the query errored, the boundary isn't // reset, the query isn't refetching, and the options opt into throwing. export function getHasError({ result, errorResetBoundary, throwOnError, query, suspense, }: { result: any; errorResetBoundary: { isReset: () => boolean }; throwOnError: any; query: any; suspense: any; }): boolean { return ( result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && ((suspense && result.data === undefined) || shouldThrowError(throwOnError, [result.error, query])) ); }