@hyper-fetch/react 9.6.0 → 9.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["r","f","t","u","a","n","v","y","d","n","o","t","r","e","u","l","c"],"sources":["../../../node_modules/.pnpm/@better-hooks+lifecycle@2.0.0_react@19.2.5/node_modules/@better-hooks/lifecycle/dist/index.esm.js","../../../node_modules/.pnpm/@better-hooks+performance@2.1.0_react@19.2.5/node_modules/@better-hooks/performance/dist/index.esm.js","../src/utils/scope.utils.ts","../src/helpers/use-request-events/use-request-events.hooks.ts","../src/helpers/use-tracked-state/use-tracked-state.constants.ts","../src/hydrate/hydrate.utils.ts","../src/hydrate/hydrate.tsx","../src/utils/deep-equal.utils.ts","../src/utils/bounce.utils.ts","../src/utils/tracked-proxy.utils.ts","../src/helpers/use-tracked-state/use-tracked-state.utils.ts","../src/helpers/use-tracked-state/use-tracked-state.hooks.ts","../src/helpers/use-socket-state/use-socket-state.hooks.ts","../src/helpers/use-socket-state/use-socket-state.constants.ts","../src/provider/provider.tsx","../src/hooks/use-fetch/use-fetch.hooks.ts","../src/hooks/use-fetch/use-fetch.utils.ts","../src/hooks/use-fetch/use-fetch.constants.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.constants.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.requests.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts","../src/hooks/use-submit/use-submit.hooks.ts","../src/hooks/use-submit/use-submit.constants.ts","../src/hooks/use-queue/use-queue.hooks.ts","../src/hooks/use-queue/use-queue.constants.ts","../src/hooks/use-cache/use-cache.hooks.ts","../src/hooks/use-cache/use-cache.constants.ts","../src/hooks/use-stream/use-stream.hooks.ts","../src/hooks/use-listener/use-listener.hooks.ts","../src/hooks/use-emitter/use-emitter.hooks.ts","../src/hooks/use-app-manager/use-app-manager.hooks.ts","../src/hooks/use-is-fetching/use-is-fetching.hooks.ts"],"sourcesContent":["import{useRef as r,useEffect as n,useState as t,useCallback as u,useLayoutEffect as c}from\"react\";var e=function(t,u,c){void 0===c&&(c=!1);var e=r(null),o=r(c);n((function(){if(o.current)return function(){t(e.current),e.current=u};o.current=!0}),u)},o=function(t){var u=r(!1);n((function(){if(!u.current)return u.current=!0,t()}),[])},i=function(t,u,c){void 0===c&&(c=!1);var e=r(c);n((function(){if(e.current)return t();e.current=!0}),u)};var f=function(){var r=function(r,n){var t=\"function\"==typeof Symbol&&r[Symbol.iterator];if(!t)return r;var u,c,e=t.call(r),o=[];try{for(;(void 0===n||n-- >0)&&!(u=e.next()).done;)o.push(u.value)}catch(r){c={error:r}}finally{try{u&&!u.done&&(t=e.return)&&t.call(e)}finally{if(c)throw c.error}}return o}(t(0),2)[1];return u((function(){r((function(r){return r+1}))}),[])},a=function(){var t=r(!0);return n((function(){return t.current=!0,function(){t.current=!1}}),[]),t},v=function(n){var t=r(!1);c((function(){if(!t.current)return t.current=!0,n()}),[])},l=function(n,t,u){void 0===u&&(u=!1);var e=r(u);c((function(){if(e.current)return n();e.current=!0}),t)},y=function(n){var t=r(!0);t.current&&n(),t.current=!1},d=function(r){n((function(){return r}),[])};export{e as useDepsChange,o as useDidMount,i as useDidUpdate,f as useForceUpdate,a as useIsMounted,v as useLayoutMount,l as useLayoutUpdate,y as useWillMount,d as useWillUnmount};\n//# sourceMappingURL=index.esm.js.map\n","import{useRef as n,useCallback as t,useEffect as r,useState as e,useMemo as u,useLayoutEffect as c}from\"react\";import{useForceUpdate as o,useDidUpdate as i,useDidMount as l}from\"@better-hooks/lifecycle\";var f=function(e){var u=(e||{}).delay,c=void 0===u?400:u,i=n(!1),l=n(null),f=o(),a=t((function(){i.current&&f()}),[f]),v=function(){null!==l.current&&clearTimeout(l.current),l.current=null},d=t((function(n,t){var r=null!=t?t:c;v(),l.current=setTimeout((function(){l.current=null,n(),a()}),r),a()}),[c,a]);return r((function(){return v}),[]),{get active(){return i.current=!0,!!l.current},debounce:d,reset:v}},a=function(n,t,e){var u=f(t).debounce;r((function(){u(n)}),e)};function v(n,t){var r=\"function\"==typeof Symbol&&n[Symbol.iterator];if(!r)return n;var e,u,c=r.call(n),o=[];try{for(;(void 0===t||t-- >0)&&!(e=c.next()).done;)o.push(e.value)}catch(n){u={error:n}}finally{try{e&&!e.done&&(r=c.return)&&r.call(c)}finally{if(u)throw u.error}}return o}var d=function(n,t){var r=f(t).debounce,u=v(e(n),2),c=u[0],o=u[1];return[c,function(n){return r((function(){return o(n)}))}]},y=function(n){var t=Object.prototype.toString.call(n);return Array.isArray(n)?!n.length:\"object\"==typeof n&&null!==n&&\"[object Object]\"===t&&!Object.keys(n).length},m=function(n,t){var r,e=Object.prototype.toString.call(n),u=Object.prototype.toString.call(t),c=typeof n,o=typeof t,i=function(n){return c===n&&o===n};return e===u&&(null===n&&null===t||(!!(i(\"number\")&&Number.isNaN(n)&&Number.isNaN(t))||(!(!y(n)||!y(t))||(Array.isArray(n)&&Array.isArray(t)?n.length===t.length&&!n.some((function(n,r){return!m(n,t[r])})):i(\"object\")&&(e===(r=\"[object Object]\")&&u===r)?Object.keys(n).length===Object.keys(t).length&&!Object.entries(n).some((function(n){var r=v(n,2),e=r[0],u=r[1];return!m(u,t[e])})):n instanceof Date&&t instanceof Date?+n==+t:n===t))))},s=function(t,e){return r(t,(o=n(c=e),i=n(0),m(c,o.current)||(o.current=c,i.current+=1),u((function(){return o.current}),[i.current])));var c,o,i},b=function(t,r,u){var c=u||{},o=c.immediate,f=void 0===o||o,a=c.disabled,d=void 0!==a&&a,y=v(e(null),2),m=y[0],s=y[1],b=n(t),p=function(){m&&clearInterval(m),s(null)},h=function(){p(),!r&&0!==r||d||s(setInterval((function(){return b.current()}),r))};return i((function(){b.current=t}),[t]),l((function(){if(b.current=t,f)return h(),p})),i((function(){return b.current=t,h(),p}),[r]),{active:null!==m,start:h,stop:p}},p=function(t){var e=t||{},u=e.interval,c=void 0===u?200:u,i=e.timeout,l=void 0===i?200:i,f=n(0),a=n(!0),v=n(!1),d=n(null),y=o(),m=function(){a.current&&(a.current=!1),v.current&&y()},s=function(){null!==d.current&&clearTimeout(d.current),d.current=null};return r((function(){return s}),[]),{get active(){return v.current=!0,!!d.current},throttle:function(n,t){var r,e,u=function(){f.current=Date.now(),n(),m()},o=null!==(r=null==t?void 0:t.interval)&&void 0!==r?r:c,i=null!==(e=null==t?void 0:t.timeout)&&void 0!==e?e:l,v=Date.now()>=f.current+o;a.current&&m(),d.current&&s(),v?u():i&&(d.current=setTimeout((function(){d.current=null,a.current=!0,u()}),i))},reset:s}},h=function(n,t,e){var u=p(t).throttle;r((function(){u(n)}),e)},j=function(n,t){var r=p(t).throttle,u=v(e(n),2),c=u[0],o=u[1];return[c,function(n){return r((function(){return o(n)}))}]},g=function(t,e){var u=n(t);w((function(){u.current=t}),[t]),r((function(){if(e||0===e){var n=setTimeout((function(){return u.current()}),e);return function(){return clearTimeout(n)}}}),[e])},w=!(\"undefined\"==typeof window||void 0===window.document||void 0===window.document.createElement)?c:r;export{f as useDebounce,a as useDebounceEffect,d as useDebounceState,s as useDeepEffect,b as useInterval,w as useIsomorphicEffect,p as useThrottle,h as useThrottleEffect,j as useThrottleState,g as useTimeout};\n//# sourceMappingURL=index.esm.js.map\n","/**\n * Core emits request and cache events by the logical (unscoped) keys, while dispatcher queues and cache storage\n * use the scoped keys. Listeners subscribe by the logical key and use this check to skip events of other scopes.\n * @internal\n */\nexport const isSameScope = (scope: string | null | undefined, otherScope: string | null | undefined): boolean => {\n return (scope ?? null) === (otherScope ?? null);\n};\n","import { useIsMounted, useWillUnmount } from \"@better-hooks/lifecycle\";\nimport type {\n ExtractErrorType,\n ExtractResponseType,\n RequestInstance,\n RequestEventType,\n RequestLoadingEventType,\n ExtractAdapterType,\n RequestProgressEventType,\n RequestResponseEventType,\n ResponseType,\n OptimisticCallbackResult,\n} from \"@hyper-fetch/core\";\nimport { runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport type {\n OnErrorCallbackType,\n OnStartCallbackType,\n OnSuccessCallbackType,\n OnProgressCallbackType,\n OnFinishedCallbackType,\n UseRequestEventsDataMap,\n UseRequestEventsReturnType,\n UseRequestEventsPropsType,\n UseRequestEventsLifecycleMap,\n} from \"helpers\";\nimport { useRef } from \"react\";\nimport { isSameScope } from \"utils/scope.utils\";\n\n/**\n * This is helper hook that handles main Hyper-Fetch event/data flow\n * @internal\n * @param options\n * @returns\n */\nexport const useRequestEvents = <R extends RequestInstance>({\n request,\n dispatcher,\n logger,\n actions,\n setCacheData,\n getIsDataProcessing,\n}: UseRequestEventsPropsType<R>): UseRequestEventsReturnType<R> => {\n const { cache, requestManager } = request.client;\n\n // ******************\n // Callbacks\n // ******************\n\n const onSuccessCallback = useRef<null | OnSuccessCallbackType<R>>(null);\n const onErrorCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onAbortCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onOfflineErrorCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onFinishedCallback = useRef<null | OnFinishedCallbackType<R>>(null);\n const onRequestStartCallback = useRef<null | OnStartCallbackType<R>>(null);\n const onResponseStartCallback = useRef<null | OnStartCallbackType<R>>(null);\n const onDownloadProgressCallback = useRef<null | OnProgressCallbackType>(null);\n const onUploadProgressCallback = useRef<null | OnProgressCallbackType>(null);\n\n // ******************\n // Listeners unmounting\n // ******************\n\n const lifecycleEvents = useRef<UseRequestEventsLifecycleMap>(new Map());\n const dataEvents = useRef<UseRequestEventsDataMap | null>(null);\n // Sending can outlive the component - the unmount cleanup never sees listeners attached after it ran\n const isMounted = useIsMounted();\n\n const removeLifecycleListener = (requestId: string) => {\n const event = lifecycleEvents.current.get(requestId);\n event?.unmount();\n lifecycleEvents.current.delete(requestId);\n };\n\n const clearLifecycleListeners = () => {\n const events = lifecycleEvents.current;\n const listeners = [...events.values()];\n listeners.forEach((value) => {\n value.unmount();\n });\n events.clear();\n };\n\n // ******************\n // Optimistic state\n // ******************\n\n // Rollback and invalidation are settled by the core - here we only deliver the context to the callbacks\n const optimisticResultsRef = useRef<Map<string, OptimisticCallbackResult<any>>>(new Map());\n\n // ******************\n // Response handlers\n // ******************\n\n const handleResponseCallbacks = (values: RequestResponseEventType<R>) => {\n const { success } = values.response;\n const { isOffline, isCanceled, willRetry } = values.details;\n const opt = optimisticResultsRef.current.get(values.requestId);\n const paramsWithContext = { ...values, mutationContext: opt?.context } as any;\n const isOfflineError = request.offline && isOffline && !success;\n\n if (isOfflineError) {\n logger.debug({ title: \"Performing offline error callback\", type: \"system\", extra: values });\n onOfflineErrorCallback.current?.(paramsWithContext);\n } else if (isCanceled) {\n logger.debug({ title: \"Performing abort callback\", type: \"system\", extra: values });\n onAbortCallback.current?.(paramsWithContext);\n } else if (success) {\n logger.debug({ title: \"Performing success callback\", type: \"system\", extra: values });\n onSuccessCallback.current?.(paramsWithContext);\n } else {\n logger.debug({ title: \"Performing error callback\", type: \"system\", extra: values });\n onErrorCallback.current?.(paramsWithContext);\n }\n onFinishedCallback.current?.(paramsWithContext);\n // Retried and offline requests respond again, their callbacks still need the context\n if (!willRetry && (!isOfflineError || isCanceled)) {\n optimisticResultsRef.current.delete(values.requestId);\n }\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n const handleGetLoadingEvent = (req: R) => {\n return ({ loading, request: eventRequest }: RequestLoadingEventType<RequestInstance>) => {\n // Loading events are emitted by the logical queryKey - skip requests of other scopes\n if (!isSameScope(eventRequest.scope, req.scope)) {\n return;\n }\n\n const isProcessing = getIsDataProcessing(req.cacheKey);\n\n // When we process the cache data, we don't want to change the loading state during it\n // This prevents the UI from flickering with { data: null, loading: false }\n if (isProcessing) {\n return;\n }\n\n const canDisableLoading = !loading && !dispatcher.hasRunningRequests(scopeKey(req.queryKey, req.scope));\n if (loading || canDisableLoading) {\n actions.setLoading(loading);\n }\n };\n };\n\n const handleDownloadProgress = (data: RequestProgressEventType<RequestInstance>) => {\n onDownloadProgressCallback.current?.(data);\n };\n\n const handleUploadProgress = (data: RequestProgressEventType<RequestInstance>) => {\n onUploadProgressCallback.current?.(data);\n };\n\n const handleRequestStart = () => {\n return (details: RequestEventType<R>) => {\n onRequestStartCallback.current?.(details);\n };\n };\n const handleResponseStart = () => {\n return (details: RequestEventType<R>) => {\n onResponseStartCallback.current?.(details);\n };\n };\n\n const handleResponse = () => {\n return (values: RequestResponseEventType<R>) => {\n const data = runResponseMapper(request, values.response);\n\n if (data instanceof Promise) {\n return (async () => {\n handleResponseCallbacks({\n ...values,\n response: (await data) as ResponseType<any, any, ExtractAdapterType<R>>,\n });\n })();\n }\n return handleResponseCallbacks(values);\n };\n };\n\n const handleRemove = ({ requestId }: RequestEventType<R>) => {\n optimisticResultsRef.current.delete(requestId);\n removeLifecycleListener(requestId);\n };\n\n // ******************\n // Data Listeners\n // ******************\n\n const clearCacheDataListener = () => {\n dataEvents.current?.unmount();\n dataEvents.current = null;\n };\n\n const addCacheDataListener = (req: R) => {\n if (!isMounted.current) {\n return () => undefined;\n }\n\n // Data handlers\n // Core emits these events by the logical keys; the handlers skip events of other scopes\n const loadingUnmount = requestManager.events.onLoadingByQueue(req.queryKey, handleGetLoadingEvent(req));\n const getResponseUnmount = cache.events.onDataByKey<\n ExtractResponseType<R>,\n ExtractErrorType<R>,\n ExtractAdapterType<R>\n >(req.cacheKey, (cacheData) => {\n if (!isSameScope(cacheData.scope, req.scope)) {\n return;\n }\n setCacheData(cacheData);\n });\n\n const unmount = () => {\n loadingUnmount();\n getResponseUnmount();\n };\n\n clearCacheDataListener();\n dataEvents.current = { unmount };\n\n return unmount;\n };\n\n // ******************\n // Lifecycle Listeners\n // ******************\n\n const addLifecycleListeners = (req: R, requestId?: string, optimisticResult?: OptimisticCallbackResult<any>) => {\n if (!isMounted.current) {\n return () => undefined;\n }\n\n /**\n * useFetch handles requesting by general keys\n * This makes it possible to deduplicate requests from different places and share data\n */\n if (!requestId) {\n // It's important to clear previously attached listeners to not cause some additional response/request\n // events to be triggered during lifecycle\n clearLifecycleListeners();\n const { queryKey, cacheKey } = req;\n const requestStartUnmount = requestManager.events.onRequestStartByQueue(queryKey, handleRequestStart());\n const responseStartUnmount = requestManager.events.onResponseStartByQueue(queryKey, handleResponseStart());\n const uploadUnmount = requestManager.events.onUploadProgressByQueue(queryKey, handleUploadProgress);\n const downloadUnmount = requestManager.events.onDownloadProgressByQueue(queryKey, handleDownloadProgress);\n const responseUnmount = requestManager.events.onResponseByCache(cacheKey, handleResponse());\n\n const unmount = () => {\n downloadUnmount();\n uploadUnmount();\n requestStartUnmount();\n responseStartUnmount();\n responseUnmount();\n };\n\n lifecycleEvents.current.set(queryKey, { unmount });\n\n return unmount;\n }\n /**\n * useSubmit handles requesting by requestIds, this makes it possible to track single requests\n */\n if (optimisticResult) {\n optimisticResultsRef.current.set(requestId, optimisticResult);\n }\n const requestRemove = requestManager.events.onRemoveById(requestId, handleRemove);\n const requestStartUnmount = requestManager.events.onRequestStartById(requestId, handleRequestStart());\n const responseStartUnmount = requestManager.events.onResponseStartById(requestId, handleResponseStart());\n const responseUnmount = requestManager.events.onResponseById(requestId, handleResponse());\n const uploadUnmount = requestManager.events.onUploadProgressById(requestId, handleUploadProgress);\n const downloadUnmount = requestManager.events.onDownloadProgressById(requestId, handleDownloadProgress);\n\n const unmount = () => {\n requestRemove();\n downloadUnmount();\n uploadUnmount();\n requestStartUnmount();\n responseStartUnmount();\n responseUnmount();\n };\n\n lifecycleEvents.current.set(requestId, { unmount });\n\n return unmount;\n };\n\n // ******************\n // Abort\n // ******************\n\n const abort = () => {\n const ak = scopeKey(request.abortKey, request.scope);\n const requests = dispatcher.getAllRunningRequests();\n requests.forEach((requestData) => {\n const reqAk = scopeKey(requestData.request.abortKey, requestData.request.scope);\n if (reqAk === ak) {\n const qk = scopeKey(requestData.request.queryKey, requestData.request.scope);\n dispatcher.delete(qk, requestData.requestId, reqAk);\n }\n });\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n /**\n * On unmount we want to clear all the listeners to prevent memory leaks\n */\n useWillUnmount(() => {\n // Unmount listeners\n clearLifecycleListeners();\n clearCacheDataListener();\n });\n\n return [\n {\n abort,\n onSuccess: (callback: OnSuccessCallbackType<R>) => {\n onSuccessCallback.current = callback;\n },\n onError: (callback: OnErrorCallbackType<R>) => {\n onErrorCallback.current = callback;\n },\n onAbort: (callback: OnErrorCallbackType<R>) => {\n onAbortCallback.current = callback;\n },\n onOfflineError: (callback: OnErrorCallbackType<R>) => {\n onOfflineErrorCallback.current = callback;\n },\n onFinished: (callback: OnFinishedCallbackType<R>) => {\n onFinishedCallback.current = callback;\n },\n onRequestStart: (callback: OnStartCallbackType<R>) => {\n onRequestStartCallback.current = callback;\n },\n onResponseStart: (callback: OnStartCallbackType<R>) => {\n onResponseStartCallback.current = callback;\n },\n onDownloadProgress: (callback: OnProgressCallbackType) => {\n onDownloadProgressCallback.current = callback;\n },\n onUploadProgress: (callback: OnProgressCallbackType) => {\n onUploadProgressCallback.current = callback;\n },\n },\n {\n addCacheDataListener,\n clearCacheDataListener,\n addLifecycleListeners,\n removeLifecycleListener,\n clearLifecycleListeners,\n },\n ];\n};\n","import type { UseTrackedStateType } from \"./use-tracked-state.types\";\n\nexport const initialState: UseTrackedStateType = {\n data: null,\n error: null,\n status: null,\n extra: {},\n success: false,\n loading: false,\n retries: 0,\n responseTimestamp: null,\n requestTimestamp: null,\n};\n","import type {\n CacheValueType,\n ClientInstance,\n EmptyTypes,\n HydrateDataType,\n HydrationOptions,\n NullableType,\n} from \"@hyper-fetch/core\";\nimport { parseResponse, scopeKey } from \"@hyper-fetch/core\";\n\nimport type { HydratedEntry, HydrateOptionsType } from \"./hydrate.types\";\n\n/**\n * Items already written to the cache (or skipped because the cache held newer data), per client.\n * Once an item is consumed the cache is the source of truth, so a hook mounted after `client.clear()`\n * does not get the old server snapshot back.\n */\nconst consumedItems = new WeakMap<ClientInstance, WeakSet<HydrateDataType>>();\n\nconst getConsumed = (client: ClientInstance) => {\n let consumed = consumedItems.get(client);\n if (!consumed) {\n consumed = new WeakSet();\n consumedItems.set(client, consumed);\n }\n return consumed;\n};\n\nexport const isConsumed = (client: ClientInstance, item: HydrateDataType) => {\n return getConsumed(client).has(item);\n};\n\nexport const markConsumed = (client: ClientInstance, item: HydrateDataType) => {\n getConsumed(client).add(item);\n};\n\n/**\n * Resolves the config of a single item exactly like `client.hydrate()` does\n */\nconst resolveConfig = (item: HydrateDataType, options?: HydrateOptionsType) => {\n const { cacheKey, scope, response: _response, ...fallbackOptions } = item;\n const defaults = { cache: true, override: true } satisfies Partial<HydrationOptions>;\n const config =\n typeof options === \"function\"\n ? { ...defaults, ...fallbackOptions, ...options(item) }\n : { ...defaults, ...fallbackOptions, ...options };\n\n return { ...config, cacheKey, scope };\n};\n\nconst getResponseTimestamp = (value: NullableType<{ responseTimestamp?: number | null }>, fallback = 0) => {\n const timestamp = Number(value?.responseTimestamp);\n return Number.isFinite(timestamp) ? timestamp : fallback;\n};\n\n/**\n * Turns dehydrated items into the values they will have in the cache, keyed by storage key.\n * The last item wins when the same key is passed twice.\n */\nexport const getHydratedEntries = (\n client: ClientInstance,\n data: NullableType<(HydrateDataType | EmptyTypes)[]>,\n options?: HydrateOptionsType,\n): Map<string, HydratedEntry> => {\n const entries = new Map<string, HydratedEntry>();\n\n data?.forEach((item) => {\n if (!item) {\n return;\n }\n\n const config = resolveConfig(item, options);\n const response = parseResponse(item.response);\n const storageKey = scopeKey(config.cacheKey, config.scope ?? null);\n\n // Mirrors the value created by `cache.set()`, so the first render matches the state after the write\n const value = {\n ...response,\n cacheKey: config.cacheKey,\n scope: config.scope ?? null,\n staleTime: config.staleTime,\n cacheTime: config.cacheTime,\n version: client.cache.version,\n cached: !!config.cache,\n } as CacheValueType;\n\n entries.set(storageKey, {\n item,\n storageKey,\n value,\n override: config.override !== false,\n timestamp: getResponseTimestamp(response, item.timestamp ?? 0),\n });\n });\n\n return entries;\n};\n\n/**\n * Decides whether the hydrated value should be used instead of the cached one.\n * Newer data always wins; with `override: false` existing cache data is kept.\n */\nexport const shouldUseHydratedValue = (cacheData: NullableType<CacheValueType>, entry: HydratedEntry): boolean => {\n if (!cacheData) {\n return true;\n }\n if (!entry.override) {\n return false;\n }\n return entry.timestamp > getResponseTimestamp(cacheData);\n};\n\n/**\n * Picks the data a hook should start with: cached data, unless the hydrated data is newer\n */\nexport const pickInitialCacheData = <T extends CacheValueType>(\n cacheData: NullableType<T>,\n entry: NullableType<HydratedEntry>,\n): NullableType<T> => {\n if (!entry || !shouldUseHydratedValue(cacheData, entry)) {\n return cacheData;\n }\n return entry.value as T;\n};\n","import React, { useContext, useEffect, useLayoutEffect, useMemo, useRef } from \"react\";\n\nimport type { HydrateProps, HydrationContextType } from \"./hydrate.types\";\nimport { getHydratedEntries, isConsumed, markConsumed, shouldUseHydratedValue } from \"./hydrate.utils\";\n\nconst HydrationContext = React.createContext<HydrationContextType | null>(null);\n\n// Layout effects do not run on the server; on the client they run before any passive effect of the tree\nconst useIsomorphicLayoutEffect = typeof window !== \"undefined\" ? useLayoutEffect : useEffect;\n\n/**\n * Hydrates the client cache with data fetched on the server.\n *\n * - Hooks below it render with the hydrated data on the first render, also during server rendering.\n * - On the client the data is written to the cache before the hooks mount, so fresh data is not refetched.\n * - Newer cache data is never replaced by an older snapshot.\n * - It can be nested and rendered conditionally; every `Hydrate` serves only its own client.\n */\nexport const Hydrate = ({ client, data, options, children }: HydrateProps) => {\n const parent = useContext(HydrationContext);\n\n const entries = useMemo(() => getHydratedEntries(client, data, options), [client, data, options]);\n\n // Read through a ref, so the context value stays stable when only the entries change (e.g. inline options)\n // and memoized children do not re-render. Hooks read the context only on their first render.\n const entriesRef = useRef(entries);\n entriesRef.current = entries;\n\n useIsomorphicLayoutEffect(() => {\n // Server mode cache does not store unscoped data - the context keeps serving it instead\n if (client.mode === \"server\") {\n return;\n }\n\n entries.forEach((entry) => {\n if (isConsumed(client, entry.item)) {\n return;\n }\n markConsumed(client, entry.item);\n\n const cacheData = client.cache.get(entry.storageKey);\n if (!shouldUseHydratedValue(cacheData, entry)) {\n return;\n }\n\n client.hydrate([entry.item], options);\n });\n }, [client, entries, options]);\n\n const value = useMemo<HydrationContextType>(\n () => ({\n get: (targetClient, storageKey) => {\n if (targetClient === client) {\n const entry = entriesRef.current.get(storageKey);\n if (entry) {\n return isConsumed(client, entry.item) ? undefined : entry;\n }\n }\n return parent?.get(targetClient, storageKey);\n },\n }),\n [client, parent],\n );\n\n return <HydrationContext.Provider value={value}>{children}</HydrationContext.Provider>;\n};\n\n/**\n * Access to the closest hydration data\n * @internal\n */\nexport const useHydration = (): HydrationContextType | null => {\n return useContext(HydrationContext);\n};\n","/**\n * Check if value is empty\n * @param value any object or primitive\n * @returns true when value is empty\n */\nexport const isEmpty = (value?: unknown): boolean => {\n const valueType = Object.prototype.toString.call(value);\n if (Array.isArray(value)) {\n return value.length === 0;\n }\n if (typeof value === \"object\" && value !== null && valueType === \"[object Object]\") {\n return Object.keys(value).length === 0;\n }\n return false;\n};\n\n/**\n * Allow to deep compare any passed values\n * @param firstValue unknown\n * @param secondValue unknown\n * @returns true when elements are equal\n */\nexport const isEqual = (firstValue?: unknown, secondValue?: unknown): boolean => {\n // Nulls (objects), and other primitives\n if (firstValue === secondValue) {\n return true;\n }\n\n try {\n const firstValueType = Object.prototype.toString.call(firstValue);\n const secondValueType = Object.prototype.toString.call(secondValue);\n\n const firstType = typeof firstValue;\n const secondType = typeof secondValue;\n\n const isType = (type: unknown) => firstType === type && secondType === type;\n const isTypeValue = (type: unknown) => firstValueType === type && secondValueType === type;\n\n // Compared types are different\n if (firstValueType !== secondValueType) {\n return false;\n }\n\n // NaN\n if (isType(\"number\") && Number.isNaN(firstValue) && Number.isNaN(secondValue)) {\n return true;\n }\n\n // Empty Array or Object\n if (isEmpty(firstValue) && isEmpty(secondValue)) {\n return true;\n }\n\n // Array\n if (Array.isArray(firstValue) && Array.isArray(secondValue)) {\n if (firstValue.length !== secondValue.length) {\n return false;\n }\n\n return !firstValue.some((element, i) => !isEqual(element, secondValue[i]));\n }\n\n // Object\n if (isType(\"object\") && isTypeValue(\"[object Object]\")) {\n if (Object.keys(firstValue as object).length !== Object.keys(secondValue as object).length) {\n return false;\n }\n\n return !Object.entries(firstValue as object).some(\n ([key, value]) => !isEqual(value, (secondValue as Record<string, unknown>)[key]),\n );\n }\n\n // Date\n if (firstValue instanceof Date && secondValue instanceof Date) {\n return +firstValue === +secondValue;\n }\n\n // undefined, string, number, bool\n return firstValue === secondValue;\n } catch (error) {\n console.error(error);\n return false;\n }\n};\n","export const getBounceData = (bounceData: {\n reset: () => void;\n active: boolean;\n}): { reset: () => void; active: boolean } => {\n return {\n ...bounceData,\n // oxlint-disable-next-line unicorn/no-useless-spread\n ...{ throttle: undefined, debounce: undefined },\n };\n};\n","/**\n * Wraps a plain object in a Proxy that calls `setRenderKey` when tracked properties are accessed.\n * Unlike getter-based tracking, Proxy-wrapped objects display their actual values in console.log,\n * making debugging significantly easier while preserving field-level dependency tracking.\n */\nexport const createTrackedProxy = <T extends Record<string, unknown>, K extends string>(\n target: T,\n trackedKeys: readonly K[],\n setRenderKey: (key: K) => void,\n): T => {\n return new Proxy(target, {\n get(obj, prop, receiver) {\n if (typeof prop === \"string\" && trackedKeys.includes(prop as K)) {\n setRenderKey(prop as K);\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n};\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport type {\n CacheValueType,\n NullableType,\n RequestInstance,\n ExtractResponseType,\n ExtractErrorType,\n ExtractAdapterResolvedType,\n Dispatcher,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ResponseDetailsType,\n ExtractAdapterStatusType,\n ResponseType,\n} from \"@hyper-fetch/core\";\nimport { runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport type { UseTrackedStateType } from \"helpers\";\nimport { initialState } from \"helpers\";\nimport type { HydratedEntry } from \"hydrate/hydrate.types\";\nimport { pickInitialCacheData } from \"hydrate/hydrate.utils\";\n\n/**\n * Extracts the \"identity\" portion of a cache key (method + endpoint with resolved params),\n * stripping the query params part. Cache keys follow the format: `method_endpoint_queryParams`.\n */\nconst getCacheKeyIdentity = (cacheKey: string): string => {\n const lastUnderscoreIndex = cacheKey.lastIndexOf(\"_\");\n if (lastUnderscoreIndex === -1) {return cacheKey;}\n return cacheKey.substring(0, lastUnderscoreIndex);\n};\n\n/**\n * Determines whether state should be cleared when the cache key changes.\n *\n * - `\"clean\"` — always clear\n * - `\"preserve\"` — never clear\n * - `\"auto\"` — clear when the resource identity changed (URL params), preserve when only query params changed\n */\nexport const getShouldClearState = (\n mode: \"auto\" | \"preserve\" | \"clean\",\n oldCacheKey: string,\n newCacheKey: string,\n): boolean => {\n if (oldCacheKey === newCacheKey) {return false;}\n\n if (mode === \"clean\") {return true;}\n if (mode === \"preserve\") {return false;}\n\n // \"auto\" — compare the identity part (method + endpoint with params)\n return getCacheKeyIdentity(oldCacheKey) !== getCacheKeyIdentity(newCacheKey);\n};\n\nexport const getDetailsState = (\n state?: UseTrackedStateType<RequestInstance>,\n details?: Partial<ResponseDetailsType>,\n): ResponseDetailsType => {\n return {\n retries: state?.retries || 0,\n isCanceled: false,\n isOffline: false,\n willRetry: false,\n addedTimestamp: Date.now(),\n triggerTimestamp: Date.now(),\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n ...details,\n };\n};\n\nexport const isStaleCacheData = (staleTime: number, staleTimestamp: NullableType<Date | number>) => {\n if (!staleTimestamp) {return true;}\n return Date.now() > +staleTimestamp + staleTime;\n};\n\nexport const getValidCacheData = <T extends RequestInstance>(\n request: T,\n initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>,\n cacheData: NullableType<CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>>,\n): CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>> | null => {\n if (cacheData) {\n return cacheData;\n }\n\n if (initialResponse) {\n return {\n data: null,\n error: null,\n status: null,\n success: true,\n extra: null,\n cached: !!request.cache,\n ...(initialResponse as Partial<ExtractAdapterResolvedType<T>>),\n ...getDetailsState(),\n staleTime: 1000,\n version: request.client.cache.version,\n cacheKey: request.cacheKey,\n scope: request.scope,\n cacheTime: request.cacheTime,\n requestTimestamp: initialResponse?.requestTimestamp ?? Date.now(),\n responseTimestamp: initialResponse?.responseTimestamp ?? Date.now(),\n };\n }\n\n return null;\n};\n\nexport const getTimestamp = (timestamp?: NullableType<number | Date>) => {\n return timestamp ? new Date(timestamp) : null;\n};\n\nexport const getIsInitiallyLoading = <T extends RequestInstance>({\n queryKey,\n dispatcher,\n hasState,\n revalidate,\n disabled,\n}: {\n queryKey: string;\n dispatcher: Dispatcher<ExtractAdapterType<T>>;\n hasState: boolean;\n revalidate?: boolean;\n disabled?: boolean;\n}) => {\n if (!revalidate && hasState) {\n return false;\n }\n\n const queue = dispatcher.getQueue(queryKey);\n const isInitiallyLoading = dispatcher.hasRunningRequests(queryKey) || (!queue.stopped && disabled === false);\n\n return isInitiallyLoading;\n};\n\nexport const getInitialState = <T extends RequestInstance>({\n initialResponse,\n dispatcher,\n request,\n disabled,\n revalidate,\n hydratedEntry,\n}: {\n initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>;\n dispatcher: Dispatcher<ExtractAdapterType<T>>;\n request: T;\n disabled?: boolean; // useFetch only\n revalidate?: boolean; // useFetch only\n /** Data from the closest `Hydrate` that was not written to the cache yet */\n hydratedEntry?: NullableType<HydratedEntry>;\n}): UseTrackedStateType<T> => {\n const { client, cacheKey } = request;\n const { cache } = client;\n\n const cacheData = pickInitialCacheData(\n cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopeKey(cacheKey, request.scope)),\n hydratedEntry,\n );\n const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);\n\n const initialLoading = getIsInitiallyLoading({\n queryKey: scopeKey(request.queryKey, request.scope),\n dispatcher,\n disabled,\n revalidate,\n hasState: !!cacheState,\n });\n\n if (cacheState) {\n const mappedData =\n runResponseMapper(request, cacheState as ResponseType<any, any, ExtractAdapterType<T>>) || cacheState;\n if (mappedData instanceof Promise) {\n // For the async mapper we cannot return async values\n // So we have return the initial state instead\n return initialState;\n }\n return {\n data: mappedData.data,\n error: mappedData.error,\n status: mappedData.status as ExtractAdapterStatusType<ExtractAdapterType<T>>,\n success: mappedData.success,\n extra: (mappedData.extra || client.adapter.defaultExtra) as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: cacheState.retries,\n requestTimestamp: getTimestamp(cacheState.requestTimestamp),\n responseTimestamp: getTimestamp(cacheState.responseTimestamp),\n loading: initialLoading,\n };\n }\n\n return {\n data: initialState.data,\n error: initialState.error,\n status: initialState.status as ExtractAdapterStatusType<ExtractAdapterType<T>>,\n success: initialState.success,\n extra: request.client.adapter.defaultExtra as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: initialState.retries,\n requestTimestamp: getTimestamp(initialState.requestTimestamp),\n responseTimestamp: getTimestamp(initialState.responseTimestamp),\n loading: initialLoading,\n };\n};\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type {\n ExtractErrorType,\n CacheValueType,\n ExtractResponseType,\n RequestInstance,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ResponseType,\n} from \"@hyper-fetch/core\";\nimport { replaceEqualDeep, runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport { useHydration } from \"hydrate/hydrate\";\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport { isEqual } from \"utils\";\n\nimport type {\n UseTrackedStateActions,\n UseTrackedStateType,\n UseTrackedStateProps,\n UseTrackedStateReturn,\n UseTrackedStateResponseDetails,\n} from \"./use-tracked-state.types\";\nimport {\n getInitialState,\n getIsInitiallyLoading,\n getShouldClearState,\n getValidCacheData,\n isStaleCacheData,\n} from \"./use-tracked-state.utils\";\n\n/**\n *\n * @param request\n * @param initialResponse\n * @param dispatcher\n * @param dependencies\n * @internal\n */\nexport const useTrackedState = <T extends RequestInstance, TData = ExtractResponseType<T>>({\n request,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n keepPreviousData = \"auto\",\n disabled,\n revalidate,\n select,\n structuralSharing = true,\n}: UseTrackedStateProps<T, TData>): UseTrackedStateReturn<T, TData> => {\n const { client, cacheKey, queryKey, staleTime } = request;\n const { cache } = client;\n const hydration = useHydration();\n\n const state = useRef<UseTrackedStateType<T, TData>>(null as unknown as UseTrackedStateType<T, TData>);\n const renderKeys = useRef<(keyof UseTrackedStateType<T, TData>)[]>([]);\n const isProcessingData = useRef(\"\");\n const previousCacheKey = useRef(cacheKey);\n\n // ******************\n // Data selection\n // ******************\n\n const selectRef = useRef(select);\n selectRef.current = select;\n const appliedSelect = useRef(select);\n // Response data before applying the selector - allows to re-run it when the selector changes\n const rawData = useRef<ExtractResponseType<T> | null>(null);\n // Data set with the setData action has the selected shape and should not get re-selected\n const isLocalData = useRef(false);\n const selectError = useRef<{ error: unknown } | null>(null);\n const responseDetails = useRef<UseTrackedStateResponseDetails | null>(null);\n\n const selectData = (data: ExtractResponseType<T> | null, previousData: TData | null = null): TData | null => {\n if (!selectRef.current || data === null || data === undefined) {\n return data as TData | null;\n }\n const selected = selectRef.current(data);\n return structuralSharing ? replaceEqualDeep(previousData, selected) : selected;\n };\n\n const getSelectedState = (newState: UseTrackedStateType<T>): UseTrackedStateType<T, TData> => {\n rawData.current = newState.data;\n isLocalData.current = false;\n responseDetails.current = null;\n appliedSelect.current = selectRef.current;\n return { ...newState, data: selectData(newState.data, state.current?.data) };\n };\n\n if (!state.current) {\n const hydratedEntry = hydration?.get(client, scopeKey(cacheKey, request.scope));\n state.current = getSelectedState(\n getInitialState({ initialResponse, dispatcher, request, disabled, hydratedEntry }),\n );\n }\n\n // Selector failed while processing incoming data - surface it to the closest error boundary\n if (selectError.current) {\n const { error } = selectError.current;\n selectError.current = null;\n throw error;\n }\n\n // Selector changed (e.g. it closes over a new prop) - re-run it against the latest response data\n if (appliedSelect.current !== select && !isLocalData.current) {\n appliedSelect.current = select;\n state.current.data = selectData(rawData.current, state.current.data);\n }\n\n // ******************\n // useSyncExternalStore\n // ******************\n\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n // ******************\n // Utils\n // ******************\n\n const getStaleStatus = (): boolean => {\n const cacheData = cache.get(scopeKey(cacheKey, request.scope));\n return !cacheData || isStaleCacheData(staleTime, cacheData?.responseTimestamp);\n };\n\n // ******************\n // Dependency Tracking\n // ******************\n\n const renderKeyTrigger = (keys: (keyof UseTrackedStateType<T, TData>)[]) => {\n const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));\n if (shouldRerender) {emitChange();}\n };\n\n const setRenderKey = (renderKey: keyof UseTrackedStateType<T, TData>) => {\n if (!renderKeys.current.includes(renderKey)) {\n renderKeys.current.push(renderKey);\n }\n };\n\n // ******************\n // Cache initialization\n // ******************\n\n useDidUpdate(\n () => {\n const oldKey = previousCacheKey.current;\n previousCacheKey.current = cacheKey;\n\n // Get cache state\n const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopeKey(cacheKey, request.scope));\n const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);\n\n // Determine whether to clear state based on keepPreviousData mode\n const shouldClear = getShouldClearState(keepPreviousData, oldKey, cacheKey);\n\n if (shouldClear && !cacheState) {\n // Reset state to initial values when no cached data exists for the new key\n const resetState = getInitialState({ initialResponse, dispatcher, request, disabled, revalidate });\n state.current = getSelectedState(resetState);\n renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T, TData>)[]);\n } else if (cacheState) {\n state.current.loading = getIsInitiallyLoading({\n queryKey: scopeKey(request.queryKey, request.scope),\n dispatcher,\n disabled,\n revalidate,\n hasState: true,\n });\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n setCacheData(cacheState);\n }\n // When state is preserved and no cache exists (e.g. query param change in \"auto\" mode),\n // don't update loading on the ref — let the dispatcher's loading event handle it (#126)\n },\n [cacheKey, queryKey],\n true,\n );\n\n // ******************\n // Turn off dependency tracking\n // ******************\n\n useDidUpdate(\n () => {\n const handleDependencyTracking = () => {\n if (!dependencyTracking) {\n Object.keys(state.current).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0]));\n }\n };\n\n handleDependencyTracking();\n },\n [dependencyTracking],\n true,\n );\n\n // ******************\n // Cache data handler\n // ******************\n\n const handleCompare = (firstValue: unknown, secondValue: unknown) => {\n if (Object.is(firstValue, secondValue)) {\n return true;\n }\n if (typeof deepCompare === \"function\") {\n return deepCompare(firstValue, secondValue);\n }\n if (deepCompare) {\n return isEqual(firstValue, secondValue);\n }\n return false;\n };\n\n const handleCacheData = (\n cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>,\n ) => {\n rawData.current = cacheData.data;\n isLocalData.current = false;\n appliedSelect.current = selectRef.current;\n responseDetails.current = {\n willRetry: !!cacheData.willRetry,\n isCanceled: !!cacheData.isCanceled,\n isOffline: !!cacheData.isOffline,\n };\n\n let data: TData | null;\n try {\n data = selectData(cacheData.data, state.current.data);\n } catch (error) {\n // Never throw inside of the cache events - rethrow it on render instead\n selectError.current = { error };\n emitChange();\n return;\n }\n\n const newStateValues: UseTrackedStateType<T, TData> = {\n data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: cacheData.retries,\n responseTimestamp: new Date(cacheData.responseTimestamp),\n requestTimestamp: new Date(cacheData.requestTimestamp),\n loading: dispatcher.hasRunningRequests(scopeKey(queryKey, request.scope)),\n };\n\n const nextState: UseTrackedStateType<T, TData> = { ...state.current };\n const changedKeys = (Object.keys(newStateValues) as (keyof UseTrackedStateType<T, TData>)[]).filter((key) => {\n const isEqualValue = handleCompare(state.current[key], newStateValues[key]);\n // Equal values keep their previous reference, so they stay stable between renders\n if (!isEqualValue) {\n (nextState as Record<string, unknown>)[key] = newStateValues[key];\n }\n return !isEqualValue;\n });\n\n state.current = nextState;\n\n renderKeyTrigger(changedKeys);\n };\n\n const setIsDataProcessing = ({\n processingCacheKey,\n isProcessing,\n }: {\n processingCacheKey: string;\n isProcessing: boolean;\n }) => {\n if (isProcessing) {\n isProcessingData.current = processingCacheKey;\n }\n // Do not turn off other keys processing\n else if (isProcessingData.current === cacheKey) {\n isProcessingData.current = \"\";\n }\n };\n\n const getIsDataProcessing = (processingCacheKey: string) => {\n return isProcessingData.current === processingCacheKey;\n };\n\n const setCacheData = (\n cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>,\n ): Promise<void> | void => {\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: true });\n const data = runResponseMapper(request, cacheData as ResponseType<any, any, ExtractAdapterType<T>>) || cacheData;\n\n if (data instanceof Promise) {\n return (async () => {\n const promiseData = await data;\n handleCacheData({ ...cacheData, ...promiseData } as CacheValueType<\n ExtractResponseType<T>,\n ExtractErrorType<T>,\n ExtractAdapterType<T>\n >);\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: false });\n })();\n }\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: false });\n return handleCacheData({ ...cacheData, ...data } as CacheValueType<\n ExtractResponseType<T>,\n ExtractErrorType<T>,\n ExtractAdapterType<T>\n >);\n };\n\n // ******************\n // Actions\n // ******************\n\n const actions: UseTrackedStateActions<T, TData> = {\n setData: (data) => {\n isLocalData.current = true;\n state.current.data = data instanceof Function ? data(state.current.data || null) : data;\n renderKeyTrigger([\"data\"]);\n },\n setError: (error) => {\n state.current.error = error instanceof Function ? error(state.current.error || null) : error;\n renderKeyTrigger([\"error\"]);\n },\n setLoading: (loading) => {\n const value = loading instanceof Function ? loading(state.current.loading) : loading;\n if (value === state.current.loading) {return;}\n state.current.loading = value;\n renderKeyTrigger([\"loading\"]);\n },\n setStatus: (status) => {\n const value = status instanceof Function ? status(state.current.status) : status;\n if (value === state.current.status) {return;}\n state.current.status = status instanceof Function ? status(state.current.status || null) : status;\n renderKeyTrigger([\"status\"]);\n },\n setSuccess: (success) => {\n const value = success instanceof Function ? success(state.current.success || false) : success;\n if (value === state.current.success) {return;}\n state.current.success = success instanceof Function ? success(state.current.success || false) : success;\n renderKeyTrigger([\"success\"]);\n },\n setExtra: (extra) => {\n const value = extra instanceof Function ? extra(state.current.extra) : extra;\n if (value === state.current.extra) {return;}\n state.current.extra = extra instanceof Function ? extra(state.current.extra) : extra;\n renderKeyTrigger([\"extra\"]);\n },\n setRetries: (retries) => {\n const value = retries instanceof Function ? retries(state.current.retries || 0) : retries;\n if (value === state.current.retries) {return;}\n state.current.retries = retries instanceof Function ? retries(state.current.retries || 0) : retries;\n renderKeyTrigger([\"retries\"]);\n },\n setResponseTimestamp: (timestamp) => {\n const value = timestamp instanceof Function ? timestamp(state.current.responseTimestamp) : timestamp;\n if (value === state.current.responseTimestamp) {return;}\n const getTimestamp = (prev: Date | null) => {\n return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;\n };\n\n state.current.responseTimestamp = getTimestamp(state.current.responseTimestamp);\n renderKeyTrigger([\"responseTimestamp\"]);\n },\n setRequestTimestamp: (timestamp) => {\n const value = timestamp instanceof Function ? timestamp(state.current.requestTimestamp) : timestamp;\n if (value === state.current.requestTimestamp) {return;}\n const getTimestamp = (prev: Date | null) => {\n return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;\n };\n\n state.current.requestTimestamp = getTimestamp(state.current.requestTimestamp);\n renderKeyTrigger([\"requestTimestamp\"]);\n },\n clearState: () => {\n rawData.current = null;\n isLocalData.current = false;\n responseDetails.current = null;\n state.current = {\n data: null,\n error: null,\n loading: false,\n status: null,\n success: false,\n extra: null,\n retries: 0,\n responseTimestamp: null,\n requestTimestamp: null,\n } as UseTrackedStateType<T, TData>;\n renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T, TData>)[]);\n },\n };\n\n return [\n state.current,\n actions,\n {\n setRenderKey,\n setCacheData,\n getStaleStatus,\n getIsDataProcessing,\n selectData: (data) => selectData(data, state.current.data),\n getResponseDetails: () => responseDetails.current,\n },\n ];\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { SocketInstance, ExtractSocketExtraType } from \"@hyper-fetch/sockets\";\nimport type { UseSocketStateType, UseSocketStateProps } from \"helpers\";\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\n\nexport const useSocketState = <DataType, Socket extends SocketInstance>(\n socket: Socket,\n { dependencyTracking }: UseSocketStateProps,\n) => {\n const onDisconnectCallback = useRef<null | VoidFunction>(null);\n const onErrorCallback = useRef<null | ((event: any) => void)>(null);\n const onConnectedCallback = useRef<null | VoidFunction>(null);\n const onConnectingCallback = useRef<null | VoidFunction>(null);\n const onReconnectingCallback = useRef<null | ((data: { attempts: number }) => void)>(null);\n const onReconnectingFailedCallback = useRef<null | ((data: { attempts: number }) => void)>(null);\n\n const state = useRef<UseSocketStateType<Socket, DataType>>({\n data: null,\n extra: null,\n connected: socket.adapter.connected,\n connecting: socket.adapter.connecting,\n timestamp: null,\n });\n const renderKeys = useRef<(keyof UseSocketStateType<Socket, DataType>)[]>([]);\n\n // ******************\n // useSyncExternalStore\n // ******************\n\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n // ******************\n // Dependency Tracking\n // ******************\n\n const renderKeyTrigger = (keys: (keyof UseSocketStateType<Socket, DataType>)[]) => {\n const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));\n if (shouldRerender) {emitChange();}\n };\n\n const setRenderKey = (renderKey: keyof UseSocketStateType<Socket, DataType>) => {\n if (!renderKeys.current.includes(renderKey)) {\n renderKeys.current.push(renderKey);\n }\n };\n\n // ******************\n // Turn off dependency tracking\n // ******************\n\n useDidUpdate(\n () => {\n const handleDependencyTracking = () => {\n if (!dependencyTracking) {\n Object.keys(state.current).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0]));\n }\n };\n\n handleDependencyTracking();\n },\n [dependencyTracking],\n true,\n );\n\n // ******************\n // Actions\n // ******************\n\n const actions = {\n setData: (data: DataType | null) => {\n state.current.data = data;\n renderKeyTrigger([\"data\"]);\n },\n setExtra: (extra: ExtractSocketExtraType<Socket> | null) => {\n state.current.extra = extra;\n renderKeyTrigger([\"extra\"]);\n },\n setConnected: (connected: boolean) => {\n state.current.connected = connected;\n renderKeyTrigger([\"connected\"]);\n },\n setConnecting: (connecting: boolean) => {\n state.current.connecting = connecting;\n renderKeyTrigger([\"connecting\"]);\n },\n setTimestamp: (timestamp: number | null) => {\n state.current.timestamp = timestamp;\n renderKeyTrigger([\"timestamp\"]);\n },\n clearState: () => {\n state.current = {\n data: null,\n extra: null,\n connected: false,\n connecting: false,\n timestamp: null,\n };\n renderKeyTrigger(Object.keys(state.current) as (keyof UseSocketStateType<Socket, DataType>)[]);\n },\n };\n\n const callbacks = {\n onConnected: (callback: VoidFunction) => {\n onConnectedCallback.current = callback;\n },\n onDisconnected: (callback: VoidFunction) => {\n onDisconnectCallback.current = callback;\n },\n onError: <ErrorType = Event>(callback: (event: ErrorType) => void) => {\n onErrorCallback.current = callback;\n },\n onConnecting: (callback: VoidFunction) => {\n onConnectingCallback.current = callback;\n },\n onReconnecting: (callback: (data: { attempts: number }) => void) => {\n onReconnectingCallback.current = callback;\n },\n onReconnectingFailed: (callback: (data: { attempts: number }) => void) => {\n onReconnectingFailedCallback.current = callback;\n },\n };\n\n // ******************\n // Hook to events\n // ******************\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without any subscriptions\n useEffect(() => {\n // Catch up with anything that happened between the render and the subscription\n if (state.current.connected !== socket.adapter.connected) {\n actions.setConnected(socket.adapter.connected);\n }\n if (state.current.connecting !== socket.adapter.connecting) {\n actions.setConnecting(socket.adapter.connecting);\n }\n\n const umountOnError = socket.events.onError((event) => {\n onErrorCallback.current?.(event);\n });\n const umountOnConnecting = socket.events.onConnecting(({ connecting }) => {\n actions.setConnecting(connecting);\n onConnectingCallback.current?.();\n });\n const umountOnOpen = socket.events.onConnected(() => {\n actions.setConnected(true);\n onConnectedCallback.current?.();\n });\n const umountOnClose = socket.events.onDisconnected(() => {\n actions.setConnected(false);\n onDisconnectCallback.current?.();\n });\n const umountOnReconnecting = socket.events.onReconnecting(({ attempts }) => {\n onReconnectingCallback.current?.({ attempts });\n });\n const umountOnReconnectingFailed = socket.events.onReconnectingFailed(({ attempts }) => {\n onReconnectingFailedCallback.current?.({ attempts });\n });\n\n return () => {\n umountOnError();\n umountOnConnecting();\n umountOnOpen();\n umountOnClose();\n umountOnReconnecting();\n umountOnReconnectingFailed();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [socket]);\n\n const getState = () => state.current;\n\n return [state.current, actions, callbacks, { setRenderKey, getState, rerender: emitChange }] as const;\n};\n","import type { SocketInstance } from \"@hyper-fetch/sockets\";\n\nimport type { UseSocketStateType } from \"./use-socket-state.types\";\n\nexport const initialSocketState: UseSocketStateType<SocketInstance> = {\n data: null,\n extra: null,\n connected: false,\n connecting: false,\n timestamp: null,\n};\n","import React, { useContext, useMemo, useState } from \"react\";\n\nimport type { ProviderProps, ProviderValueType } from \"./provider.types\";\n\nconst ConfigContext = React.createContext<ProviderValueType>({\n config: {},\n setConfig: () => null,\n});\n\n/**\n * Provider with configuration for hooks\n * @param options\n * @returns\n */\nexport const Provider = ({ children, config }: ProviderProps) => {\n const [currentConfig, setConfig] = useState(config || {});\n\n const value = useMemo(() => {\n const contextValue: ProviderValueType = { config: currentConfig, setConfig };\n return contextValue;\n }, [currentConfig]);\n\n return <ConfigContext.Provider value={value}>{children}</ConfigContext.Provider>;\n};\n\n/**\n * Hook to allow reading current context config\n * @returns\n */\nexport const useProvider = (): ProviderValueType => {\n const config = useContext(ConfigContext);\n return config;\n};\n","import { useDidUpdate, useDidMount, useWillUnmount } from \"@better-hooks/lifecycle\";\nimport { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n ClientInstance,\n RequestInstance,\n ExtractAdapterStatusType,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ExtractErrorType,\n ExtractResponseType,\n} from \"@hyper-fetch/core\";\nimport { scopeKey } from \"@hyper-fetch/core\";\nimport { useRequestEvents, useTrackedState } from \"helpers\";\nimport type { UseFetchOptionsType, UseFetchReturnType } from \"hooks/use-fetch\";\nimport { useFetchDefaultOptions } from \"hooks/use-fetch\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\nimport { isSameScope } from \"utils/scope.utils\";\n\ntype SuspenseEntry = { promise: Promise<void>; resolve: () => void; cleanup: () => void };\ntype SuspenseResult = { data: any; error: any; status: any; extra: any; success: boolean };\ntype SuspenseStore = { promises: Map<string, SuspenseEntry>; results: Map<string, SuspenseResult> };\n\n// Kept per client and keyed by the scoped cache key, so clients and scopes sharing a cache key never\n// wait on or receive each other's suspense results\nconst suspenseStores = new WeakMap<ClientInstance, SuspenseStore>();\n\n// Data received this recently is not refetched when a suspended component mounts\nconst suspenseFreshTime = 1000;\n\nconst getSuspenseStore = (client: ClientInstance): SuspenseStore => {\n let store = suspenseStores.get(client);\n if (!store) {\n store = { promises: new Map(), results: new Map() };\n suspenseStores.set(client, store);\n }\n return store;\n};\n\n/**\n * This hook aims to retrieve data from the server. It automatically fetches on mount and\n * refetches based on dependencies, with support for caching, polling, and suspense.\n * @param request Request instance\n * @param options Hook options\n * @returns\n */\nexport const useFetch = <R extends RequestInstance, TSelected = ExtractResponseType<R>>(\n request: R,\n options?: UseFetchOptionsType<R, TSelected>,\n): UseFetchReturnType<R, TSelected> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const {\n suspense,\n dependencies,\n disabled,\n dependencyTracking,\n revalidate,\n initialResponse,\n keepPreviousData,\n refresh,\n refreshTime,\n refetchBlurred,\n refetchOnBlur,\n refetchOnFocus,\n refetchOnReconnect,\n bounce,\n bounceType,\n bounceTime,\n bounceTimeout,\n deepCompare,\n structuralSharing,\n throwOnError,\n } = {\n ...useFetchDefaultOptions,\n ...globalConfig.useFetchConfig,\n ...options,\n };\n\n const updateKey = JSON.stringify(request.toJSON());\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({ interval: bounceTime, timeout: bounceTimeout });\n const refreshDebounce = useDebounce({ delay: refreshTime });\n\n const { cacheKey, queryKey, client } = request;\n const { cache, fetchDispatcher: dispatcher, appManager, loggerManager } = client;\n\n const ignoreReact18DoubleRender = useRef(true);\n const resolvedBySuspense = useRef(false);\n const logger = useRef(loggerManager.initialize(client, \"useFetch\")).current;\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n /**\n * State handler with optimization for re-rendering, that hooks into the cache state and dispatchers queues\n */\n const [\n state,\n actions,\n { setRenderKey, setCacheData, getStaleStatus, getIsDataProcessing, selectData, getResponseDetails },\n ] = useTrackedState<R, TSelected>({\n logger,\n request: request as unknown as R,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n keepPreviousData,\n disabled,\n revalidate,\n select: options?.select,\n structuralSharing,\n });\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [callbacks, listeners] = useRequestEvents<R>({\n logger,\n actions,\n request: request as unknown as R,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners, clearCacheDataListener } = listeners;\n\n // ******************\n // Fetching\n // ******************\n const handleFetch = (options?: { force?: boolean }) => {\n if (!disabled) {\n logger.debug({ title: `Fetching data`, type: \"system\", extra: { request } });\n // A forced fetch must not be deduplicated into an already running request: that request\n // started earlier, so its response can be older than the state that prompted the call.\n // Manual refetch() promises data at least as fresh as the moment it was called.\n const requestToAdd = options?.force ? request.setDeduplicate(false) : request;\n dispatcher.add(requestToAdd as unknown as R);\n } else {\n logger.debug({ title: `Cannot add to fetch queue`, type: \"system\", extra: { disabled } });\n }\n };\n\n // ******************\n // Refreshing\n // ******************\n\n function handleRefresh() {\n if (!refresh || disabled) {\n refreshDebounce.reset();\n return;\n }\n\n refreshDebounce.debounce(() => {\n const isBlurred = !appManager.isFocused;\n\n // If window tab is not active should we refresh the cache\n const scopedQueryKey = scopeKey(request.queryKey, request.scope);\n const isFetching = dispatcher.hasRunningRequests(scopedQueryKey);\n const isQueued = dispatcher.getIsActiveQueue(scopedQueryKey);\n const isActive = isFetching || isQueued;\n const canRefreshBlurred = isBlurred && refetchBlurred && !isActive;\n const canRefreshFocused = !isBlurred && !isActive;\n\n if (canRefreshBlurred || canRefreshFocused) {\n handleFetch();\n logger.debug({ title: `Performing refresh request`, type: \"system\", extra: { request } });\n }\n\n // Start new refresh counter\n handleRefresh();\n });\n }\n\n const refetch = () => {\n handleFetch({ force: true });\n handleRefresh();\n };\n\n // ******************\n // Fetching lifecycle\n // ******************\n\n // This help us to check for currently running requests\n const getIsFetchingIdentity = () => {\n // We need to check if the queryKey have the same cacheKey elements ongoing\n return dispatcher\n .getRunningRequests(scopeKey(queryKey, request.scope))\n .some((running) => running.request.cacheKey === cacheKey);\n };\n\n /**\n * A suspended component mounts right after its own request resolved - fetching again on mount would\n * duplicate that request. Data received within the last moment counts as fresh, like the minimal stale time\n * applied by other suspense-enabled libraries.\n */\n const getHasJustResolvedSuspense = () => {\n if (!suspense) {\n return false;\n }\n if (resolvedBySuspense.current) {\n return true;\n }\n const cacheData = cache.get(scopeKey(cacheKey, request.scope));\n return !!cacheData && Date.now() - cacheData.responseTimestamp < suspenseFreshTime;\n };\n\n const initialFetchData = () => {\n if (getHasJustResolvedSuspense()) {\n return;\n }\n const hasStaleData = getStaleStatus();\n const isFetching = getIsFetchingIdentity();\n if ((revalidate || hasStaleData) && !isFetching) {\n handleFetch();\n }\n };\n\n const updateFetchData = () => {\n const hasStaleData = getStaleStatus();\n const shouldUpdate = !revalidate ? hasStaleData : true;\n /**\n * This is a hack to avoid double rendering in React 18\n * It renders initial mount event and allow us to consume only hook updates\n */\n if (!ignoreReact18DoubleRender.current && shouldUpdate) {\n /**\n * While debouncing we need to make sure that first request is not debounced when the cache is not available\n * This way it will not wait for debouncing but fetch data right away\n */\n if (bounce) {\n logger.debug({ title: `Bounce request with ${bounceType}`, type: \"system\", extra: { queryKey, request } });\n bounceFunction(() => handleFetch());\n } else {\n handleFetch();\n }\n } else {\n ignoreReact18DoubleRender.current = false;\n }\n };\n\n // ******************\n // Events\n // ******************\n\n const handleMountEvents = () => {\n addCacheDataListener(request as unknown as R);\n addLifecycleListeners(request as unknown as R);\n\n const focusUnmount = appManager.events.onFocus(() => {\n if (refetchOnFocus && !disabled) {\n handleFetch();\n handleRefresh();\n }\n });\n const blurUnmount = appManager.events.onBlur(() => {\n if (refetchOnBlur && !disabled) {\n handleFetch();\n handleRefresh();\n }\n });\n const onlineUnmount = appManager.events.onOnline(() => {\n if (refetchOnReconnect && !disabled) {\n handleFetch();\n handleRefresh();\n }\n });\n\n const invalidateUnmount = cache.events.onInvalidateByKey(cacheKey, handleFetch);\n const deletionUnmount = cache.events.onDeleteByKey(cacheKey, handleFetch);\n\n const unmount = () => {\n clearCacheDataListener();\n focusUnmount();\n blurUnmount();\n onlineUnmount();\n invalidateUnmount();\n deletionUnmount();\n };\n\n return unmount;\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n /**\n * Initialization of the events related to data exchange with cache and queue\n * This allows to share the state with other hooks and keep it related\n */\n useDidUpdate(handleMountEvents, [updateKey, disabled], true);\n\n /**\n * Initial fetch triggered once data is stale or we use the refetch strategy\n */\n useDidMount(initialFetchData);\n\n /**\n * Fetching logic for updates handling\n */\n useDidUpdate(updateFetchData, [updateKey, disabled, ...dependencies], true);\n\n /**\n * Refresh lifecycle handler\n */\n useDidUpdate(handleRefresh, [updateKey, ...dependencies, disabled, refresh, refreshTime], true);\n\n /**\n * Reset the ignore flag for React 18 strict mode\n */\n useWillUnmount(() => {\n ignoreReact18DoubleRender.current = true;\n });\n\n // ******************\n // Suspense\n // ******************\n if (suspense && !disabled) {\n const { promises: suspensePromiseMap, results: suspenseResultMap } = getSuspenseStore(client);\n const suspenseKey = scopeKey(cacheKey, request.scope);\n\n // Apply any cached suspense result (covers error responses that aren't stored in cache)\n const suspenseResult = suspenseResultMap.get(suspenseKey);\n if (suspenseResult) {\n suspenseResultMap.delete(suspenseKey);\n // Error responses are not cached, so the mount logic cannot see they just arrived\n resolvedBySuspense.current = true;\n if (suspenseResult.data !== null) {\n state.data = selectData(suspenseResult.data);\n }\n if (suspenseResult.error !== null) {\n state.error = suspenseResult.error;\n }\n if (suspenseResult.status !== null) {\n state.status = suspenseResult.status;\n }\n if (suspenseResult.extra !== null) {\n state.extra = suspenseResult.extra;\n }\n state.success = suspenseResult.success;\n // The response has arrived - nothing is loading unless another request for this key is running\n state.loading = dispatcher.hasRunningRequests(scopeKey(queryKey, request.scope));\n }\n\n const hasData = state.data !== null || state.error !== null;\n\n if (!hasData) {\n let entry = suspensePromiseMap.get(suspenseKey);\n if (!entry) {\n let resolvePromise: () => void;\n const promise = new Promise<void>((r) => {\n resolvePromise = r;\n });\n\n // Cache events are emitted by the logical cacheKey - skip data of other scopes\n const unsubscribe = cache.events.onDataByKey(cacheKey, (cacheData: any) => {\n if (!isSameScope(cacheData.scope, request.scope)) {\n return;\n }\n suspenseResultMap.set(suspenseKey, {\n data: cacheData.data ?? null,\n error: cacheData.error ?? null,\n status: cacheData.status ?? null,\n extra: cacheData.extra ?? null,\n success: cacheData.success ?? false,\n });\n resolvePromise();\n unsubscribe();\n suspensePromiseMap.delete(suspenseKey);\n });\n\n entry = { promise, resolve: resolvePromise!, cleanup: unsubscribe };\n suspensePromiseMap.set(suspenseKey, entry);\n }\n\n // Ensure the request is dispatched before suspending —\n // effects never run when a component suspends.\n // React may render a suspended component again before the queued request starts running,\n // so a queued request counts as dispatched too.\n const scopedQueryKey = scopeKey(queryKey, request.scope);\n if (!dispatcher.hasRunningRequests(scopedQueryKey) && !dispatcher.getIsActiveQueue(scopedQueryKey)) {\n dispatcher.add(request as unknown as R);\n }\n\n throw entry.promise;\n }\n\n // Data has arrived — clean up any leftover entry\n const entry = suspensePromiseMap.get(suspenseKey);\n if (entry) {\n entry.cleanup();\n suspensePromiseMap.delete(suspenseKey);\n }\n }\n\n // ******************\n // Error boundary\n // ******************\n if (throwOnError) {\n // The error has to be observed to rerender (and throw) even if the component does not read it\n setRenderKey(\"error\");\n setRenderKey(\"loading\");\n setRenderKey(\"success\");\n\n const details = getResponseDetails();\n // Errors of retried, canceled or offline (re-queued) requests are not final\n const isSettled = !state.loading && !details?.willRetry && !details?.isCanceled && !details?.isOffline;\n const hasError = !state.success && state.error !== null && state.error !== undefined;\n\n if (isSettled && hasError) {\n const error = state.error as ExtractErrorType<R>;\n if (typeof throwOnError === \"function\" ? throwOnError(error) : throwOnError) {\n throw error;\n }\n }\n }\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"loading\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n error: state.error,\n loading: state.loading,\n status: state.status as ExtractAdapterStatusType<ExtractAdapterType<R>>,\n success: state.success,\n extra: state.extra as ExtractAdapterExtraType<ExtractAdapterType<R>>,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n bounce: getBounceData(bounceData),\n ...actions,\n ...(callbacks as any),\n refetch,\n },\n trackedKeys,\n setRenderKey,\n ) as UseFetchReturnType<R, TSelected>;\n};\n","export const getRefreshTime = (refreshTime: number, dataTimestamp?: Date) => {\n if (dataTimestamp) {\n const timeDiff = Date.now() - +dataTimestamp;\n return timeDiff < refreshTime ? refreshTime - timeDiff : refreshTime;\n }\n return refreshTime;\n};\n","import type { RequestInstance, RequiredKeys } from \"@hyper-fetch/core\";\nimport { Time } from \"@hyper-fetch/core\";\nimport type { UseFetchOptionsType } from \"hooks/use-fetch\";\n\ntype DefaultOptionsType = RequiredKeys<Omit<UseFetchOptionsType<RequestInstance>, \"initialResponse\" | \"select\">> & {\n initialResponse: null;\n};\n\nexport const useFetchDefaultOptions: DefaultOptionsType = {\n suspense: false,\n dependencies: [],\n disabled: false,\n dependencyTracking: true,\n revalidate: true,\n initialResponse: null,\n keepPreviousData: \"auto\",\n refresh: false,\n refreshTime: Time.HOUR,\n refetchBlurred: true,\n refetchOnBlur: false,\n refetchOnFocus: false,\n refetchOnReconnect: false,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n bounceTimeout: 400,\n deepCompare: true,\n structuralSharing: true,\n throwOnError: false,\n};\n","import { Time } from \"@hyper-fetch/core\";\n\nimport type { UseInfiniteFetchConfigType } from \"./use-infinite-fetch.types\";\n\nexport const useInfiniteFetchDefaultOptions = {\n suspense: false,\n throwOnError: false,\n dependencies: [],\n disabled: false,\n dependencyTracking: true,\n // Pages restored from the cache are refetched only once they are stale\n revalidate: false,\n keepPreviousData: \"auto\",\n refresh: false,\n refreshTime: Time.HOUR,\n refetchBlurred: true,\n refetchOnBlur: false,\n refetchOnFocus: false,\n refetchOnReconnect: false,\n structuralSharing: true,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n bounceTimeout: 400,\n} satisfies Required<UseInfiniteFetchConfigType>;\n","import type { RequestInstance } from \"@hyper-fetch/core\";\nimport { getErrorMessage, mapResponseForSend, scopeKey } from \"@hyper-fetch/core\";\n\ntype LoadPageOptions = {\n request: RequestInstance;\n /** Skips requests started before this fetch was asked for */\n force: boolean;\n /** Filled with the functions stopping this fetch */\n cancellers: Set<VoidFunction>;\n isCancelled: () => boolean;\n};\n\n/**\n * Cancelled pages are not failures: the list simply did not need them anymore\n */\nexport const isCancelledResponse = (response: any) => {\n const message = response?.error?.message;\n return (\n !response?.success &&\n (message === getErrorMessage(\"abort\").message || message === getErrorMessage(\"deleted\").message)\n );\n};\n\n/**\n * Joins a request started elsewhere. Cancelling only stops waiting, the request belongs to someone else.\n */\nconst waitForResponse = (request: RequestInstance, requestId: string, cancellers: Set<VoidFunction>) => {\n const { requestManager } = request.client;\n\n return new Promise<any>((resolve) => {\n const finish = (response: any) => {\n unmountResponse();\n unmountRemove();\n cancellers.delete(cancel);\n resolve(response);\n };\n const cancel = () => finish(null);\n const unmountResponse = requestManager.events.onResponseById(requestId, ({ response, details }) => {\n if (response.success || (!details.willRetry && !details.isOffline)) {\n finish(response);\n }\n });\n const unmountRemove = requestManager.events.onRemoveById(requestId, cancel);\n\n cancellers.add(cancel);\n });\n};\n\nconst sendPage = async ({ request, force, cancellers }: LoadPageOptions) => {\n const { fetchDispatcher } = request.client;\n const pageRequest = force ? request.setDeduplicate(false) : request;\n let sentRequestId = \"\";\n\n const cancel = () => {\n fetchDispatcher.delete(\n scopeKey(request.queryKey, request.scope),\n sentRequestId,\n scopeKey(request.abortKey, request.scope),\n );\n };\n cancellers.add(cancel);\n\n const response = await (pageRequest as RequestInstance).send({\n dispatcherType: \"fetch\",\n onBeforeSent: ({ requestId }: { requestId: string }) => {\n sentRequestId = requestId;\n },\n } as any);\n\n cancellers.delete(cancel);\n return response;\n};\n\n/**\n * Loads a page, reusing the request already running for it\n */\nexport const loadPage = async (options: LoadPageOptions) => {\n const { request, force, cancellers, isCancelled } = options;\n\n // A forced fetch must not reuse a request started before it was asked for\n if (!force) {\n const running = request.client.fetchDispatcher\n .getRunningRequests(scopeKey(request.queryKey, request.scope))\n .find((item) => item.request.cacheKey === request.cacheKey);\n\n if (running) {\n const response = await waitForResponse(request, running.requestId, cancellers);\n if (response) {\n return mapResponseForSend(request, response);\n }\n if (isCancelled()) {\n return null;\n }\n }\n }\n\n return sendPage(options);\n};\n","import type {\n CacheValueType,\n ClientInstance,\n PaginationConfig,\n PaginationPageContext,\n RequestInstance,\n} from \"@hyper-fetch/core\";\nimport {\n getCachedPages,\n getHasNextPage,\n getHasPreviousPage,\n getInitialPageParam,\n getNextPageParam,\n getPageItems,\n getPageRequest,\n getPageTotal,\n getPaginationMode,\n getPreviousPageParam,\n replaceEqualDeep,\n scopeKey,\n stringifyKey,\n} from \"@hyper-fetch/core\";\nimport { isStaleCacheData } from \"helpers/use-tracked-state/use-tracked-state.utils\";\nimport { pickInitialCacheData } from \"hydrate/hydrate.utils\";\n\nimport { isCancelledResponse, loadPage } from \"./use-infinite-fetch.requests\";\nimport type {\n FetchedPage,\n InfinitePage,\n InfiniteSnapshot,\n InfiniteStoreOptions,\n Operation,\n OperationKind,\n} from \"./use-infinite-fetch.store.types\";\nimport type { InfinitePageEvent } from \"./use-infinite-fetch.types\";\n\n// Render and commit are separate steps, a store waits this long for the component that created it\nconst unusedStoreTime = 1000;\n\nconst stores = new WeakMap<ClientInstance, Map<string, InfiniteStore>>();\n\nconst getStores = (client: ClientInstance) => {\n let clientStores = stores.get(client);\n if (!clientStores) {\n clientStores = new Map();\n stores.set(client, clientStores);\n }\n return clientStores;\n};\n\nconst isSameSnapshot = (a: InfiniteSnapshot, b: InfiniteSnapshot) => {\n return (Object.keys(a) as (keyof InfiniteSnapshot)[]).every((key) => a[key] === b[key]);\n};\n\n/**\n * State of a single list. Hooks showing the same list share one store, so they stay in sync and never request\n * the same page twice. Pages are ordinary requests under their own cache keys - nothing extra is stored.\n *\n * Fetches run one at a time: every page depends on the list as it was when its value was computed.\n */\nexport class InfiniteStore {\n private listeners = new Set<VoidFunction>();\n private pageListeners = new Set<(event: InfinitePageEvent<any>) => void>();\n private pages: InfinitePage[] = [];\n // Values of pages dropped by `maxPages`, a cursor list may have no other way of going back to them\n private droppedParams: unknown[] = [];\n private queue: Operation[] = [];\n private running: Operation | null = null;\n private cancellers = new Set<VoidFunction>();\n // Pages being refetched - their cache events wait for the whole list to be swapped at once\n private refetchedKeys = new Set<string>();\n private unmountCacheListeners: VoidFunction | null = null;\n private unusedTimer: ReturnType<typeof setTimeout> | null = null;\n private started = false;\n private settled = false;\n private firstFetch: Promise<any> = Promise.resolve(null);\n private nextPageError = false;\n private previousPageError = false;\n private result: { error: any; status: any; extra: any; success: boolean } = {\n error: null,\n status: null,\n extra: null,\n success: false,\n };\n private snapshot: InfiniteSnapshot;\n\n constructor(\n readonly key: string,\n private options: InfiniteStoreOptions,\n ) {\n getPaginationMode(options.pagination);\n this.restorePages();\n this.snapshot = this.createSnapshot();\n }\n\n // ******************\n // State\n // ******************\n\n getSnapshot = () => this.snapshot;\n\n subscribe = (listener: VoidFunction) => {\n this.listeners.add(listener);\n if (this.listeners.size === 1) {\n this.attach();\n }\n\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) {\n this.detach();\n }\n };\n };\n\n onPage = (listener: (event: InfinitePageEvent<any>) => void) => {\n this.pageListeners.add(listener);\n return () => {\n this.pageListeners.delete(listener);\n };\n };\n\n /** Callbacks can capture values of the latest render */\n setPagination = (pagination: PaginationConfig) => {\n this.options.pagination = pagination;\n };\n\n hasPages = () => this.pages.length > 0;\n\n // ******************\n // Actions\n // ******************\n\n /**\n * Loads the list when it is first needed. Safe to call many times.\n */\n start = ({ revalidate }: { revalidate?: boolean } = {}) => {\n if (this.started) {\n return this.firstFetch;\n }\n this.started = true;\n\n if (this.pages.length === 0) {\n this.firstFetch = this.schedule(\"initial\");\n } else if (revalidate || this.getHasStalePages()) {\n this.revalidate();\n } else {\n this.settled = true;\n }\n this.publish();\n return this.firstFetch;\n };\n\n fetchNextPage = () => this.fetchDirection(\"next\");\n\n fetchPreviousPage = () => this.fetchDirection(\"previous\");\n\n /**\n * Refetch asked for by the user: anything already refetching is older than this call and gets replaced.\n */\n refetch = () => {\n if (this.pages.length === 0) {\n return this.revalidate();\n }\n this.getOperations(\"refetch\").forEach(this.cancelOperation);\n return this.schedule(\"refetch\");\n };\n\n /**\n * Automatic refetch: joins the one in progress\n */\n revalidate = () => {\n const kind = this.pages.length > 0 ? \"refetch\" : \"initial\";\n return this.getOperations(kind)[0]?.promise ?? this.schedule(kind);\n };\n\n reset = () => {\n this.cancelOperations();\n const startParam = stringifyKey(getInitialPageParam(this.options.request, this.options.pagination));\n\n this.pages = this.pages.filter((page) => stringifyKey(page.param) === startParam);\n this.droppedParams = [];\n this.nextPageError = false;\n this.previousPageError = false;\n this.settled = false;\n this.started = true;\n\n return this.schedule(this.pages.length > 0 ? \"refetch\" : \"initial\");\n };\n\n abort = () => {\n this.cancelOperations();\n this.settled = true;\n this.publish();\n };\n\n /** The list is no longer on screen - stop fetching its pages */\n cancelIfUnused = () => {\n if (this.listeners.size === 0) {\n this.cancelOperations();\n }\n };\n\n /** A store that threw its error starts over when the Error Boundary renders the component again */\n evictSoon = () => {\n setTimeout(this.evict, 0);\n };\n\n /** Stores created while rendering are removed when the component never mounts */\n scheduleUnusedCheck = () => {\n this.unusedTimer = setTimeout(() => {\n this.unusedTimer = null;\n if (this.running || this.queue.length > 0) {\n this.scheduleUnusedCheck();\n } else {\n this.evict();\n }\n }, unusedStoreTime);\n };\n\n // ******************\n // Operations\n // ******************\n\n private fetchDirection = (kind: \"next\" | \"previous\") => {\n if (this.pages.length === 0) {\n return this.getOperations(\"initial\")[0]?.promise ?? Promise.resolve(null);\n }\n const scheduled = this.getOperations(kind)[0];\n if (scheduled) {\n return scheduled.promise;\n }\n if (kind === \"next\" ? this.getNextParam() === undefined : !this.getPreviousTarget()) {\n return Promise.resolve(null);\n }\n if (kind === \"next\") {\n this.nextPageError = false;\n } else {\n this.previousPageError = false;\n }\n return this.schedule(kind);\n };\n\n private getOperations = (kind: OperationKind) => {\n const operations = this.running ? [this.running, ...this.queue] : this.queue;\n return operations.filter((operation) => operation.kind === kind && !operation.cancelled);\n };\n\n private schedule = (kind: OperationKind) => {\n const operation = { kind, cancelled: false } as Operation;\n operation.promise = new Promise<any>((resolve) => {\n operation.resolve = resolve;\n });\n\n if (kind === \"initial\") {\n this.settled = false;\n }\n this.queue.push(operation);\n this.pump();\n this.publish();\n return operation.promise;\n };\n\n private pump = async () => {\n if (this.running) {\n return;\n }\n const operation = this.queue.shift();\n if (!operation) {\n return;\n }\n\n this.running = operation;\n const previousPages = this.pages;\n let response = null;\n try {\n response = await this.perform(operation);\n } catch (error) {\n this.setFailure(error);\n }\n this.keepValidPages(previousPages);\n this.running = null;\n this.refetchedKeys.clear();\n\n if ((operation.kind === \"initial\" || operation.kind === \"refetch\") && !operation.cancelled) {\n this.settled = true;\n }\n\n operation.resolve(operation.cancelled ? null : response);\n this.pump();\n this.publish();\n };\n\n private cancelOperation = (operation: Operation) => {\n operation.cancelled = true;\n if (operation === this.running) {\n this.cancellers.forEach((cancel) => cancel());\n this.cancellers.clear();\n this.refetchedKeys.clear();\n } else {\n this.queue = this.queue.filter((item) => item !== operation);\n operation.resolve(null);\n }\n };\n\n private cancelOperations = () => {\n [...this.queue, ...(this.running ? [this.running] : [])].forEach(this.cancelOperation);\n };\n\n private perform = (operation: Operation) => {\n switch (operation.kind) {\n case \"next\": {\n return this.performNext(operation);\n }\n case \"previous\": {\n return this.performPrevious(operation);\n }\n case \"refetch\": {\n return this.performRefetch(operation);\n }\n default: {\n return this.performInitial(operation);\n }\n }\n };\n\n private performInitial = async (operation: Operation) => {\n const { request, pagination } = this.options;\n const fetched = await this.fetchPage(operation, getInitialPageParam(request, pagination));\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n if (fetched.response.success) {\n this.pages = [this.createPage(fetched)];\n }\n return fetched.response;\n };\n\n private performNext = async (operation: Operation) => {\n const param = this.getNextParam();\n if (param === undefined) {\n return null;\n }\n\n const fetched = await this.fetchPage(operation, param);\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n this.nextPageError = !fetched.response.success;\n if (fetched.response.success) {\n this.pages = [...this.pages, this.createPage(fetched)];\n this.trimPages(\"start\");\n }\n return fetched.response;\n };\n\n private performPrevious = async (operation: Operation) => {\n const target = this.getPreviousTarget();\n if (!target) {\n return null;\n }\n\n const { param } = target;\n const fetched = await this.fetchPage(operation, param);\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n this.previousPageError = !fetched.response.success;\n if (fetched.response.success) {\n if (target.isDropped) {\n this.droppedParams = this.droppedParams.slice(0, -1);\n }\n this.pages = [this.createPage(fetched), ...this.pages];\n this.trimPages(\"end\");\n }\n return fetched.response;\n };\n\n private performRefetch = async (operation: Operation) => {\n const current = this.pages;\n current.forEach((page) => this.refetchedKeys.add(page.storageKey));\n\n return getPaginationMode(this.options.pagination) === \"cursor\"\n ? this.refetchInOrder(operation, current)\n : this.refetchAtOnce(operation, current);\n };\n\n /**\n * Page and offset values do not depend on other pages, so they can be requested together\n */\n private refetchAtOnce = async (operation: Operation, current: InfinitePage[]) => {\n const results = await Promise.all(current.map((page) => this.fetchPage(operation, page.param, true)));\n if (operation.cancelled) {\n return null;\n }\n\n const failed = results.find((fetched) => fetched && !fetched.response.success);\n const last = failed ?? results.findLast(Boolean);\n\n this.pages = current.map((page, index) => {\n const fetched = results[index];\n return fetched?.response.success ? this.createPage(fetched) : page;\n });\n if (last) {\n this.setResult(last.response);\n }\n return last?.response ?? null;\n };\n\n /**\n * Every cursor comes from the page before it, and the fresh data can hold different cursors than before.\n * The list is replaced only when the whole chain arrived, a failure leaves it as it was.\n */\n private refetchInOrder = async (operation: Operation, current: InfinitePage[]) => {\n const fresh: InfinitePage[] = [];\n let param = current[0].param;\n let response = null;\n\n while (fresh.length < current.length) {\n // Each request needs the response of the previous one\n // eslint-disable-next-line no-await-in-loop\n const fetched = await this.fetchPage(operation, param, true);\n if (!fetched) {\n return null;\n }\n\n response = fetched.response;\n this.setResult(response);\n if (!response.success) {\n return response;\n }\n\n const page = this.createPage(fetched);\n fresh.push(page);\n\n const context = this.getContext(page, fresh);\n if (!getHasNextPage(context)) {\n break;\n }\n param = getNextPageParam(context);\n }\n\n this.pages = fresh;\n return response;\n };\n\n private trimPages = (side: \"start\" | \"end\") => {\n const { maxPages } = this.options;\n if (!maxPages || this.pages.length <= maxPages) {\n return;\n }\n\n const overflow = this.pages.length - maxPages;\n if (side === \"start\") {\n this.droppedParams = [...this.droppedParams, ...this.pages.slice(0, overflow).map((page) => page.param)];\n this.pages = this.pages.slice(overflow);\n } else {\n this.pages = this.pages.slice(0, maxPages);\n }\n };\n\n // ******************\n // Requests\n // ******************\n\n private fetchPage = async (operation: Operation, param: unknown, force = false): Promise<FetchedPage | null> => {\n const request = getPageRequest(this.options.request, this.options.pagination, param);\n const response = await loadPage({\n request,\n force,\n cancellers: this.cancellers,\n isCancelled: () => operation.cancelled,\n });\n\n if (operation.cancelled || !response || isCancelledResponse(response)) {\n return null;\n }\n\n this.pageListeners.forEach((listener) => listener({ response, request, param }));\n return { param, request, response };\n };\n\n // ******************\n // Pages\n // ******************\n\n private getContext = (page: InfinitePage, pages: InfinitePage[] = this.pages): PaginationPageContext => ({\n request: this.options.request,\n pagination: this.options.pagination,\n data: page.data,\n param: page.param,\n pages: pages.map((item) => item.data),\n });\n\n private getNextParam = () => {\n const last = this.pages.at(-1);\n if (!last || !getHasNextPage(this.getContext(last))) {\n return;\n }\n return getNextPageParam(this.getContext(last));\n };\n\n // The first page of a cursor list has no cursor, so \"no value\" cannot mean \"no page\"\n private getPreviousTarget = (): { param: unknown; isDropped: boolean } | null => {\n const first = this.pages[0];\n if (!first) {\n return null;\n }\n if (this.droppedParams.length > 0) {\n return { param: this.droppedParams.at(-1), isDropped: true };\n }\n if (getHasPreviousPage(this.getContext(first))) {\n return { param: getPreviousPageParam(this.getContext(first)), isDropped: false };\n }\n return null;\n };\n\n private getHasStalePages = () => {\n return this.pages.some((page) => {\n const value = this.readValue(page.request);\n return !value || isStaleCacheData(value.staleTime, value.responseTimestamp);\n });\n };\n\n private readValue = (request: RequestInstance) => {\n const { client } = request;\n const storageKey = scopeKey(request.cacheKey, request.scope);\n return pickInitialCacheData<CacheValueType>(\n client.cache.get(storageKey),\n this.options.hydration?.get(client, storageKey),\n );\n };\n\n /** Responses go through the response mapper of the request, an asynchronous one cannot be read synchronously */\n private mapValue = (request: RequestInstance, value: CacheValueType) => {\n const mapped: any = request.unstable_responseMapper ? request.unstable_responseMapper(value as any) : value;\n return mapped instanceof Promise ? undefined : mapped;\n };\n\n private createPage = ({ param, request, response }: FetchedPage): InfinitePage => {\n // Reading the cache keeps changes made after the response arrived, like optimistic updates\n const value = this.readValue(request);\n const cached =\n value && value.responseTimestamp >= response.responseTimestamp ? this.mapValue(request, value) : null;\n\n return {\n param,\n request,\n storageKey: scopeKey(request.cacheKey, request.scope),\n data: cached?.success ? cached.data : response.data,\n responseTimestamp: response.responseTimestamp,\n };\n };\n\n private restorePages = () => {\n const { request, pagination, maxPages } = this.options;\n\n this.pages = getCachedPages({\n request,\n pagination,\n maxPages,\n read: (pageRequest) => {\n const value = this.readValue(pageRequest);\n const mapped = value ? this.mapValue(pageRequest, value) : null;\n return mapped?.success ? { ...value, data: mapped.data } : null;\n },\n }).map(({ param, request: pageRequest, value }) => ({\n param,\n request: pageRequest,\n storageKey: scopeKey(pageRequest.cacheKey, pageRequest.scope),\n data: value.data,\n responseTimestamp: Number(value.responseTimestamp),\n }));\n };\n\n /** Picks up everything that happened between rendering and mounting */\n private syncPages = () => {\n if (this.running || this.queue.length > 0) {\n return;\n }\n if (this.pages.length === 0) {\n this.restorePages();\n return;\n }\n\n this.pages = this.pages.map((page) => {\n const value = this.readValue(page.request);\n const mapped = value ? this.mapValue(page.request, value) : null;\n return mapped?.success\n ? { ...page, data: mapped.data, responseTimestamp: Number(value?.responseTimestamp) }\n : page;\n });\n };\n\n private setFailure = (error: unknown) => {\n this.result = { error, status: null, extra: null, success: false };\n };\n\n /**\n * Pagination callbacks read the data of every page. When one of them throws, the page that caused it is not\n * used and the error is reported instead of breaking the list.\n */\n private keepValidPages = (previousPages: InfinitePage[]) => {\n try {\n this.createSnapshot();\n } catch (error) {\n this.pages = previousPages;\n this.setFailure(error);\n }\n };\n\n private setResult = (response: any) => {\n this.result = {\n error: response.success ? null : response.error,\n status: response.status,\n extra: response.extra,\n success: response.success,\n };\n };\n\n // ******************\n // Cache\n // ******************\n\n private attach = () => {\n if (this.unusedTimer) {\n clearTimeout(this.unusedTimer);\n this.unusedTimer = null;\n }\n\n const { client } = this.options.request;\n const clientStores = getStores(client);\n if (!clientStores.has(this.key) && client.mode !== \"server\") {\n clientStores.set(this.key, this);\n }\n\n const { cache } = client;\n const unmountData = cache.events.onData(this.handleCacheData);\n const unmountInvalidate = cache.events.onInvalidate(this.handleCacheChange);\n const unmountDelete = cache.events.onDelete(this.handleCacheChange);\n\n this.unmountCacheListeners = () => {\n unmountData();\n unmountInvalidate();\n unmountDelete();\n };\n\n this.syncPages();\n this.publish();\n };\n\n private detach = () => {\n this.unmountCacheListeners?.();\n this.unmountCacheListeners = null;\n this.evict();\n };\n\n private evict = () => {\n if (this.listeners.size > 0) {\n return;\n }\n const clientStores = getStores(this.options.request.client);\n if (clientStores.get(this.key) === this) {\n clientStores.delete(this.key);\n }\n };\n\n private handleCacheData = (value: CacheValueType) => {\n const storageKey = scopeKey(value.cacheKey, value.scope ?? null);\n if (!value.success || this.refetchedKeys.has(storageKey)) {\n return;\n }\n\n const index = this.pages.findIndex((page) => page.storageKey === storageKey);\n const page = this.pages[index];\n const mapped = page ? this.mapValue(page.request, value) : null;\n if (!page || !mapped?.success) {\n return;\n }\n\n const previousPages = this.pages;\n this.pages = this.pages.map((item, itemIndex) => {\n return itemIndex === index\n ? { ...item, data: mapped.data, responseTimestamp: Number(value.responseTimestamp) }\n : item;\n });\n this.keepValidPages(previousPages);\n this.publish();\n };\n\n private hasInvalidation = false;\n\n /**\n * Invalidated data may have changed after a running refetch started, so that refetch is replaced.\n * Invalidating by a pattern reports every key on its own, all of them are handled by one refetch.\n */\n private handleCacheChange = (key: string) => {\n const isLoaded = this.pages.some((page) => page.storageKey === key || page.request.cacheKey === key);\n if (!isLoaded || this.hasInvalidation) {\n return;\n }\n\n this.hasInvalidation = true;\n queueMicrotask(() => {\n this.hasInvalidation = false;\n if (this.listeners.size > 0) {\n this.refetch();\n }\n });\n };\n\n // ******************\n // Snapshot\n // ******************\n\n private createSnapshot = (): InfiniteSnapshot => {\n const { structuralSharing = true } = this.options;\n const previous = this.snapshot as InfiniteSnapshot | undefined;\n const share = <T>(prev: T | undefined, next: T) =>\n structuralSharing && prev ? replaceEqualDeep(prev, next) : next;\n\n const contexts = this.pages.map((page) => this.getContext(page));\n const last = contexts.at(-1);\n const totals = contexts.map(getPageTotal).filter((total) => total !== null);\n const operations = [...this.queue, ...(this.running ? [this.running] : [])].filter((item) => !item.cancelled);\n const isRunning = (kind: OperationKind) => operations.some((item) => item.kind === kind);\n\n return {\n items: share(previous?.items, contexts.flatMap((context) => getPageItems(context))),\n data: share(previous?.data, this.pages.map((page) => page.data)),\n pageParams: share(previous?.pageParams, this.pages.map((page) => page.param)),\n total: totals.length > 0 ? (totals.at(-1) as number) : null,\n hasNextPage: !!last && this.getNextParam() !== undefined,\n hasPreviousPage: !!this.getPreviousTarget(),\n loading: this.pages.length === 0 && !this.settled,\n isFetching: operations.length > 0,\n isRefetching: isRunning(\"refetch\"),\n isFetchingNextPage: isRunning(\"next\"),\n isFetchingPreviousPage: isRunning(\"previous\"),\n isFetchNextPageError: this.nextPageError,\n isFetchPreviousPageError: this.previousPageError,\n ...this.result,\n };\n };\n\n private publish = () => {\n const snapshot = this.createSnapshot();\n if (isSameSnapshot(this.snapshot, snapshot)) {\n return;\n }\n this.snapshot = snapshot;\n this.listeners.forEach((listener) => listener());\n };\n}\n\n/**\n * Returns the store of the list, shared between all the mounted hooks showing it.\n * Server renders never share one: a client can serve many users at the same time.\n */\nexport const getInfiniteStore = (key: string, options: InfiniteStoreOptions) => {\n const { client } = options.request;\n if (client.mode === \"server\" || typeof window === \"undefined\") {\n return new InfiniteStore(key, options);\n }\n\n const clientStores = getStores(client);\n let store = clientStores.get(key);\n if (!store) {\n store = new InfiniteStore(key, options);\n clientStores.set(key, store);\n store.scheduleUnusedCheck();\n }\n return store;\n};\n","import type { RequestInstance } from \"@hyper-fetch/core\";\n\n/**\n * Identity of a list. Everything describing the request takes part in it, so a changed filter, sort, page size\n * or URL param starts a new list without anything having to be listed by hand.\n */\nexport const getInfiniteKey = (request: RequestInstance, pagination: unknown, maxPages?: number) => {\n return JSON.stringify([request.toJSON(), pagination, maxPages ?? null], (_key, value) => {\n return typeof value === \"function\" ? value.toString() : value;\n });\n};\n\n/**\n * Keeps the first occurrence of every item\n */\nexport const getUniqueItems = (items: unknown[], uniqueBy: unknown) => {\n if (uniqueBy === undefined) {\n return items;\n }\n\n const seen = new Set<unknown>();\n return items.filter((item: any) => {\n const identity = typeof uniqueBy === \"function\" ? uniqueBy({ item }) : item?.[uniqueBy as string];\n if (seen.has(identity)) {\n return false;\n }\n seen.add(identity);\n return true;\n });\n};\n\n/**\n * Decides if the previous list stays on screen while the new one loads its first page\n */\nexport const getShouldKeepPreviousList = (\n mode: \"auto\" | \"preserve\" | \"clean\",\n previous: RequestInstance,\n current: RequestInstance,\n) => {\n if (mode === \"auto\") {\n return previous.method === current.method && previous.endpoint === current.endpoint;\n }\n return mode === \"preserve\";\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n ExtractErrorType,\n Pagination,\n PaginationConfig,\n PaginationItem,\n RequestInstance,\n} from \"@hyper-fetch/core\";\nimport { replaceEqualDeep } from \"@hyper-fetch/core\";\nimport { useHydration } from \"hydrate/hydrate\";\nimport { useProvider } from \"provider\";\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\n\nimport { useInfiniteFetchDefaultOptions } from \"./use-infinite-fetch.constants\";\nimport type { InfiniteStore } from \"./use-infinite-fetch.store\";\nimport { getInfiniteStore } from \"./use-infinite-fetch.store\";\nimport type { InfiniteSnapshot } from \"./use-infinite-fetch.store.types\";\nimport type { UseInfiniteFetchOptionsType, UseInfiniteFetchReturnType } from \"./use-infinite-fetch.types\";\nimport { getInfiniteKey, getShouldKeepPreviousList, getUniqueItems } from \"./use-infinite-fetch.utils\";\n\n// What decides about a returned value - the list on screen also depends on the new list still loading\nconst trackedSources: Record<string, (keyof InfiniteSnapshot)[]> = {\n items: [\"items\", \"loading\"],\n pages: [\"data\", \"loading\"],\n pageParams: [\"pageParams\", \"loading\"],\n total: [\"total\", \"loading\"],\n isPreviousData: [\"data\", \"loading\"],\n loading: [\"data\", \"loading\"],\n};\n\nconst trackedKeys = [\n \"items\",\n \"pages\",\n \"pageParams\",\n \"total\",\n \"hasNextPage\",\n \"hasPreviousPage\",\n \"loading\",\n \"isFetching\",\n \"isRefetching\",\n \"isFetchingNextPage\",\n \"isFetchingPreviousPage\",\n \"isFetchNextPageError\",\n \"isFetchPreviousPageError\",\n \"isPreviousData\",\n \"error\",\n \"status\",\n \"extra\",\n \"success\",\n] as const;\n\n/**\n * Loads a list page by page. Say which fields page through the request, and the hook takes care of the rest:\n * every page is a normal request under its own cache key, and the hook glues them together.\n *\n * A changed filter, sort or URL param starts a new list on its own. When to load more is up to you - call\n * `fetchNextPage` from a button, an intersection observer, `onEndReached` or a virtualizer.\n *\n * @param request Request instance\n * @param options Hook options, `pagination` is required\n * @returns\n * @example\n * ```tsx\n * const { items, hasNextPage, fetchNextPage } = useInfiniteFetch(getFeed.setQueryParams({ topic }), {\n * pagination: { cursor: \"cursor\", next: \"nextCursor\", items: \"data\" },\n * });\n * ```\n */\nexport const useInfiniteFetch = <\n R extends RequestInstance,\n const P extends Pagination<R>,\n TSelected = PaginationItem<R, P>[],\n>(\n request: R,\n options: UseInfiniteFetchOptionsType<R, P, TSelected>,\n): UseInfiniteFetchReturnType<R, P, TSelected> => {\n const { config: globalConfig } = useProvider();\n const {\n pagination,\n uniqueBy,\n maxPages,\n select,\n suspense,\n throwOnError,\n dependencies,\n disabled,\n dependencyTracking,\n revalidate,\n keepPreviousData,\n refresh,\n refreshTime,\n refetchBlurred,\n refetchOnBlur,\n refetchOnFocus,\n refetchOnReconnect,\n structuralSharing,\n bounce,\n bounceType,\n bounceTime,\n bounceTimeout,\n } = {\n ...useInfiniteFetchDefaultOptions,\n ...globalConfig.useInfiniteFetchConfig,\n ...options,\n };\n\n const { client } = request;\n const hydration = useHydration();\n\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({ interval: bounceTime, timeout: bounceTimeout });\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n // ******************\n // Store\n // ******************\n\n const key = getInfiniteKey(request, pagination, maxPages);\n const storeRef = useRef<InfiniteStore | null>(null);\n const storeClientRef = useRef(client);\n\n if (!storeRef.current || storeRef.current.key !== key || storeClientRef.current !== client) {\n storeClientRef.current = client;\n storeRef.current = getInfiniteStore(key, {\n request,\n pagination: pagination as PaginationConfig,\n maxPages,\n structuralSharing,\n hydration,\n });\n }\n const store = storeRef.current;\n\n // Rerenders only when something the component reads has changed\n const usedKeys = useRef(new Set<string>()).current;\n const renderedRef = useRef<{ store: InfiniteStore; snapshot: InfiniteSnapshot } | null>(null);\n\n const getSnapshot = () => {\n const next = store.getSnapshot();\n const rendered = renderedRef.current;\n\n if (dependencyTracking && rendered?.store === store) {\n const hasChanged = [...usedKeys].some((usedKey) => {\n const sources = trackedSources[usedKey] ?? [usedKey as keyof InfiniteSnapshot];\n return sources.some((source) => rendered.snapshot[source] !== next[source]);\n });\n if (!hasChanged) {\n return rendered.snapshot;\n }\n }\n\n renderedRef.current = { store, snapshot: next };\n return next;\n };\n\n const snapshot = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);\n\n // ******************\n // Latest values\n // ******************\n\n const callbacks = useRef<{\n onSuccess?: (event: any) => void;\n onError?: (event: any) => void;\n onFinished?: (event: any) => void;\n onReset?: VoidFunction;\n }>({});\n\n const latest = useRef({ disabled, revalidate, refetchOnBlur, refetchOnFocus, refetchOnReconnect });\n latest.current = { disabled, revalidate, refetchOnBlur, refetchOnFocus, refetchOnReconnect };\n\n // ******************\n // Lifecycle\n // ******************\n\n useEffect(() => {\n store.setPagination(pagination as PaginationConfig);\n });\n\n useEffect(() => {\n return store.onPage((event) => {\n if (event.response.success) {\n callbacks.current.onSuccess?.(event);\n } else {\n callbacks.current.onError?.(event);\n }\n callbacks.current.onFinished?.(event);\n });\n }, [store]);\n\n /**\n * A new list stops the pages of the previous one, so a late response never gets in the way\n */\n const mountedStore = useRef<InfiniteStore | null>(null);\n\n useEffect(() => {\n const previous = mountedStore.current;\n mountedStore.current = store;\n\n if (previous && previous !== store) {\n previous.cancelIfUnused();\n callbacks.current.onReset?.();\n }\n if (disabled) {\n return;\n }\n\n if (bounce && previous && previous !== store && !store.hasPages()) {\n bounceFunction(() => store.start({ revalidate: latest.current.revalidate }));\n } else {\n store.start({ revalidate });\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [store, disabled]);\n\n useDidUpdate(() => {\n if (!disabled) {\n store.refetch();\n }\n }, dependencies);\n\n useEffect(() => {\n const { appManager } = client;\n const handle = (option: \"refetchOnBlur\" | \"refetchOnFocus\" | \"refetchOnReconnect\") => () => {\n if (latest.current[option] && !latest.current.disabled) {\n store.revalidate();\n }\n };\n\n const unmountFocus = appManager.events.onFocus(handle(\"refetchOnFocus\"));\n const unmountBlur = appManager.events.onBlur(handle(\"refetchOnBlur\"));\n const unmountOnline = appManager.events.onOnline(handle(\"refetchOnReconnect\"));\n\n return () => {\n unmountFocus();\n unmountBlur();\n unmountOnline();\n };\n }, [client, store]);\n\n useEffect(() => {\n if (!refresh || disabled) {\n return;\n }\n\n const timer = setInterval(() => {\n if (client.appManager.isFocused || refetchBlurred) {\n store.revalidate();\n }\n }, refreshTime);\n\n return () => clearInterval(timer);\n }, [client, store, refresh, refreshTime, refetchBlurred, disabled]);\n\n // ******************\n // Previous list\n // ******************\n\n const previousList = useRef<{ store: InfiniteStore; request: RequestInstance; snapshot: InfiniteSnapshot } | null>(\n null,\n );\n\n useEffect(() => {\n if (snapshot.data.length > 0) {\n previousList.current = { store, request, snapshot };\n }\n });\n\n const previous = previousList.current;\n const isPreviousData =\n !disabled &&\n snapshot.loading &&\n snapshot.data.length === 0 &&\n !!previous &&\n previous.store !== store &&\n getShouldKeepPreviousList(keepPreviousData, previous.request, request);\n\n const list = isPreviousData ? previous.snapshot : snapshot;\n\n // ******************\n // Suspense\n // ******************\n\n const isServer = client.mode === \"server\" || typeof window === \"undefined\";\n\n if (suspense && !disabled && !isServer && snapshot.loading && !isPreviousData) {\n throw store.start({ revalidate });\n }\n\n // ******************\n // Error boundary\n // ******************\n\n if (throwOnError) {\n usedKeys.add(\"error\");\n usedKeys.add(\"isFetching\");\n\n const error = snapshot.error as ExtractErrorType<R> | null;\n const shouldThrow = typeof throwOnError === \"function\" ? !!error && throwOnError(error) : !!error;\n\n if (shouldThrow && !snapshot.isFetching) {\n store.evictSoon();\n throw error;\n }\n }\n\n // ******************\n // Items\n // ******************\n\n const uniqueByRef = useRef(uniqueBy);\n uniqueByRef.current = uniqueBy;\n const uniqueByKey = typeof uniqueBy === \"function\" ? uniqueBy.toString() : uniqueBy;\n\n const uniqueItems = useMemo(() => {\n return getUniqueItems(list.items, uniqueByRef.current);\n // Inline functions change on every render, the key changes only with their code\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [list.items, uniqueByKey]);\n\n const selectedRef = useRef<unknown>(null);\n let items: unknown = uniqueItems;\n\n if (select) {\n const selected = select({ items: uniqueItems as PaginationItem<R, P>[], pages: list.data as any[] });\n items = structuralSharing ? replaceEqualDeep(selectedRef.current, selected) : selected;\n selectedRef.current = items;\n }\n\n // ******************\n // Actions\n // ******************\n\n const actions = useMemo(\n () => ({\n fetchNextPage: () => store.fetchNextPage(),\n fetchPreviousPage: () => store.fetchPreviousPage(),\n refetch: () => store.refetch(),\n reset: () => {\n callbacks.current.onReset?.();\n return store.reset();\n },\n abort: () => store.abort(),\n onSuccess: (callback: (event: any) => void) => {\n callbacks.current.onSuccess = callback;\n },\n onError: (callback: (event: any) => void) => {\n callbacks.current.onError = callback;\n },\n onFinished: (callback: (event: any) => void) => {\n callbacks.current.onFinished = callback;\n },\n onReset: (callback: VoidFunction) => {\n callbacks.current.onReset = callback;\n },\n }),\n [store],\n );\n\n return createTrackedProxy(\n {\n items,\n pages: list.data,\n pageParams: list.pageParams,\n total: list.total,\n hasNextPage: snapshot.hasNextPage,\n hasPreviousPage: snapshot.hasPreviousPage,\n loading: !disabled && snapshot.loading && !isPreviousData,\n isFetching: snapshot.isFetching,\n isRefetching: snapshot.isRefetching,\n isFetchingNextPage: snapshot.isFetchingNextPage,\n isFetchingPreviousPage: snapshot.isFetchingPreviousPage,\n isFetchNextPageError: snapshot.isFetchNextPageError,\n isFetchPreviousPageError: snapshot.isFetchPreviousPageError,\n isPreviousData,\n error: snapshot.error,\n status: snapshot.status,\n extra: snapshot.extra,\n success: snapshot.success,\n bounce: getBounceData(bounceData),\n ...actions,\n },\n trackedKeys,\n (usedKey) => usedKeys.add(usedKey),\n ) as unknown as UseInfiniteFetchReturnType<R, P, TSelected>;\n};\n","import { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n ExtractAdapterResolvedType,\n RequestInstance,\n ResponseType,\n ExtractResponseType,\n ExtractErrorType,\n RequestSendOptionsType,\n RequestSendType,\n ExtractAdapterType,\n} from \"@hyper-fetch/core\";\nimport { sendRequest } from \"@hyper-fetch/core\";\nimport type { UseTrackedStateType } from \"helpers\";\nimport { useTrackedState, useRequestEvents } from \"helpers\";\nimport type { UseSubmitOptionsType, UseSubmitReturnType } from \"hooks/use-submit\";\nimport { useSubmitDefaultOptions } from \"hooks/use-submit\";\nimport { useProvider } from \"provider\";\nimport { useEffect, useMemo, useRef } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\n\n/**\n * This hook aims to mutate data on the server. Unlike useFetch, it does not fire automatically -\n * call the returned `submit` function to trigger the request (e.g., on button click).\n * @param request\n * @param options\n * @returns\n */\nexport const useSubmit = <RequestType extends RequestInstance, TSelected = ExtractResponseType<RequestType>>(\n request: RequestType,\n options?: UseSubmitOptionsType<RequestType, TSelected>,\n): UseSubmitReturnType<RequestType, TSelected> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const mergedOptions: UseSubmitOptionsType<RequestType, TSelected> = useMemo(\n () => ({\n ...useSubmitDefaultOptions,\n ...globalConfig.useSubmitConfig,\n ...options,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [globalConfig.useSubmitConfig, JSON.stringify(options), options?.deepCompare],\n );\n const {\n disabled,\n dependencyTracking,\n initialResponse,\n bounce,\n bounceType,\n bounceTime,\n deepCompare,\n structuralSharing,\n } = mergedOptions;\n\n /**\n * Because of the dynamic cacheKey / queryKey signing within the request we need to store it's latest instance\n * so the events got triggered properly and show the latest result without mixing it up\n */\n const { client } = request;\n const { cache, submitDispatcher: dispatcher, loggerManager } = client;\n\n const logger = useRef(loggerManager.initialize(client, \"useSubmit\")).current;\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({\n interval: bounceTime,\n timeout: \"bounceTimeout\" in mergedOptions ? mergedOptions.bounceTimeout : bounceTime,\n });\n const bounceResolver = useRef<\n (\n value: ResponseType<\n ExtractResponseType<RequestType>,\n ExtractErrorType<RequestType>,\n ExtractAdapterType<RequestType>\n >,\n ) => void\n >(() => null);\n\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n /**\n * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues\n */\n const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<\n RequestType,\n TSelected\n >({\n logger,\n request,\n dispatcher,\n initialResponse,\n deepCompare: deepCompare as boolean,\n dependencyTracking: dependencyTracking as boolean,\n // Read directly from options - functions are not part of the memoized options key\n select: options?.select,\n structuralSharing,\n });\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [callbacks, listeners] = useRequestEvents({\n logger,\n actions,\n request,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners } = listeners;\n\n // ******************\n // Submitting\n // ******************\n\n const handleSubmit: RequestSendType<RequestType> = (submitOptions?: RequestSendOptionsType<RequestType>) => {\n const requestClone = request.clone(submitOptions as any) as unknown as RequestType;\n\n if (disabled) {\n logger.warning({ title: `Cannot submit request`, type: \"system\", extra: { disabled, submitOptions } });\n return Promise.resolve({\n data: null,\n error: new Error(\"Cannot submit request. Option 'disabled' is enabled\"),\n status: null,\n extra: request.client.adapter.defaultExtra,\n }) as Promise<\n ResponseType<ExtractResponseType<RequestType>, ExtractErrorType<RequestType>, ExtractAdapterType<RequestType>>\n >;\n }\n\n const triggerRequest = () => {\n addCacheDataListener(requestClone);\n\n const configuration: RequestSendOptionsType<RequestType> = {\n dispatcherType: \"submit\",\n ...(submitOptions as RequestSendOptionsType<RequestType>),\n onBeforeSent: (data) => {\n addLifecycleListeners(requestClone, data.requestId, data.mutationContext);\n submitOptions?.onBeforeSent?.(data);\n },\n };\n\n return sendRequest(requestClone, configuration);\n };\n\n return new Promise<ExtractAdapterResolvedType<RequestType>>((resolve) => {\n const performSubmit = async () => {\n logger.debug({ title: `Submitting request`, type: \"system\", extra: { disabled, submitOptions } });\n if (bounce) {\n const bouncedResolve = bounceResolver.current;\n // We need to keep the resolve of debounced requests to prevent memory leaks - we need to always resolve promise.\n // By default bounce method will prevent function to be triggered, but returned promise will still await to be resolved.\n // This way we can close previous promise, making sure our logic will not stuck in memory.\n bounceResolver.current = (\n value: ResponseType<\n ExtractResponseType<RequestType>,\n ExtractErrorType<RequestType>,\n ExtractAdapterType<RequestType>\n >,\n ) => {\n // Trigger previous awaiting calls to resolve together in bounced batches\n bouncedResolve(value);\n resolve(value);\n };\n\n // Start bounce\n bounceFunction(async () => {\n // We will always resolve previous calls as we stack the callbacks together until bounce function trigger\n const callback = bounceResolver.current;\n // Clean bounce resolvers to start the new stack\n bounceResolver.current = () => null;\n\n const value = await triggerRequest();\n callback(value);\n });\n } else {\n const value = await triggerRequest();\n resolve(value);\n }\n };\n\n performSubmit();\n });\n };\n\n // ******************\n // Invalidation\n // ******************\n\n const refetch = () => {\n cache.invalidate(request);\n };\n\n // ******************\n // Misc\n // ******************\n\n const handlers = {\n onSubmitSuccess: callbacks.onSuccess,\n onSubmitError: callbacks.onError,\n onSubmitFinished: callbacks.onFinished,\n onSubmitRequestStart: callbacks.onRequestStart,\n onSubmitResponseStart: callbacks.onResponseStart,\n onSubmitDownloadProgress: callbacks.onDownloadProgress,\n onSubmitUploadProgress: callbacks.onUploadProgress,\n onSubmitOfflineError: callbacks.onOfflineError,\n onSubmitAbort: callbacks.onAbort,\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without the cache subscription\n useEffect(() => {\n addCacheDataListener(request);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const setSubmitRenderKey = (key: string) => {\n setRenderKey((key === \"submitting\" ? \"loading\" : key) as keyof UseTrackedStateType);\n };\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"submitting\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n submit: handleSubmit,\n data: state.data,\n error: state.error,\n submitting: state.loading,\n status: state.status,\n success: state.success,\n extra: state.extra,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n abort: callbacks.abort,\n ...actions,\n ...handlers,\n bounce: getBounceData(bounceData),\n refetch,\n },\n trackedKeys,\n setSubmitRenderKey,\n ) as UseSubmitReturnType<RequestType, TSelected>;\n};\n","import type { RequestInstance, RequiredKeys } from \"@hyper-fetch/core\";\n\nimport type { UseSubmitOptionsType } from \"./use-submit.types\";\n\ntype DefaultOptionsType = RequiredKeys<Omit<UseSubmitOptionsType<RequestInstance>, \"initialResponse\" | \"select\">> & {\n initialResponse: null;\n};\n\nexport const useSubmitDefaultOptions: DefaultOptionsType = {\n disabled: false,\n dependencyTracking: true,\n initialResponse: null,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n deepCompare: true,\n structuralSharing: true,\n};\n","import type { RequestInstance, ResolvedQueueItemType, QueueDataType, QueueItemType } from \"@hyper-fetch/core\";\nimport { Request, getRequestDispatcher, scopeKey } from \"@hyper-fetch/core\";\nimport type { UseQueueOptionsType, QueueRequest, UseQueueReturnType } from \"hooks/use-queue\";\nimport { useQueueDefaultOptions } from \"hooks/use-queue\";\nimport { useProvider } from \"provider\";\nimport { useState, useEffect, useCallback } from \"react\";\n\nconst canUpdate = (\n item: Pick<QueueRequest<RequestInstance>, \"success\" | \"failed\" | \"canceled\" | \"removed\" | \"resolved\">,\n) => {\n if (item.success || item.failed) {\n return false;\n }\n return true;\n};\n\n/**\n * This hook allows you to monitor and control dispatcher request queues for a given request,\n * including starting, stopping, pausing, and inspecting pending/in-flight items.\n * @param request\n * @param options\n * @returns\n */\nexport const useQueue = <Request extends RequestInstance>(\n request: Request,\n options?: UseQueueOptionsType,\n): UseQueueReturnType<Request> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const { dispatcherType, keepFinishedRequests } = {\n ...useQueueDefaultOptions,\n ...globalConfig.useQueueConfig,\n ...options,\n };\n\n const { abortKey: rawAbortKey, queryKey: rawQueryKey, scope, client } = request;\n const abortKey = scopeKey(rawAbortKey, scope);\n const queryKey = scopeKey(rawQueryKey, scope);\n const { requestManager } = client;\n\n const [dispatcher] = getRequestDispatcher(request, dispatcherType);\n\n const [stopped, setStopped] = useState(false);\n const [requests, setRequests] = useState<QueueRequest<Request>[]>([]);\n\n // ******************\n // Mapping\n // ******************\n\n const createRequestsArray = useCallback(\n (\n queueElements: ResolvedQueueItemType<Request>[],\n prevRequests?: QueueRequest<Request>[],\n ): QueueRequest<Request>[] => {\n const newRequests = queueElements\n // Keep only unique requests\n .filter((el) => !prevRequests?.some((prevEl) => prevEl.requestId === el.requestId))\n .map<QueueRequest<Request>>((req) => ({\n failed: false,\n canceled: false,\n removed: false,\n success: false,\n ...req,\n downloading: {\n progress: 0,\n timeLeft: 0,\n sizeLeft: 0,\n total: 0,\n loaded: 0,\n startTimestamp: 0,\n },\n uploading: {\n progress: 0,\n timeLeft: 0,\n sizeLeft: 0,\n total: 0,\n loaded: 0,\n startTimestamp: 0,\n },\n stopRequest: () => dispatcher.stopRequest(queryKey, req.requestId),\n startRequest: () => dispatcher.startRequest(queryKey, req.requestId),\n deleteRequest: () => dispatcher.delete(queryKey, req.requestId, abortKey),\n }));\n\n if (keepFinishedRequests && prevRequests) {\n return [...prevRequests, ...newRequests];\n }\n\n return newRequests;\n },\n [abortKey, dispatcher, queryKey, keepFinishedRequests],\n );\n\n const mergePayloadType = useCallback((requestId: string, data: Partial<QueueRequest<Request>>) => {\n setRequests((prev) =>\n prev.map((el) => {\n if (el.requestId === requestId && canUpdate(el)) {\n return { ...el, ...data };\n }\n return el;\n }),\n );\n }, []);\n\n // ******************\n // State\n // ******************\n\n const getInitialState = () => {\n const requestQueue = dispatcher.getQueue<Request>(queryKey);\n\n setStopped(requestQueue.stopped);\n setRequests(createRequestsArray(requestQueue.requests));\n };\n\n const resolveQueueItems = useCallback(\n (items: QueueItemType<Request>[]): ResolvedQueueItemType<Request>[] => {\n return items.map((item) => {\n if (item.request instanceof Request) {\n return item as ResolvedQueueItemType<Request>;\n }\n return { ...item, request: client.fromJSON(item.request) as Request };\n });\n },\n [client],\n );\n\n const updateQueueState = useCallback(\n (values: QueueDataType<Request>) => {\n setStopped(values.stopped);\n setRequests((prev) => createRequestsArray(resolveQueueItems(values.requests), prev));\n },\n [createRequestsArray, resolveQueueItems],\n );\n\n // ******************\n // Events\n // ******************\n\n const mountEvents = () => {\n const unmountChange = dispatcher.events.onQueueChangeByKey<Request>(queryKey, updateQueueState);\n const unmountStatus = dispatcher.events.onQueueStatusChangeByKey<Request>(queryKey, updateQueueState);\n\n const unmountFailed = requestManager.events.onResponse(({ requestId, response }) => {\n if (!response.success) {\n setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, failed: true } : el)));\n } else {\n setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, success: true } : el)));\n }\n });\n const unmountCanceled = requestManager.events.onAbort(({ requestId }) => {\n setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, canceled: true } : el)));\n });\n\n const unmountRemoved = requestManager.events.onRemove(({ requestId }) => {\n setRequests((prev) =>\n prev.map((el) => (el.requestId === requestId && canUpdate(el) ? { ...el, removed: true } : el)),\n );\n });\n\n const unmountDownload = requestManager.events.onDownloadProgress(\n ({ progress, timeLeft, sizeLeft, total, loaded, startTimestamp, requestId }) => {\n mergePayloadType(requestId, { downloading: { progress, timeLeft, sizeLeft, total, loaded, startTimestamp } });\n },\n );\n\n const unmountUpload = requestManager.events.onUploadProgress(\n ({ progress, timeLeft, sizeLeft, total, loaded, startTimestamp, requestId }) => {\n mergePayloadType(requestId, { uploading: { progress, timeLeft, sizeLeft, total, loaded, startTimestamp } });\n },\n );\n\n const unmount = () => {\n unmountStatus();\n unmountChange();\n unmountDownload();\n unmountUpload();\n unmountFailed();\n unmountCanceled();\n unmountRemoved();\n };\n\n return unmount;\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n useEffect(getInitialState, [createRequestsArray, dispatcher, queryKey]);\n\n useEffect(mountEvents, [\n stopped,\n requests,\n setRequests,\n setStopped,\n queryKey,\n dispatcher.events,\n requestManager.events,\n updateQueueState,\n mergePayloadType,\n ]);\n\n return {\n stopped,\n requests,\n dispatcher,\n stop: () => dispatcher.stop(queryKey),\n pause: () => dispatcher.pause(queryKey),\n start: () => dispatcher.start(queryKey),\n };\n};\n","import type { RequiredKeys } from \"@hyper-fetch/core\";\nimport type { UseQueueOptionsType } from \"hooks/use-queue\";\n\nexport const useQueueDefaultOptions: RequiredKeys<UseQueueOptionsType> = {\n dispatcherType: \"auto\",\n keepFinishedRequests: false,\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { ExtractResponseType, RequestInstance } from \"@hyper-fetch/core\";\nimport { getRequestDispatcher } from \"@hyper-fetch/core\";\nimport { useRequestEvents, useTrackedState } from \"helpers\";\nimport type { UseCacheOptionsType, UseCacheReturnType } from \"hooks/use-cache\";\nimport { useCacheDefaultOptions } from \"hooks/use-cache\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\n\n/** Subscribe to cache updates for a given request without triggering network activity. */\nexport const useCache = <T extends RequestInstance, TSelected = ExtractResponseType<T>>(\n request: T,\n options?: UseCacheOptionsType<T, TSelected>,\n): UseCacheReturnType<T, TSelected> => {\n const { cacheKey, client } = request;\n\n const { cache, loggerManager } = client;\n const logger = useRef(loggerManager.initialize(client, \"useCache\")).current;\n const [dispatcher] = getRequestDispatcher(request);\n const updateKey = JSON.stringify(request.toJSON());\n\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const { dependencyTracking, initialResponse, deepCompare, structuralSharing } = {\n ...useCacheDefaultOptions,\n ...globalConfig.useCacheConfig,\n ...options,\n };\n\n /**\n * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues\n */\n const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<T, TSelected>({\n logger,\n request,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n select: options?.select,\n structuralSharing,\n });\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [, listeners] = useRequestEvents({\n logger,\n actions,\n request,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners } = listeners;\n\n const handleMountEvents = () => {\n const unmountDataListener = addCacheDataListener(request);\n const unmountLifecycleListener = addLifecycleListeners(request);\n return () => {\n unmountDataListener();\n unmountLifecycleListener();\n };\n };\n\n useDidUpdate(\n () => {\n return handleMountEvents();\n },\n [updateKey],\n true,\n );\n\n const invalidate = (cacheKeys?: string | RegExp | RequestInstance | (string | RegExp | RequestInstance)[]) => {\n cache.invalidate(cacheKeys ?? cacheKey);\n };\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"loading\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n error: state.error,\n loading: state.loading,\n status: state.status,\n success: state.success,\n extra: state.extra,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n ...actions,\n invalidate,\n },\n trackedKeys,\n setRenderKey,\n ) as UseCacheReturnType<T, TSelected>;\n};\n","export const useCacheDefaultOptions = {\n dependencyTracking: true,\n initialResponse: null,\n deepCompare: true,\n structuralSharing: true,\n};\n","import type { RequestInstance, ExtractAdapterExtraType, ExtractAdapterType, ExtractErrorType } from \"@hyper-fetch/core\";\nimport { scopeKey } from \"@hyper-fetch/core\";\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\n\nimport type { UseStreamOptionsType, UseStreamReturnType } from \"./use-stream.types\";\n\ntype StreamState<T extends RequestInstance> = {\n text: string;\n chunks: Uint8Array[];\n streaming: boolean;\n done: boolean;\n error: ExtractErrorType<T> | null;\n extra: ExtractAdapterExtraType<ExtractAdapterType<T>> | null;\n status: number | null;\n};\n\nconst getInitialState = <T extends RequestInstance>(): StreamState<T> => ({\n text: \"\",\n chunks: [],\n streaming: false,\n done: false,\n error: null,\n extra: null,\n status: null,\n});\n\n/**\n * Hook for consuming streaming responses chunk-by-chunk.\n * Works with any request that uses the fetch adapter's `streaming: true` option.\n *\n * Provides both accumulated `text` (for LLM/SSE use cases) and raw `chunks`\n * (for binary streaming / file downloads).\n */\nexport const useStream = <T extends RequestInstance>(\n request: T,\n options?: UseStreamOptionsType,\n): UseStreamReturnType<T> => {\n const { autoStart = false } = options || {};\n\n const state = useRef<StreamState<T>>(getInitialState<T>());\n const abortRef = useRef<(() => void) | null>(null);\n const startedRef = useRef(false);\n\n // useSyncExternalStore for re-renders\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n const consumeStream = async (stream: ReadableStream<Uint8Array>) => {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {break;}\n\n state.current.chunks = [...state.current.chunks, value];\n state.current.text += decoder.decode(value, { stream: true });\n emitChange();\n }\n\n state.current.streaming = false;\n state.current.done = true;\n emitChange();\n } catch (error) {\n state.current.streaming = false;\n state.current.error = error as ExtractErrorType<T>;\n emitChange();\n }\n };\n\n const start = useCallback(() => {\n if (state.current.streaming) {return;}\n\n state.current = {\n ...getInitialState<T>(),\n streaming: true,\n };\n emitChange();\n\n const streamingRequest = request.setOptions({ streaming: true } as any);\n\n streamingRequest.send().then((response) => {\n const { data, error, status, extra } = response;\n\n state.current.status = status as number | null;\n state.current.extra = extra as ExtractAdapterExtraType<ExtractAdapterType<T>> | null;\n\n if (error) {\n state.current.streaming = false;\n state.current.error = error;\n emitChange();\n return;\n }\n\n if (data && typeof (data as any).getReader === \"function\") {\n consumeStream(data as unknown as ReadableStream<Uint8Array>);\n } else {\n state.current.streaming = false;\n state.current.text = typeof data === \"string\" ? data : JSON.stringify(data);\n state.current.done = true;\n emitChange();\n }\n });\n\n abortRef.current = () => {\n request.client.requestManager.abortByKey(scopeKey(request.abortKey, request.scope));\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [request]);\n\n const abort = useCallback(() => {\n abortRef.current?.();\n state.current.streaming = false;\n emitChange();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const reset = useCallback(() => {\n abortRef.current?.();\n state.current = getInitialState<T>();\n startedRef.current = false;\n emitChange();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (autoStart && !startedRef.current) {\n startedRef.current = true;\n start();\n }\n }, [autoStart, start]);\n\n return {\n text: state.current.text,\n chunks: state.current.chunks,\n streaming: state.current.streaming,\n done: state.current.done,\n error: state.current.error,\n extra: state.current.extra,\n status: state.current.status,\n start,\n abort,\n reset,\n };\n};\n","import { useDidUpdate, useWillUnmount } from \"@better-hooks/lifecycle\";\nimport { replaceEqualDeep } from \"@hyper-fetch/core\";\nimport type { ListenerInstance, ExtractListenerDeliveredType } from \"@hyper-fetch/sockets\";\nimport { getDeliveryKey } from \"@hyper-fetch/sockets\";\nimport { useSocketState } from \"helpers\";\nimport type { UseListenerOptionsType } from \"hooks/use-listener\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\n\n/** Subscribe to incoming socket messages on a given listener topic with tracked connection state and callbacks. */\nexport const useListener = <\n ListenerType extends ListenerInstance,\n TSelected = ExtractListenerDeliveredType<ListenerType>,\n>(\n listener: ListenerType,\n options?: UseListenerOptionsType<ExtractListenerDeliveredType<ListenerType>, TSelected>,\n) => {\n const { config: globalConfig } = useProvider();\n const { dependencyTracking = true, structuralSharing = true } = { ...globalConfig.useListener, ...options };\n const select = options?.select;\n const [state, actions, callbacks, { setRenderKey, getState, rerender }] = useSocketState<\n TSelected,\n ListenerType[\"socket\"]\n >(listener.socket, { dependencyTracking });\n const removeListenerRef = useRef<ReturnType<typeof listener.listen> | null>(null);\n\n /**\n * Selection\n */\n\n const selectRef = useRef(select);\n selectRef.current = select;\n const appliedSelect = useRef(select);\n // Last message data before applying the selector - allows to re-run it when the selector changes\n const rawData = useRef<{ data: ExtractListenerDeliveredType<ListenerType> } | null>(null);\n const selectError = useRef<{ error: unknown } | null>(null);\n\n const selectData = (data: ExtractListenerDeliveredType<ListenerType>): TSelected => {\n if (!selectRef.current) {\n return data as unknown as TSelected;\n }\n const selected = selectRef.current(data);\n return structuralSharing ? replaceEqualDeep(getState().data, selected) : selected;\n };\n\n // Selector failed while processing a message - surface it to the closest error boundary\n if (selectError.current) {\n const { error } = selectError.current;\n selectError.current = null;\n throw error;\n }\n\n // Selector changed (e.g. it closes over a new prop) - re-run it against the last message\n if (appliedSelect.current !== select) {\n appliedSelect.current = select;\n if (rawData.current) {\n state.data = selectData(rawData.current.data);\n }\n }\n\n /**\n * Callbacks\n */\n\n const onEventCallback = useRef<\n null | ((response: { data: ExtractListenerDeliveredType<ListenerType>; extra: Record<string, any> }) => void)\n >(null);\n\n /**\n * Actions\n */\n\n const stopListener = () => {\n removeListenerRef.current?.();\n };\n\n const listen = () => {\n stopListener();\n removeListenerRef.current = listener.listen(({ data, extra }) => {\n onEventCallback.current?.({ data, extra });\n rawData.current = { data };\n appliedSelect.current = selectRef.current;\n\n let selected: TSelected;\n try {\n selected = selectData(data);\n } catch (error) {\n // Never throw inside of the socket events - rethrow it on render instead\n selectError.current = { error };\n rerender();\n return;\n }\n\n // With a selector, data is updated only when the selected value changed\n if (!selectRef.current || !Object.is(selected, getState().data)) {\n actions.setData(selected);\n }\n actions.setExtra(extra);\n actions.setTimestamp(Date.now());\n });\n };\n\n const additionalCallbacks = {\n onEvent: (callback: NonNullable<typeof onEventCallback.current>) => {\n onEventCallback.current = callback;\n },\n };\n\n /**\n * Lifecycle\n */\n\n useDidUpdate(\n () => {\n listen();\n },\n // Topic already contains resolved params. Delivery presets compare by value, custom strategies by identity.\n [listener.topic, JSON.stringify(listener.options), getDeliveryKey(listener.delivery)],\n true,\n );\n\n useWillUnmount(() => {\n stopListener();\n });\n\n const trackedKeys = [\"data\", \"extra\", \"connected\", \"connecting\", \"timestamp\"] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n extra: state.extra,\n connected: state.connected,\n connecting: state.connecting,\n timestamp: state.timestamp,\n ...actions,\n ...callbacks,\n ...additionalCallbacks,\n listen,\n },\n trackedKeys,\n setRenderKey,\n );\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { EmitterInstance, EmitterCallbackErrorType, EmitType } from \"@hyper-fetch/sockets\";\nimport { useSocketState } from \"helpers\";\nimport type { UseEmitterOptionsType } from \"hooks/use-emitter\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\n\n/** Send messages through a socket emitter with tracked connection state and lifecycle callbacks. */\nexport const useEmitter = <EmitterType extends EmitterInstance>(\n emitter: EmitterType,\n options?: UseEmitterOptionsType,\n) => {\n const { config: globalConfig } = useProvider();\n const { dependencyTracking = true } = { ...globalConfig.useEmitter, ...options };\n\n const [state, actions, callbacks, { setRenderKey }] = useSocketState(emitter.socket, { dependencyTracking });\n\n /**\n * Callbacks\n */\n const onEventStartCallback = useRef<null | ((emitter: EmitterType) => void)>(null);\n const onEventErrorCallback = useRef<null | EmitterCallbackErrorType>(null);\n\n useDidUpdate(\n () => {\n const onEventStart = () => {\n return emitter.socket.events.onEmitterStartEventByTopic(emitter, () => {\n onEventStartCallback.current?.(emitter);\n });\n };\n\n const onEventError = () => {\n return emitter.socket.events.onEmitterErrorByTopic(emitter, ({ error }) => {\n onEventErrorCallback.current?.({ error });\n });\n };\n\n const unmountEventStart = onEventStart();\n const unmountEventError = onEventError();\n\n return () => {\n unmountEventStart();\n unmountEventError();\n };\n },\n [emitter.topic, onEventStartCallback.current, onEventErrorCallback.current],\n true,\n );\n\n /**\n * Emitter\n */\n\n const emit: EmitType<EmitterType> = (emitOptions: Parameters<EmitType<EmitterType>>[0]) => {\n return emitter.emit(emitOptions as any);\n };\n\n const onEmit = (callback: (emitter: EmitterType) => void) => {\n onEventStartCallback.current = callback;\n };\n\n const onEmitError = (callback: EmitterCallbackErrorType) => {\n onEventErrorCallback.current = callback;\n };\n\n const trackedKeys = [\"connected\", \"connecting\"] as const;\n\n return createTrackedProxy(\n {\n connected: state.connected,\n connecting: state.connecting,\n ...actions,\n ...callbacks,\n onEmit,\n onEmitError,\n emit,\n },\n trackedKeys,\n setRenderKey,\n );\n};\n","import type { ClientInstance } from \"@hyper-fetch/core\";\nimport type { UseAppManagerReturnType } from \"hooks/use-app-manager\";\nimport { useEffect, useState } from \"react\";\n\n/** Track the application's online/offline and focus/blur state through the client's AppManager. */\nexport const useAppManager = <Client extends ClientInstance>(client: Client): UseAppManagerReturnType => {\n const [online, setIsOnline] = useState(client.appManager.isOnline);\n const [focused, setIsFocused] = useState(client.appManager.isFocused);\n\n const mountEvents = () => {\n // Catch up with anything that happened between the render and the subscription\n setIsOnline(client.appManager.isOnline);\n setIsFocused(client.appManager.isFocused);\n\n const unmountIsOnline = client.appManager.events.onOnline(() => setIsOnline(true));\n const unmountIsOffline = client.appManager.events.onOffline(() => setIsOnline(false));\n const unmountIsFocus = client.appManager.events.onFocus(() => setIsFocused(true));\n const unmountIsBlur = client.appManager.events.onBlur(() => setIsFocused(false));\n\n return () => {\n unmountIsOnline();\n unmountIsOffline();\n unmountIsFocus();\n unmountIsBlur();\n };\n };\n\n const setOnline = (isOnline: boolean) => {\n client.appManager.setOnline(isOnline);\n };\n\n const setFocused = (isFocused: boolean) => {\n client.appManager.setFocused(isFocused);\n };\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without any subscriptions\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(mountEvents, [client]);\n\n return { isOnline: online, isFocused: focused, setOnline, setFocused };\n};\n","import type { AdapterInstance, ClientInstance, Dispatcher } from \"@hyper-fetch/core\";\nimport type { UseIsFetchingOptionsType } from \"hooks/use-is-fetching\";\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\n\nconst useRunningRequestsCount = (\n dispatcher: Dispatcher<AdapterInstance>,\n options?: UseIsFetchingOptionsType,\n): number => {\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const subscribe = useCallback(\n (listener: () => void) => dispatcher.events.onRunningRequestsChange(listener),\n [dispatcher],\n );\n\n const getCount = () => {\n const { queryKey, predicate } = optionsRef.current || {};\n return dispatcher.getAllRunningRequests().filter(({ request }) => {\n if (typeof queryKey === \"string\" && request.queryKey !== queryKey) {\n return false;\n }\n if (queryKey instanceof RegExp && !queryKey.test(request.queryKey)) {\n return false;\n }\n return !predicate || predicate(request);\n }).length;\n };\n\n return useSyncExternalStore(subscribe, getCount, getCount);\n};\n\n/**\n * Count of the currently running fetch requests (useFetch, useCache and fetch dispatcher). Useful for global loading indicators.\n * @param client Client instance\n * @param options Filters for the counted requests\n * @returns number of running requests\n */\nexport const useIsFetching = (client: ClientInstance, options?: UseIsFetchingOptionsType): number => {\n return useRunningRequestsCount(client.fetchDispatcher, options);\n};\n\n/**\n * Count of the currently running submit requests (useSubmit and submit dispatcher). Useful for global saving indicators.\n * @param client Client instance\n * @param options Filters for the counted requests\n * @returns number of running requests\n */\nexport const useIsSubmitting = (client: ClientInstance, options?: UseIsFetchingOptionsType): number => {\n return useRunningRequestsCount(client.submitDispatcher, options);\n};\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;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AAET,UAAO,CAAC,aAAa,UAAU,QAAQ;IACvC,CAAC;;AAGL,QAAO,qBAAqB,WAAW,UAAU,SAAS;;;;;;;;AAS5D,IAAa,iBAAiB,QAAwB,YAA+C;AACnG,QAAO,wBAAwB,OAAO,iBAAiB,QAAQ;;;;;;;;AASjE,IAAa,mBAAmB,QAAwB,YAA+C;AACrG,QAAO,wBAAwB,OAAO,kBAAkB,QAAQ"}
1
+ {"version":3,"file":"index.mjs","names":["r","f","t","u","a","n","v","y","d","n","o","t","r","e","u","l","c"],"sources":["../../../node_modules/.pnpm/@better-hooks+lifecycle@2.0.0_react@19.2.5/node_modules/@better-hooks/lifecycle/dist/index.esm.js","../../../node_modules/.pnpm/@better-hooks+performance@2.1.0_react@19.2.5/node_modules/@better-hooks/performance/dist/index.esm.js","../src/utils/scope.utils.ts","../src/helpers/use-request-events/use-request-events.hooks.ts","../src/helpers/use-tracked-state/use-tracked-state.constants.ts","../src/hydrate/hydrate.utils.ts","../src/hydrate/hydrate.tsx","../src/utils/deep-equal.utils.ts","../src/utils/bounce.utils.ts","../src/utils/tracked-proxy.utils.ts","../src/helpers/use-tracked-state/use-tracked-state.utils.ts","../src/helpers/use-tracked-state/use-tracked-state.hooks.ts","../src/helpers/use-socket-state/use-socket-state.hooks.ts","../src/helpers/use-socket-state/use-socket-state.constants.ts","../src/provider/provider.tsx","../src/hooks/use-fetch/use-fetch.hooks.ts","../src/hooks/use-fetch/use-fetch.utils.ts","../src/hooks/use-fetch/use-fetch.constants.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.constants.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.requests.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts","../src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts","../src/hooks/use-submit/use-submit.hooks.ts","../src/hooks/use-submit/use-submit.constants.ts","../src/hooks/use-queue/use-queue.hooks.ts","../src/hooks/use-queue/use-queue.constants.ts","../src/hooks/use-cache/use-cache.hooks.ts","../src/hooks/use-cache/use-cache.constants.ts","../src/hooks/use-stream/use-stream.hooks.ts","../src/hooks/use-listener/use-listener.hooks.ts","../src/hooks/use-emitter/use-emitter.hooks.ts","../src/hooks/use-app-manager/use-app-manager.hooks.ts","../src/hooks/use-is-fetching/use-is-fetching.hooks.ts"],"sourcesContent":["import{useRef as r,useEffect as n,useState as t,useCallback as u,useLayoutEffect as c}from\"react\";var e=function(t,u,c){void 0===c&&(c=!1);var e=r(null),o=r(c);n((function(){if(o.current)return function(){t(e.current),e.current=u};o.current=!0}),u)},o=function(t){var u=r(!1);n((function(){if(!u.current)return u.current=!0,t()}),[])},i=function(t,u,c){void 0===c&&(c=!1);var e=r(c);n((function(){if(e.current)return t();e.current=!0}),u)};var f=function(){var r=function(r,n){var t=\"function\"==typeof Symbol&&r[Symbol.iterator];if(!t)return r;var u,c,e=t.call(r),o=[];try{for(;(void 0===n||n-- >0)&&!(u=e.next()).done;)o.push(u.value)}catch(r){c={error:r}}finally{try{u&&!u.done&&(t=e.return)&&t.call(e)}finally{if(c)throw c.error}}return o}(t(0),2)[1];return u((function(){r((function(r){return r+1}))}),[])},a=function(){var t=r(!0);return n((function(){return t.current=!0,function(){t.current=!1}}),[]),t},v=function(n){var t=r(!1);c((function(){if(!t.current)return t.current=!0,n()}),[])},l=function(n,t,u){void 0===u&&(u=!1);var e=r(u);c((function(){if(e.current)return n();e.current=!0}),t)},y=function(n){var t=r(!0);t.current&&n(),t.current=!1},d=function(r){n((function(){return r}),[])};export{e as useDepsChange,o as useDidMount,i as useDidUpdate,f as useForceUpdate,a as useIsMounted,v as useLayoutMount,l as useLayoutUpdate,y as useWillMount,d as useWillUnmount};\n//# sourceMappingURL=index.esm.js.map\n","import{useRef as n,useCallback as t,useEffect as r,useState as e,useMemo as u,useLayoutEffect as c}from\"react\";import{useForceUpdate as o,useDidUpdate as i,useDidMount as l}from\"@better-hooks/lifecycle\";var f=function(e){var u=(e||{}).delay,c=void 0===u?400:u,i=n(!1),l=n(null),f=o(),a=t((function(){i.current&&f()}),[f]),v=function(){null!==l.current&&clearTimeout(l.current),l.current=null},d=t((function(n,t){var r=null!=t?t:c;v(),l.current=setTimeout((function(){l.current=null,n(),a()}),r),a()}),[c,a]);return r((function(){return v}),[]),{get active(){return i.current=!0,!!l.current},debounce:d,reset:v}},a=function(n,t,e){var u=f(t).debounce;r((function(){u(n)}),e)};function v(n,t){var r=\"function\"==typeof Symbol&&n[Symbol.iterator];if(!r)return n;var e,u,c=r.call(n),o=[];try{for(;(void 0===t||t-- >0)&&!(e=c.next()).done;)o.push(e.value)}catch(n){u={error:n}}finally{try{e&&!e.done&&(r=c.return)&&r.call(c)}finally{if(u)throw u.error}}return o}var d=function(n,t){var r=f(t).debounce,u=v(e(n),2),c=u[0],o=u[1];return[c,function(n){return r((function(){return o(n)}))}]},y=function(n){var t=Object.prototype.toString.call(n);return Array.isArray(n)?!n.length:\"object\"==typeof n&&null!==n&&\"[object Object]\"===t&&!Object.keys(n).length},m=function(n,t){var r,e=Object.prototype.toString.call(n),u=Object.prototype.toString.call(t),c=typeof n,o=typeof t,i=function(n){return c===n&&o===n};return e===u&&(null===n&&null===t||(!!(i(\"number\")&&Number.isNaN(n)&&Number.isNaN(t))||(!(!y(n)||!y(t))||(Array.isArray(n)&&Array.isArray(t)?n.length===t.length&&!n.some((function(n,r){return!m(n,t[r])})):i(\"object\")&&(e===(r=\"[object Object]\")&&u===r)?Object.keys(n).length===Object.keys(t).length&&!Object.entries(n).some((function(n){var r=v(n,2),e=r[0],u=r[1];return!m(u,t[e])})):n instanceof Date&&t instanceof Date?+n==+t:n===t))))},s=function(t,e){return r(t,(o=n(c=e),i=n(0),m(c,o.current)||(o.current=c,i.current+=1),u((function(){return o.current}),[i.current])));var c,o,i},b=function(t,r,u){var c=u||{},o=c.immediate,f=void 0===o||o,a=c.disabled,d=void 0!==a&&a,y=v(e(null),2),m=y[0],s=y[1],b=n(t),p=function(){m&&clearInterval(m),s(null)},h=function(){p(),!r&&0!==r||d||s(setInterval((function(){return b.current()}),r))};return i((function(){b.current=t}),[t]),l((function(){if(b.current=t,f)return h(),p})),i((function(){return b.current=t,h(),p}),[r]),{active:null!==m,start:h,stop:p}},p=function(t){var e=t||{},u=e.interval,c=void 0===u?200:u,i=e.timeout,l=void 0===i?200:i,f=n(0),a=n(!0),v=n(!1),d=n(null),y=o(),m=function(){a.current&&(a.current=!1),v.current&&y()},s=function(){null!==d.current&&clearTimeout(d.current),d.current=null};return r((function(){return s}),[]),{get active(){return v.current=!0,!!d.current},throttle:function(n,t){var r,e,u=function(){f.current=Date.now(),n(),m()},o=null!==(r=null==t?void 0:t.interval)&&void 0!==r?r:c,i=null!==(e=null==t?void 0:t.timeout)&&void 0!==e?e:l,v=Date.now()>=f.current+o;a.current&&m(),d.current&&s(),v?u():i&&(d.current=setTimeout((function(){d.current=null,a.current=!0,u()}),i))},reset:s}},h=function(n,t,e){var u=p(t).throttle;r((function(){u(n)}),e)},j=function(n,t){var r=p(t).throttle,u=v(e(n),2),c=u[0],o=u[1];return[c,function(n){return r((function(){return o(n)}))}]},g=function(t,e){var u=n(t);w((function(){u.current=t}),[t]),r((function(){if(e||0===e){var n=setTimeout((function(){return u.current()}),e);return function(){return clearTimeout(n)}}}),[e])},w=!(\"undefined\"==typeof window||void 0===window.document||void 0===window.document.createElement)?c:r;export{f as useDebounce,a as useDebounceEffect,d as useDebounceState,s as useDeepEffect,b as useInterval,w as useIsomorphicEffect,p as useThrottle,h as useThrottleEffect,j as useThrottleState,g as useTimeout};\n//# sourceMappingURL=index.esm.js.map\n","/**\n * Core emits request and cache events by the logical (unscoped) keys, while dispatcher queues and cache storage\n * use the scoped keys. Listeners subscribe by the logical key and use this check to skip events of other scopes.\n * @internal\n */\nexport const isSameScope = (scope: string | null | undefined, otherScope: string | null | undefined): boolean => {\n return (scope ?? null) === (otherScope ?? null);\n};\n","import { useIsMounted, useWillUnmount } from \"@better-hooks/lifecycle\";\nimport type {\n ExtractErrorType,\n ExtractResponseType,\n RequestInstance,\n RequestEventType,\n RequestLoadingEventType,\n ExtractAdapterType,\n RequestProgressEventType,\n RequestResponseEventType,\n ResponseType,\n OptimisticCallbackResult,\n} from \"@hyper-fetch/core\";\nimport { runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport type {\n OnErrorCallbackType,\n OnStartCallbackType,\n OnSuccessCallbackType,\n OnProgressCallbackType,\n OnFinishedCallbackType,\n UseRequestEventsDataMap,\n UseRequestEventsReturnType,\n UseRequestEventsPropsType,\n UseRequestEventsLifecycleMap,\n} from \"helpers\";\nimport { useRef } from \"react\";\nimport { isSameScope } from \"utils/scope.utils\";\n\n/**\n * This is helper hook that handles main Hyper-Fetch event/data flow\n * @internal\n * @param options\n * @returns\n */\nexport const useRequestEvents = <R extends RequestInstance>({\n request,\n dispatcher,\n logger,\n actions,\n setCacheData,\n getIsDataProcessing,\n}: UseRequestEventsPropsType<R>): UseRequestEventsReturnType<R> => {\n const { cache, requestManager } = request.client;\n\n // ******************\n // Callbacks\n // ******************\n\n const onSuccessCallback = useRef<null | OnSuccessCallbackType<R>>(null);\n const onErrorCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onAbortCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onOfflineErrorCallback = useRef<null | OnErrorCallbackType<R>>(null);\n const onFinishedCallback = useRef<null | OnFinishedCallbackType<R>>(null);\n const onRequestStartCallback = useRef<null | OnStartCallbackType<R>>(null);\n const onResponseStartCallback = useRef<null | OnStartCallbackType<R>>(null);\n const onDownloadProgressCallback = useRef<null | OnProgressCallbackType>(null);\n const onUploadProgressCallback = useRef<null | OnProgressCallbackType>(null);\n\n // ******************\n // Listeners unmounting\n // ******************\n\n const lifecycleEvents = useRef<UseRequestEventsLifecycleMap>(new Map());\n const dataEvents = useRef<UseRequestEventsDataMap | null>(null);\n // Sending can outlive the component - the unmount cleanup never sees listeners attached after it ran\n const isMounted = useIsMounted();\n\n const removeLifecycleListener = (requestId: string) => {\n const event = lifecycleEvents.current.get(requestId);\n event?.unmount();\n lifecycleEvents.current.delete(requestId);\n };\n\n const clearLifecycleListeners = () => {\n const events = lifecycleEvents.current;\n const listeners = [...events.values()];\n listeners.forEach((value) => {\n value.unmount();\n });\n events.clear();\n };\n\n // ******************\n // Optimistic state\n // ******************\n\n // Rollback and invalidation are settled by the core - here we only deliver the context to the callbacks\n const optimisticResultsRef = useRef<Map<string, OptimisticCallbackResult<any>>>(new Map());\n\n // ******************\n // Response handlers\n // ******************\n\n const handleResponseCallbacks = (values: RequestResponseEventType<R>) => {\n const { success } = values.response;\n const { isOffline, isCanceled, willRetry } = values.details;\n const opt = optimisticResultsRef.current.get(values.requestId);\n const paramsWithContext = { ...values, mutationContext: opt?.context } as any;\n const isOfflineError = request.offline && isOffline && !success;\n\n if (isOfflineError) {\n logger.debug({ title: \"Performing offline error callback\", type: \"system\", extra: values });\n onOfflineErrorCallback.current?.(paramsWithContext);\n } else if (isCanceled) {\n logger.debug({ title: \"Performing abort callback\", type: \"system\", extra: values });\n onAbortCallback.current?.(paramsWithContext);\n } else if (success) {\n logger.debug({ title: \"Performing success callback\", type: \"system\", extra: values });\n onSuccessCallback.current?.(paramsWithContext);\n } else {\n logger.debug({ title: \"Performing error callback\", type: \"system\", extra: values });\n onErrorCallback.current?.(paramsWithContext);\n }\n onFinishedCallback.current?.(paramsWithContext);\n // Retried and offline requests respond again, their callbacks still need the context\n if (!willRetry && (!isOfflineError || isCanceled)) {\n optimisticResultsRef.current.delete(values.requestId);\n }\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n const handleGetLoadingEvent = (req: R) => {\n return ({ loading, request: eventRequest }: RequestLoadingEventType<RequestInstance>) => {\n // Loading events are emitted by the logical queryKey - skip requests of other scopes\n if (!isSameScope(eventRequest.scope, req.scope)) {\n return;\n }\n\n const isProcessing = getIsDataProcessing(req.cacheKey);\n\n // When we process the cache data, we don't want to change the loading state during it\n // This prevents the UI from flickering with { data: null, loading: false }\n if (isProcessing) {\n return;\n }\n\n const canDisableLoading = !loading && !dispatcher.hasRunningRequests(scopeKey(req.queryKey, req.scope));\n if (loading || canDisableLoading) {\n actions.setLoading(loading);\n }\n };\n };\n\n const handleDownloadProgress = (data: RequestProgressEventType<RequestInstance>) => {\n onDownloadProgressCallback.current?.(data);\n };\n\n const handleUploadProgress = (data: RequestProgressEventType<RequestInstance>) => {\n onUploadProgressCallback.current?.(data);\n };\n\n const handleRequestStart = () => {\n return (details: RequestEventType<R>) => {\n onRequestStartCallback.current?.(details);\n };\n };\n const handleResponseStart = () => {\n return (details: RequestEventType<R>) => {\n onResponseStartCallback.current?.(details);\n };\n };\n\n const handleResponse = () => {\n return (values: RequestResponseEventType<R>) => {\n const data = runResponseMapper(request, values.response);\n\n if (data instanceof Promise) {\n return (async () => {\n const response = (await data) as ResponseType<any, any, ExtractAdapterType<R>>;\n // The mapper can outlive the component - the unmount cleanup can't stop a response already being mapped\n if (!isMounted.current) {\n return;\n }\n handleResponseCallbacks({ ...values, response });\n })();\n }\n return handleResponseCallbacks(values);\n };\n };\n\n const handleRemove = ({ requestId }: RequestEventType<R>) => {\n optimisticResultsRef.current.delete(requestId);\n removeLifecycleListener(requestId);\n };\n\n // ******************\n // Data Listeners\n // ******************\n\n const clearCacheDataListener = () => {\n dataEvents.current?.unmount();\n dataEvents.current = null;\n };\n\n const addCacheDataListener = (req: R) => {\n if (!isMounted.current) {\n return () => undefined;\n }\n\n // Data handlers\n // Core emits these events by the logical keys; the handlers skip events of other scopes\n const loadingUnmount = requestManager.events.onLoadingByQueue(req.queryKey, handleGetLoadingEvent(req));\n const getResponseUnmount = cache.events.onDataByKey<\n ExtractResponseType<R>,\n ExtractErrorType<R>,\n ExtractAdapterType<R>\n >(req.cacheKey, (cacheData) => {\n if (!isSameScope(cacheData.scope, req.scope)) {\n return;\n }\n setCacheData(cacheData);\n });\n\n const unmount = () => {\n loadingUnmount();\n getResponseUnmount();\n };\n\n clearCacheDataListener();\n dataEvents.current = { unmount };\n\n return unmount;\n };\n\n // ******************\n // Lifecycle Listeners\n // ******************\n\n const addLifecycleListeners = (req: R, requestId?: string, optimisticResult?: OptimisticCallbackResult<any>) => {\n if (!isMounted.current) {\n return () => undefined;\n }\n\n /**\n * useFetch handles requesting by general keys\n * This makes it possible to deduplicate requests from different places and share data\n */\n if (!requestId) {\n // It's important to clear previously attached listeners to not cause some additional response/request\n // events to be triggered during lifecycle\n clearLifecycleListeners();\n const { queryKey, cacheKey } = req;\n const requestStartUnmount = requestManager.events.onRequestStartByQueue(queryKey, handleRequestStart());\n const responseStartUnmount = requestManager.events.onResponseStartByQueue(queryKey, handleResponseStart());\n const uploadUnmount = requestManager.events.onUploadProgressByQueue(queryKey, handleUploadProgress);\n const downloadUnmount = requestManager.events.onDownloadProgressByQueue(queryKey, handleDownloadProgress);\n const responseUnmount = requestManager.events.onResponseByCache(cacheKey, handleResponse());\n\n const unmount = () => {\n downloadUnmount();\n uploadUnmount();\n requestStartUnmount();\n responseStartUnmount();\n responseUnmount();\n };\n\n lifecycleEvents.current.set(queryKey, { unmount });\n\n return unmount;\n }\n /**\n * useSubmit handles requesting by requestIds, this makes it possible to track single requests\n */\n if (optimisticResult) {\n optimisticResultsRef.current.set(requestId, optimisticResult);\n }\n const requestRemove = requestManager.events.onRemoveById(requestId, handleRemove);\n const requestStartUnmount = requestManager.events.onRequestStartById(requestId, handleRequestStart());\n const responseStartUnmount = requestManager.events.onResponseStartById(requestId, handleResponseStart());\n const responseUnmount = requestManager.events.onResponseById(requestId, handleResponse());\n const uploadUnmount = requestManager.events.onUploadProgressById(requestId, handleUploadProgress);\n const downloadUnmount = requestManager.events.onDownloadProgressById(requestId, handleDownloadProgress);\n\n const unmount = () => {\n requestRemove();\n downloadUnmount();\n uploadUnmount();\n requestStartUnmount();\n responseStartUnmount();\n responseUnmount();\n };\n\n lifecycleEvents.current.set(requestId, { unmount });\n\n return unmount;\n };\n\n // ******************\n // Abort\n // ******************\n\n const abort = () => {\n const ak = scopeKey(request.abortKey, request.scope);\n const requests = dispatcher.getAllRunningRequests();\n requests.forEach((requestData) => {\n const reqAk = scopeKey(requestData.request.abortKey, requestData.request.scope);\n if (reqAk === ak) {\n const qk = scopeKey(requestData.request.queryKey, requestData.request.scope);\n dispatcher.delete(qk, requestData.requestId, reqAk);\n }\n });\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n /**\n * On unmount we want to clear all the listeners to prevent memory leaks\n */\n useWillUnmount(() => {\n // Unmount listeners\n clearLifecycleListeners();\n clearCacheDataListener();\n });\n\n return [\n {\n abort,\n onSuccess: (callback: OnSuccessCallbackType<R>) => {\n onSuccessCallback.current = callback;\n },\n onError: (callback: OnErrorCallbackType<R>) => {\n onErrorCallback.current = callback;\n },\n onAbort: (callback: OnErrorCallbackType<R>) => {\n onAbortCallback.current = callback;\n },\n onOfflineError: (callback: OnErrorCallbackType<R>) => {\n onOfflineErrorCallback.current = callback;\n },\n onFinished: (callback: OnFinishedCallbackType<R>) => {\n onFinishedCallback.current = callback;\n },\n onRequestStart: (callback: OnStartCallbackType<R>) => {\n onRequestStartCallback.current = callback;\n },\n onResponseStart: (callback: OnStartCallbackType<R>) => {\n onResponseStartCallback.current = callback;\n },\n onDownloadProgress: (callback: OnProgressCallbackType) => {\n onDownloadProgressCallback.current = callback;\n },\n onUploadProgress: (callback: OnProgressCallbackType) => {\n onUploadProgressCallback.current = callback;\n },\n },\n {\n addCacheDataListener,\n clearCacheDataListener,\n addLifecycleListeners,\n removeLifecycleListener,\n clearLifecycleListeners,\n },\n ];\n};\n","import type { UseTrackedStateType } from \"./use-tracked-state.types\";\n\nexport const initialState: UseTrackedStateType = {\n data: null,\n error: null,\n status: null,\n extra: {},\n success: false,\n loading: false,\n retries: 0,\n responseTimestamp: null,\n requestTimestamp: null,\n};\n","import type {\n CacheValueType,\n ClientInstance,\n EmptyTypes,\n HydrateDataType,\n HydrationOptions,\n NullableType,\n} from \"@hyper-fetch/core\";\nimport { parseResponse, scopeKey } from \"@hyper-fetch/core\";\n\nimport type { HydratedEntry, HydrateOptionsType } from \"./hydrate.types\";\n\n/**\n * Items already written to the cache (or skipped because the cache held newer data), per client.\n * Once an item is consumed the cache is the source of truth, so a hook mounted after `client.clear()`\n * does not get the old server snapshot back.\n */\nconst consumedItems = new WeakMap<ClientInstance, WeakSet<HydrateDataType>>();\n\nconst getConsumed = (client: ClientInstance) => {\n let consumed = consumedItems.get(client);\n if (!consumed) {\n consumed = new WeakSet();\n consumedItems.set(client, consumed);\n }\n return consumed;\n};\n\nexport const isConsumed = (client: ClientInstance, item: HydrateDataType) => {\n return getConsumed(client).has(item);\n};\n\nexport const markConsumed = (client: ClientInstance, item: HydrateDataType) => {\n getConsumed(client).add(item);\n};\n\n/**\n * Resolves the config of a single item exactly like `client.hydrate()` does\n */\nconst resolveConfig = (item: HydrateDataType, options?: HydrateOptionsType) => {\n const { cacheKey, scope, response: _response, ...fallbackOptions } = item;\n const defaults = { cache: true, override: true } satisfies Partial<HydrationOptions>;\n const config =\n typeof options === \"function\"\n ? { ...defaults, ...fallbackOptions, ...options(item) }\n : { ...defaults, ...fallbackOptions, ...options };\n\n return { ...config, cacheKey, scope };\n};\n\nconst getResponseTimestamp = (value: NullableType<{ responseTimestamp?: number | null }>, fallback = 0) => {\n const timestamp = Number(value?.responseTimestamp);\n return Number.isFinite(timestamp) ? timestamp : fallback;\n};\n\n/**\n * Turns dehydrated items into the values they will have in the cache, keyed by storage key.\n * The last item wins when the same key is passed twice.\n */\nexport const getHydratedEntries = (\n client: ClientInstance,\n data: NullableType<(HydrateDataType | EmptyTypes)[]>,\n options?: HydrateOptionsType,\n): Map<string, HydratedEntry> => {\n const entries = new Map<string, HydratedEntry>();\n\n data?.forEach((item) => {\n if (!item) {\n return;\n }\n\n const config = resolveConfig(item, options);\n const response = parseResponse(item.response);\n const storageKey = scopeKey(config.cacheKey, config.scope ?? null);\n\n // Mirrors the value created by `cache.set()`, so the first render matches the state after the write\n const value = {\n ...response,\n cacheKey: config.cacheKey,\n scope: config.scope ?? null,\n staleTime: config.staleTime,\n cacheTime: config.cacheTime,\n version: client.cache.version,\n cached: !!config.cache,\n } as CacheValueType;\n\n entries.set(storageKey, {\n item,\n storageKey,\n value,\n override: config.override !== false,\n timestamp: getResponseTimestamp(response, item.timestamp ?? 0),\n });\n });\n\n return entries;\n};\n\n/**\n * Decides whether the hydrated value should be used instead of the cached one.\n * Newer data always wins; with `override: false` existing cache data is kept.\n */\nexport const shouldUseHydratedValue = (cacheData: NullableType<CacheValueType>, entry: HydratedEntry): boolean => {\n if (!cacheData) {\n return true;\n }\n if (!entry.override) {\n return false;\n }\n return entry.timestamp > getResponseTimestamp(cacheData);\n};\n\n/**\n * Picks the data a hook should start with: cached data, unless the hydrated data is newer\n */\nexport const pickInitialCacheData = <T extends CacheValueType>(\n cacheData: NullableType<T>,\n entry: NullableType<HydratedEntry>,\n): NullableType<T> => {\n if (!entry || !shouldUseHydratedValue(cacheData, entry)) {\n return cacheData;\n }\n return entry.value as T;\n};\n","import React, { useContext, useEffect, useLayoutEffect, useMemo, useRef } from \"react\";\n\nimport type { HydrateProps, HydrationContextType } from \"./hydrate.types\";\nimport { getHydratedEntries, isConsumed, markConsumed, shouldUseHydratedValue } from \"./hydrate.utils\";\n\nconst HydrationContext = React.createContext<HydrationContextType | null>(null);\n\n// Layout effects do not run on the server; on the client they run before any passive effect of the tree\nconst useIsomorphicLayoutEffect = typeof window !== \"undefined\" ? useLayoutEffect : useEffect;\n\n/**\n * Hydrates the client cache with data fetched on the server.\n *\n * - Hooks below it render with the hydrated data on the first render, also during server rendering.\n * - On the client the data is written to the cache before the hooks mount, so fresh data is not refetched.\n * - Newer cache data is never replaced by an older snapshot.\n * - It can be nested and rendered conditionally; every `Hydrate` serves only its own client.\n */\nexport const Hydrate = ({ client, data, options, children }: HydrateProps) => {\n const parent = useContext(HydrationContext);\n\n const entries = useMemo(() => getHydratedEntries(client, data, options), [client, data, options]);\n\n // Read through a ref, so the context value stays stable when only the entries change (e.g. inline options)\n // and memoized children do not re-render. Hooks read the context only on their first render.\n const entriesRef = useRef(entries);\n entriesRef.current = entries;\n\n useIsomorphicLayoutEffect(() => {\n // Server mode cache does not store unscoped data - the context keeps serving it instead\n if (client.mode === \"server\") {\n return;\n }\n\n entries.forEach((entry) => {\n if (isConsumed(client, entry.item)) {\n return;\n }\n markConsumed(client, entry.item);\n\n const cacheData = client.cache.get(entry.storageKey);\n if (!shouldUseHydratedValue(cacheData, entry)) {\n return;\n }\n\n client.hydrate([entry.item], options);\n });\n }, [client, entries, options]);\n\n const value = useMemo<HydrationContextType>(\n () => ({\n get: (targetClient, storageKey) => {\n if (targetClient === client) {\n const entry = entriesRef.current.get(storageKey);\n if (entry) {\n return isConsumed(client, entry.item) ? undefined : entry;\n }\n }\n return parent?.get(targetClient, storageKey);\n },\n }),\n [client, parent],\n );\n\n return <HydrationContext.Provider value={value}>{children}</HydrationContext.Provider>;\n};\n\n/**\n * Access to the closest hydration data\n * @internal\n */\nexport const useHydration = (): HydrationContextType | null => {\n return useContext(HydrationContext);\n};\n","/**\n * Check if value is empty\n * @param value any object or primitive\n * @returns true when value is empty\n */\nexport const isEmpty = (value?: unknown): boolean => {\n const valueType = Object.prototype.toString.call(value);\n if (Array.isArray(value)) {\n return value.length === 0;\n }\n if (typeof value === \"object\" && value !== null && valueType === \"[object Object]\") {\n return Object.keys(value).length === 0;\n }\n return false;\n};\n\n/**\n * Allow to deep compare any passed values\n * @param firstValue unknown\n * @param secondValue unknown\n * @returns true when elements are equal\n */\nexport const isEqual = (firstValue?: unknown, secondValue?: unknown): boolean => {\n // Nulls (objects), and other primitives\n if (firstValue === secondValue) {\n return true;\n }\n\n try {\n const firstValueType = Object.prototype.toString.call(firstValue);\n const secondValueType = Object.prototype.toString.call(secondValue);\n\n const firstType = typeof firstValue;\n const secondType = typeof secondValue;\n\n const isType = (type: unknown) => firstType === type && secondType === type;\n const isTypeValue = (type: unknown) => firstValueType === type && secondValueType === type;\n\n // Compared types are different\n if (firstValueType !== secondValueType) {\n return false;\n }\n\n // NaN\n if (isType(\"number\") && Number.isNaN(firstValue) && Number.isNaN(secondValue)) {\n return true;\n }\n\n // Empty Array or Object\n if (isEmpty(firstValue) && isEmpty(secondValue)) {\n return true;\n }\n\n // Array\n if (Array.isArray(firstValue) && Array.isArray(secondValue)) {\n if (firstValue.length !== secondValue.length) {\n return false;\n }\n\n return !firstValue.some((element, i) => !isEqual(element, secondValue[i]));\n }\n\n // Object\n if (isType(\"object\") && isTypeValue(\"[object Object]\")) {\n if (Object.keys(firstValue as object).length !== Object.keys(secondValue as object).length) {\n return false;\n }\n\n return !Object.entries(firstValue as object).some(\n ([key, value]) => !isEqual(value, (secondValue as Record<string, unknown>)[key]),\n );\n }\n\n // Date\n if (firstValue instanceof Date && secondValue instanceof Date) {\n return +firstValue === +secondValue;\n }\n\n // undefined, string, number, bool\n return firstValue === secondValue;\n } catch (error) {\n console.error(error);\n return false;\n }\n};\n","export const getBounceData = (bounceData: {\n reset: () => void;\n active: boolean;\n}): { reset: () => void; active: boolean } => {\n return {\n ...bounceData,\n // oxlint-disable-next-line unicorn/no-useless-spread\n ...{ throttle: undefined, debounce: undefined },\n };\n};\n","/**\n * Wraps a plain object in a Proxy that calls `setRenderKey` when tracked properties are accessed.\n * Unlike getter-based tracking, Proxy-wrapped objects display their actual values in console.log,\n * making debugging significantly easier while preserving field-level dependency tracking.\n */\nexport const createTrackedProxy = <T extends Record<string, unknown>, K extends string>(\n target: T,\n trackedKeys: readonly K[],\n setRenderKey: (key: K) => void,\n): T => {\n return new Proxy(target, {\n get(obj, prop, receiver) {\n if (typeof prop === \"string\" && trackedKeys.includes(prop as K)) {\n setRenderKey(prop as K);\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n};\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport type {\n CacheValueType,\n NullableType,\n RequestInstance,\n ExtractResponseType,\n ExtractErrorType,\n ExtractAdapterResolvedType,\n Dispatcher,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ResponseDetailsType,\n ExtractAdapterStatusType,\n ResponseType,\n} from \"@hyper-fetch/core\";\nimport { runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport type { UseTrackedStateType } from \"helpers\";\nimport { initialState } from \"helpers\";\nimport type { HydratedEntry } from \"hydrate/hydrate.types\";\nimport { pickInitialCacheData } from \"hydrate/hydrate.utils\";\n\n/**\n * Extracts the \"identity\" portion of a cache key (method + endpoint with resolved params),\n * stripping the query params part. Cache keys follow the format: `method_endpoint_queryParams`.\n */\nconst getCacheKeyIdentity = (cacheKey: string): string => {\n const lastUnderscoreIndex = cacheKey.lastIndexOf(\"_\");\n if (lastUnderscoreIndex === -1) {return cacheKey;}\n return cacheKey.substring(0, lastUnderscoreIndex);\n};\n\n/**\n * Determines whether state should be cleared when the cache key changes.\n *\n * - `\"clean\"` — always clear\n * - `\"preserve\"` — never clear\n * - `\"auto\"` — clear when the resource identity changed (URL params), preserve when only query params changed\n */\nexport const getShouldClearState = (\n mode: \"auto\" | \"preserve\" | \"clean\",\n oldCacheKey: string,\n newCacheKey: string,\n): boolean => {\n if (oldCacheKey === newCacheKey) {return false;}\n\n if (mode === \"clean\") {return true;}\n if (mode === \"preserve\") {return false;}\n\n // \"auto\" — compare the identity part (method + endpoint with params)\n return getCacheKeyIdentity(oldCacheKey) !== getCacheKeyIdentity(newCacheKey);\n};\n\nexport const getDetailsState = (\n state?: UseTrackedStateType<RequestInstance>,\n details?: Partial<ResponseDetailsType>,\n): ResponseDetailsType => {\n return {\n retries: state?.retries || 0,\n isCanceled: false,\n isOffline: false,\n willRetry: false,\n addedTimestamp: Date.now(),\n triggerTimestamp: Date.now(),\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n ...details,\n };\n};\n\nexport const isStaleCacheData = (staleTime: number, staleTimestamp: NullableType<Date | number>) => {\n if (!staleTimestamp) {return true;}\n return Date.now() > +staleTimestamp + staleTime;\n};\n\nexport const getValidCacheData = <T extends RequestInstance>(\n request: T,\n initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>,\n cacheData: NullableType<CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>>,\n): CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>> | null => {\n if (cacheData) {\n return cacheData;\n }\n\n if (initialResponse) {\n return {\n data: null,\n error: null,\n status: null,\n success: true,\n extra: null,\n cached: !!request.cache,\n ...(initialResponse as Partial<ExtractAdapterResolvedType<T>>),\n ...getDetailsState(),\n staleTime: 1000,\n version: request.client.cache.version,\n cacheKey: request.cacheKey,\n scope: request.scope,\n cacheTime: request.cacheTime,\n requestTimestamp: initialResponse?.requestTimestamp ?? Date.now(),\n responseTimestamp: initialResponse?.responseTimestamp ?? Date.now(),\n };\n }\n\n return null;\n};\n\nexport const getTimestamp = (timestamp?: NullableType<number | Date>) => {\n return timestamp ? new Date(timestamp) : null;\n};\n\nexport const getIsInitiallyLoading = <T extends RequestInstance>({\n queryKey,\n dispatcher,\n hasState,\n revalidate,\n disabled,\n}: {\n queryKey: string;\n dispatcher: Dispatcher<ExtractAdapterType<T>>;\n hasState: boolean;\n revalidate?: boolean;\n disabled?: boolean;\n}) => {\n if (!revalidate && hasState) {\n return false;\n }\n\n const queue = dispatcher.getQueue(queryKey);\n const isInitiallyLoading = dispatcher.hasRunningRequests(queryKey) || (!queue.stopped && disabled === false);\n\n return isInitiallyLoading;\n};\n\nexport const getInitialState = <T extends RequestInstance>({\n initialResponse,\n dispatcher,\n request,\n disabled,\n revalidate,\n hydratedEntry,\n}: {\n initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>;\n dispatcher: Dispatcher<ExtractAdapterType<T>>;\n request: T;\n disabled?: boolean; // useFetch only\n revalidate?: boolean; // useFetch only\n /** Data from the closest `Hydrate` that was not written to the cache yet */\n hydratedEntry?: NullableType<HydratedEntry>;\n}): UseTrackedStateType<T> => {\n const { client, cacheKey } = request;\n const { cache } = client;\n\n const cacheData = pickInitialCacheData(\n cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopeKey(cacheKey, request.scope)),\n hydratedEntry,\n );\n const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);\n\n const initialLoading = getIsInitiallyLoading({\n queryKey: scopeKey(request.queryKey, request.scope),\n dispatcher,\n disabled,\n revalidate,\n hasState: !!cacheState,\n });\n\n if (cacheState) {\n const mappedData =\n runResponseMapper(request, cacheState as ResponseType<any, any, ExtractAdapterType<T>>) || cacheState;\n if (mappedData instanceof Promise) {\n // For the async mapper we cannot return async values\n // So we have return the initial state instead\n return initialState;\n }\n return {\n data: mappedData.data,\n error: mappedData.error,\n status: mappedData.status as ExtractAdapterStatusType<ExtractAdapterType<T>>,\n success: mappedData.success,\n extra: (mappedData.extra || client.adapter.defaultExtra) as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: cacheState.retries,\n requestTimestamp: getTimestamp(cacheState.requestTimestamp),\n responseTimestamp: getTimestamp(cacheState.responseTimestamp),\n loading: initialLoading,\n };\n }\n\n return {\n data: initialState.data,\n error: initialState.error,\n status: initialState.status as ExtractAdapterStatusType<ExtractAdapterType<T>>,\n success: initialState.success,\n extra: request.client.adapter.defaultExtra as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: initialState.retries,\n requestTimestamp: getTimestamp(initialState.requestTimestamp),\n responseTimestamp: getTimestamp(initialState.responseTimestamp),\n loading: initialLoading,\n };\n};\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type {\n ExtractErrorType,\n CacheValueType,\n ExtractResponseType,\n RequestInstance,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ResponseType,\n} from \"@hyper-fetch/core\";\nimport { replaceEqualDeep, runResponseMapper, scopeKey } from \"@hyper-fetch/core\";\nimport { useHydration } from \"hydrate/hydrate\";\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport { isEqual } from \"utils\";\n\nimport type {\n UseTrackedStateActions,\n UseTrackedStateType,\n UseTrackedStateProps,\n UseTrackedStateReturn,\n UseTrackedStateResponseDetails,\n} from \"./use-tracked-state.types\";\nimport {\n getInitialState,\n getIsInitiallyLoading,\n getShouldClearState,\n getValidCacheData,\n isStaleCacheData,\n} from \"./use-tracked-state.utils\";\n\n/**\n *\n * @param request\n * @param initialResponse\n * @param dispatcher\n * @param dependencies\n * @internal\n */\nexport const useTrackedState = <T extends RequestInstance, TData = ExtractResponseType<T>>({\n request,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n keepPreviousData = \"auto\",\n disabled,\n revalidate,\n select,\n structuralSharing = true,\n}: UseTrackedStateProps<T, TData>): UseTrackedStateReturn<T, TData> => {\n const { client, cacheKey, queryKey, staleTime } = request;\n const { cache } = client;\n const hydration = useHydration();\n\n const state = useRef<UseTrackedStateType<T, TData>>(null as unknown as UseTrackedStateType<T, TData>);\n const renderKeys = useRef<(keyof UseTrackedStateType<T, TData>)[]>([]);\n const isProcessingData = useRef(\"\");\n const previousCacheKey = useRef(cacheKey);\n\n // ******************\n // Data selection\n // ******************\n\n const selectRef = useRef(select);\n selectRef.current = select;\n const appliedSelect = useRef(select);\n // Response data before applying the selector - allows to re-run it when the selector changes\n const rawData = useRef<ExtractResponseType<T> | null>(null);\n // Data set with the setData action has the selected shape and should not get re-selected\n const isLocalData = useRef(false);\n const selectError = useRef<{ error: unknown } | null>(null);\n const responseDetails = useRef<UseTrackedStateResponseDetails | null>(null);\n\n const selectData = (data: ExtractResponseType<T> | null, previousData: TData | null = null): TData | null => {\n if (!selectRef.current || data === null || data === undefined) {\n return data as TData | null;\n }\n const selected = selectRef.current(data);\n return structuralSharing ? replaceEqualDeep(previousData, selected) : selected;\n };\n\n const getSelectedState = (newState: UseTrackedStateType<T>): UseTrackedStateType<T, TData> => {\n rawData.current = newState.data;\n isLocalData.current = false;\n responseDetails.current = null;\n appliedSelect.current = selectRef.current;\n return { ...newState, data: selectData(newState.data, state.current?.data) };\n };\n\n if (!state.current) {\n const hydratedEntry = hydration?.get(client, scopeKey(cacheKey, request.scope));\n state.current = getSelectedState(\n getInitialState({ initialResponse, dispatcher, request, disabled, hydratedEntry }),\n );\n }\n\n // Selector failed while processing incoming data - surface it to the closest error boundary\n if (selectError.current) {\n const { error } = selectError.current;\n selectError.current = null;\n throw error;\n }\n\n // Selector changed (e.g. it closes over a new prop) - re-run it against the latest response data\n if (appliedSelect.current !== select && !isLocalData.current) {\n appliedSelect.current = select;\n state.current.data = selectData(rawData.current, state.current.data);\n }\n\n // ******************\n // useSyncExternalStore\n // ******************\n\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n // ******************\n // Utils\n // ******************\n\n const getStaleStatus = (): boolean => {\n const cacheData = cache.get(scopeKey(cacheKey, request.scope));\n return !cacheData || isStaleCacheData(staleTime, cacheData?.responseTimestamp);\n };\n\n // ******************\n // Dependency Tracking\n // ******************\n\n const renderKeyTrigger = (keys: (keyof UseTrackedStateType<T, TData>)[]) => {\n const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));\n if (shouldRerender) {emitChange();}\n };\n\n const setRenderKey = (renderKey: keyof UseTrackedStateType<T, TData>) => {\n if (!renderKeys.current.includes(renderKey)) {\n renderKeys.current.push(renderKey);\n }\n };\n\n // ******************\n // Cache initialization\n // ******************\n\n useDidUpdate(\n () => {\n const oldKey = previousCacheKey.current;\n previousCacheKey.current = cacheKey;\n\n // Get cache state\n const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopeKey(cacheKey, request.scope));\n const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);\n\n // Determine whether to clear state based on keepPreviousData mode\n const shouldClear = getShouldClearState(keepPreviousData, oldKey, cacheKey);\n\n if (shouldClear && !cacheState) {\n // Reset state to initial values when no cached data exists for the new key\n const resetState = getInitialState({ initialResponse, dispatcher, request, disabled, revalidate });\n state.current = getSelectedState(resetState);\n renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T, TData>)[]);\n } else if (cacheState) {\n state.current.loading = getIsInitiallyLoading({\n queryKey: scopeKey(request.queryKey, request.scope),\n dispatcher,\n disabled,\n revalidate,\n hasState: true,\n });\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n setCacheData(cacheState);\n }\n // When state is preserved and no cache exists (e.g. query param change in \"auto\" mode),\n // don't update loading on the ref — let the dispatcher's loading event handle it (#126)\n },\n [cacheKey, queryKey],\n true,\n );\n\n // ******************\n // Turn off dependency tracking\n // ******************\n\n useDidUpdate(\n () => {\n const handleDependencyTracking = () => {\n if (!dependencyTracking) {\n Object.keys(state.current).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0]));\n }\n };\n\n handleDependencyTracking();\n },\n [dependencyTracking],\n true,\n );\n\n // ******************\n // Cache data handler\n // ******************\n\n const handleCompare = (firstValue: unknown, secondValue: unknown) => {\n if (Object.is(firstValue, secondValue)) {\n return true;\n }\n if (typeof deepCompare === \"function\") {\n return deepCompare(firstValue, secondValue);\n }\n if (deepCompare) {\n return isEqual(firstValue, secondValue);\n }\n return false;\n };\n\n const handleCacheData = (\n cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>,\n ) => {\n rawData.current = cacheData.data;\n isLocalData.current = false;\n appliedSelect.current = selectRef.current;\n responseDetails.current = {\n willRetry: !!cacheData.willRetry,\n isCanceled: !!cacheData.isCanceled,\n isOffline: !!cacheData.isOffline,\n };\n\n let data: TData | null;\n try {\n data = selectData(cacheData.data, state.current.data);\n } catch (error) {\n // Never throw inside of the cache events - rethrow it on render instead\n selectError.current = { error };\n emitChange();\n return;\n }\n\n const newStateValues: UseTrackedStateType<T, TData> = {\n data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra as ExtractAdapterExtraType<ExtractAdapterType<T>>,\n retries: cacheData.retries,\n responseTimestamp: new Date(cacheData.responseTimestamp),\n requestTimestamp: new Date(cacheData.requestTimestamp),\n loading: dispatcher.hasRunningRequests(scopeKey(queryKey, request.scope)),\n };\n\n const nextState: UseTrackedStateType<T, TData> = { ...state.current };\n const changedKeys = (Object.keys(newStateValues) as (keyof UseTrackedStateType<T, TData>)[]).filter((key) => {\n const isEqualValue = handleCompare(state.current[key], newStateValues[key]);\n // Equal values keep their previous reference, so they stay stable between renders\n if (!isEqualValue) {\n (nextState as Record<string, unknown>)[key] = newStateValues[key];\n }\n return !isEqualValue;\n });\n\n state.current = nextState;\n\n renderKeyTrigger(changedKeys);\n };\n\n const setIsDataProcessing = ({\n processingCacheKey,\n isProcessing,\n }: {\n processingCacheKey: string;\n isProcessing: boolean;\n }) => {\n if (isProcessing) {\n isProcessingData.current = processingCacheKey;\n }\n // Do not turn off other keys processing\n else if (isProcessingData.current === cacheKey) {\n isProcessingData.current = \"\";\n }\n };\n\n const getIsDataProcessing = (processingCacheKey: string) => {\n return isProcessingData.current === processingCacheKey;\n };\n\n const setCacheData = (\n cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>,\n ): Promise<void> | void => {\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: true });\n const data = runResponseMapper(request, cacheData as ResponseType<any, any, ExtractAdapterType<T>>) || cacheData;\n\n if (data instanceof Promise) {\n return (async () => {\n const promiseData = await data;\n handleCacheData({ ...cacheData, ...promiseData } as CacheValueType<\n ExtractResponseType<T>,\n ExtractErrorType<T>,\n ExtractAdapterType<T>\n >);\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: false });\n })();\n }\n setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: false });\n return handleCacheData({ ...cacheData, ...data } as CacheValueType<\n ExtractResponseType<T>,\n ExtractErrorType<T>,\n ExtractAdapterType<T>\n >);\n };\n\n // ******************\n // Actions\n // ******************\n\n const actions: UseTrackedStateActions<T, TData> = {\n setData: (data) => {\n isLocalData.current = true;\n state.current.data = data instanceof Function ? data(state.current.data || null) : data;\n renderKeyTrigger([\"data\"]);\n },\n setError: (error) => {\n state.current.error = error instanceof Function ? error(state.current.error || null) : error;\n renderKeyTrigger([\"error\"]);\n },\n setLoading: (loading) => {\n const value = loading instanceof Function ? loading(state.current.loading) : loading;\n if (value === state.current.loading) {return;}\n state.current.loading = value;\n renderKeyTrigger([\"loading\"]);\n },\n setStatus: (status) => {\n const value = status instanceof Function ? status(state.current.status) : status;\n if (value === state.current.status) {return;}\n state.current.status = status instanceof Function ? status(state.current.status || null) : status;\n renderKeyTrigger([\"status\"]);\n },\n setSuccess: (success) => {\n const value = success instanceof Function ? success(state.current.success || false) : success;\n if (value === state.current.success) {return;}\n state.current.success = success instanceof Function ? success(state.current.success || false) : success;\n renderKeyTrigger([\"success\"]);\n },\n setExtra: (extra) => {\n const value = extra instanceof Function ? extra(state.current.extra) : extra;\n if (value === state.current.extra) {return;}\n state.current.extra = extra instanceof Function ? extra(state.current.extra) : extra;\n renderKeyTrigger([\"extra\"]);\n },\n setRetries: (retries) => {\n const value = retries instanceof Function ? retries(state.current.retries || 0) : retries;\n if (value === state.current.retries) {return;}\n state.current.retries = retries instanceof Function ? retries(state.current.retries || 0) : retries;\n renderKeyTrigger([\"retries\"]);\n },\n setResponseTimestamp: (timestamp) => {\n const value = timestamp instanceof Function ? timestamp(state.current.responseTimestamp) : timestamp;\n if (value === state.current.responseTimestamp) {return;}\n const getTimestamp = (prev: Date | null) => {\n return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;\n };\n\n state.current.responseTimestamp = getTimestamp(state.current.responseTimestamp);\n renderKeyTrigger([\"responseTimestamp\"]);\n },\n setRequestTimestamp: (timestamp) => {\n const value = timestamp instanceof Function ? timestamp(state.current.requestTimestamp) : timestamp;\n if (value === state.current.requestTimestamp) {return;}\n const getTimestamp = (prev: Date | null) => {\n return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;\n };\n\n state.current.requestTimestamp = getTimestamp(state.current.requestTimestamp);\n renderKeyTrigger([\"requestTimestamp\"]);\n },\n clearState: () => {\n rawData.current = null;\n isLocalData.current = false;\n responseDetails.current = null;\n state.current = {\n data: null,\n error: null,\n loading: false,\n status: null,\n success: false,\n extra: null,\n retries: 0,\n responseTimestamp: null,\n requestTimestamp: null,\n } as UseTrackedStateType<T, TData>;\n renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T, TData>)[]);\n },\n };\n\n return [\n state.current,\n actions,\n {\n setRenderKey,\n setCacheData,\n getStaleStatus,\n getIsDataProcessing,\n selectData: (data) => selectData(data, state.current.data),\n getResponseDetails: () => responseDetails.current,\n },\n ];\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { SocketInstance, ExtractSocketExtraType } from \"@hyper-fetch/sockets\";\nimport type { UseSocketStateType, UseSocketStateProps } from \"helpers\";\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\n\nexport const useSocketState = <DataType, Socket extends SocketInstance>(\n socket: Socket,\n { dependencyTracking }: UseSocketStateProps,\n) => {\n const onDisconnectCallback = useRef<null | VoidFunction>(null);\n const onErrorCallback = useRef<null | ((event: any) => void)>(null);\n const onConnectedCallback = useRef<null | VoidFunction>(null);\n const onConnectingCallback = useRef<null | VoidFunction>(null);\n const onReconnectingCallback = useRef<null | ((data: { attempts: number }) => void)>(null);\n const onReconnectingFailedCallback = useRef<null | ((data: { attempts: number }) => void)>(null);\n\n const state = useRef<UseSocketStateType<Socket, DataType>>({\n data: null,\n extra: null,\n connected: socket.adapter.connected,\n connecting: socket.adapter.connecting,\n timestamp: null,\n });\n const renderKeys = useRef<(keyof UseSocketStateType<Socket, DataType>)[]>([]);\n\n // ******************\n // useSyncExternalStore\n // ******************\n\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n // ******************\n // Dependency Tracking\n // ******************\n\n const renderKeyTrigger = (keys: (keyof UseSocketStateType<Socket, DataType>)[]) => {\n const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));\n if (shouldRerender) {emitChange();}\n };\n\n const setRenderKey = (renderKey: keyof UseSocketStateType<Socket, DataType>) => {\n if (!renderKeys.current.includes(renderKey)) {\n renderKeys.current.push(renderKey);\n }\n };\n\n // ******************\n // Turn off dependency tracking\n // ******************\n\n useDidUpdate(\n () => {\n const handleDependencyTracking = () => {\n if (!dependencyTracking) {\n Object.keys(state.current).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0]));\n }\n };\n\n handleDependencyTracking();\n },\n [dependencyTracking],\n true,\n );\n\n // ******************\n // Actions\n // ******************\n\n const actions = {\n setData: (data: DataType | null) => {\n state.current.data = data;\n renderKeyTrigger([\"data\"]);\n },\n setExtra: (extra: ExtractSocketExtraType<Socket> | null) => {\n state.current.extra = extra;\n renderKeyTrigger([\"extra\"]);\n },\n setConnected: (connected: boolean) => {\n state.current.connected = connected;\n renderKeyTrigger([\"connected\"]);\n },\n setConnecting: (connecting: boolean) => {\n state.current.connecting = connecting;\n renderKeyTrigger([\"connecting\"]);\n },\n setTimestamp: (timestamp: number | null) => {\n state.current.timestamp = timestamp;\n renderKeyTrigger([\"timestamp\"]);\n },\n clearState: () => {\n state.current = {\n data: null,\n extra: null,\n connected: false,\n connecting: false,\n timestamp: null,\n };\n renderKeyTrigger(Object.keys(state.current) as (keyof UseSocketStateType<Socket, DataType>)[]);\n },\n };\n\n const callbacks = {\n onConnected: (callback: VoidFunction) => {\n onConnectedCallback.current = callback;\n },\n onDisconnected: (callback: VoidFunction) => {\n onDisconnectCallback.current = callback;\n },\n onError: <ErrorType = Event>(callback: (event: ErrorType) => void) => {\n onErrorCallback.current = callback;\n },\n onConnecting: (callback: VoidFunction) => {\n onConnectingCallback.current = callback;\n },\n onReconnecting: (callback: (data: { attempts: number }) => void) => {\n onReconnectingCallback.current = callback;\n },\n onReconnectingFailed: (callback: (data: { attempts: number }) => void) => {\n onReconnectingFailedCallback.current = callback;\n },\n };\n\n // ******************\n // Hook to events\n // ******************\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without any subscriptions\n useEffect(() => {\n // Catch up with anything that happened between the render and the subscription\n if (state.current.connected !== socket.adapter.connected) {\n actions.setConnected(socket.adapter.connected);\n }\n if (state.current.connecting !== socket.adapter.connecting) {\n actions.setConnecting(socket.adapter.connecting);\n }\n\n const umountOnError = socket.events.onError((event) => {\n onErrorCallback.current?.(event);\n });\n const umountOnConnecting = socket.events.onConnecting(({ connecting }) => {\n actions.setConnecting(connecting);\n onConnectingCallback.current?.();\n });\n const umountOnOpen = socket.events.onConnected(() => {\n actions.setConnected(true);\n onConnectedCallback.current?.();\n });\n const umountOnClose = socket.events.onDisconnected(() => {\n actions.setConnected(false);\n onDisconnectCallback.current?.();\n });\n const umountOnReconnecting = socket.events.onReconnecting(({ attempts }) => {\n onReconnectingCallback.current?.({ attempts });\n });\n const umountOnReconnectingFailed = socket.events.onReconnectingFailed(({ attempts }) => {\n onReconnectingFailedCallback.current?.({ attempts });\n });\n\n return () => {\n umountOnError();\n umountOnConnecting();\n umountOnOpen();\n umountOnClose();\n umountOnReconnecting();\n umountOnReconnectingFailed();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [socket]);\n\n const getState = () => state.current;\n\n return [state.current, actions, callbacks, { setRenderKey, getState, rerender: emitChange }] as const;\n};\n","import type { SocketInstance } from \"@hyper-fetch/sockets\";\n\nimport type { UseSocketStateType } from \"./use-socket-state.types\";\n\nexport const initialSocketState: UseSocketStateType<SocketInstance> = {\n data: null,\n extra: null,\n connected: false,\n connecting: false,\n timestamp: null,\n};\n","import React, { useContext, useMemo, useState } from \"react\";\n\nimport type { ProviderProps, ProviderValueType } from \"./provider.types\";\n\nconst ConfigContext = React.createContext<ProviderValueType>({\n config: {},\n setConfig: () => null,\n});\n\n/**\n * Provider with configuration for hooks\n * @param options\n * @returns\n */\nexport const Provider = ({ children, config }: ProviderProps) => {\n const [currentConfig, setConfig] = useState(config || {});\n\n const value = useMemo(() => {\n const contextValue: ProviderValueType = { config: currentConfig, setConfig };\n return contextValue;\n }, [currentConfig]);\n\n return <ConfigContext.Provider value={value}>{children}</ConfigContext.Provider>;\n};\n\n/**\n * Hook to allow reading current context config\n * @returns\n */\nexport const useProvider = (): ProviderValueType => {\n const config = useContext(ConfigContext);\n return config;\n};\n","import { useDidUpdate, useDidMount, useWillUnmount } from \"@better-hooks/lifecycle\";\nimport { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n ClientInstance,\n RequestInstance,\n ExtractAdapterStatusType,\n ExtractAdapterType,\n ExtractAdapterExtraType,\n ExtractErrorType,\n ExtractResponseType,\n} from \"@hyper-fetch/core\";\nimport { scopeKey } from \"@hyper-fetch/core\";\nimport { useRequestEvents, useTrackedState } from \"helpers\";\nimport type { UseFetchOptionsType, UseFetchReturnType } from \"hooks/use-fetch\";\nimport { useFetchDefaultOptions } from \"hooks/use-fetch\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\nimport { isSameScope } from \"utils/scope.utils\";\n\ntype SuspenseEntry = { promise: Promise<void>; resolve: () => void; cleanup: () => void };\ntype SuspenseResult = { data: any; error: any; status: any; extra: any; success: boolean };\ntype SuspenseStore = { promises: Map<string, SuspenseEntry>; results: Map<string, SuspenseResult> };\n\n// Kept per client and keyed by the scoped cache key, so clients and scopes sharing a cache key never\n// wait on or receive each other's suspense results\nconst suspenseStores = new WeakMap<ClientInstance, SuspenseStore>();\n\n// Data received this recently is not refetched when a suspended component mounts\nconst suspenseFreshTime = 1000;\n\nconst getSuspenseStore = (client: ClientInstance): SuspenseStore => {\n let store = suspenseStores.get(client);\n if (!store) {\n store = { promises: new Map(), results: new Map() };\n suspenseStores.set(client, store);\n }\n return store;\n};\n\n/**\n * This hook aims to retrieve data from the server. It automatically fetches on mount and\n * refetches based on dependencies, with support for caching, polling, and suspense.\n * @param request Request instance\n * @param options Hook options\n * @returns\n */\nexport const useFetch = <R extends RequestInstance, TSelected = ExtractResponseType<R>>(\n request: R,\n options?: UseFetchOptionsType<R, TSelected>,\n): UseFetchReturnType<R, TSelected> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const {\n suspense,\n dependencies,\n disabled,\n dependencyTracking,\n revalidate,\n initialResponse,\n keepPreviousData,\n refresh,\n refreshTime,\n refetchBlurred,\n refetchOnBlur,\n refetchOnFocus,\n refetchOnReconnect,\n bounce,\n bounceType,\n bounceTime,\n bounceTimeout,\n deepCompare,\n structuralSharing,\n throwOnError,\n } = {\n ...useFetchDefaultOptions,\n ...globalConfig.useFetchConfig,\n ...options,\n };\n\n const updateKey = JSON.stringify(request.toJSON());\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({ interval: bounceTime, timeout: bounceTimeout });\n const refreshDebounce = useDebounce({ delay: refreshTime });\n\n const { cacheKey, queryKey, client } = request;\n const { cache, fetchDispatcher: dispatcher, appManager, loggerManager } = client;\n\n const ignoreReact18DoubleRender = useRef(true);\n const resolvedBySuspense = useRef(false);\n const logger = useRef(loggerManager.initialize(client, \"useFetch\")).current;\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n /**\n * State handler with optimization for re-rendering, that hooks into the cache state and dispatchers queues\n */\n const [\n state,\n actions,\n { setRenderKey, setCacheData, getStaleStatus, getIsDataProcessing, selectData, getResponseDetails },\n ] = useTrackedState<R, TSelected>({\n logger,\n request: request as unknown as R,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n keepPreviousData,\n disabled,\n revalidate,\n select: options?.select,\n structuralSharing,\n });\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [callbacks, listeners] = useRequestEvents<R>({\n logger,\n actions,\n request: request as unknown as R,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners, clearCacheDataListener } = listeners;\n\n // ******************\n // Fetching\n // ******************\n const handleFetch = (options?: { force?: boolean }) => {\n if (!disabled) {\n logger.debug({ title: `Fetching data`, type: \"system\", extra: { request } });\n // A forced fetch must not be deduplicated into an already running request: that request\n // started earlier, so its response can be older than the state that prompted the call.\n // Manual refetch() promises data at least as fresh as the moment it was called.\n const requestToAdd = options?.force ? request.setDeduplicate(false) : request;\n dispatcher.add(requestToAdd as unknown as R);\n } else {\n logger.debug({ title: `Cannot add to fetch queue`, type: \"system\", extra: { disabled } });\n }\n };\n\n // ******************\n // Refreshing\n // ******************\n\n function handleRefresh() {\n if (!refresh || disabled) {\n refreshDebounce.reset();\n return;\n }\n\n refreshDebounce.debounce(() => {\n const isBlurred = !appManager.isFocused;\n\n // If window tab is not active should we refresh the cache\n const scopedQueryKey = scopeKey(request.queryKey, request.scope);\n const isFetching = dispatcher.hasRunningRequests(scopedQueryKey);\n const isQueued = dispatcher.getIsActiveQueue(scopedQueryKey);\n const isActive = isFetching || isQueued;\n const canRefreshBlurred = isBlurred && refetchBlurred && !isActive;\n const canRefreshFocused = !isBlurred && !isActive;\n\n if (canRefreshBlurred || canRefreshFocused) {\n handleFetch();\n logger.debug({ title: `Performing refresh request`, type: \"system\", extra: { request } });\n }\n\n // Start new refresh counter\n handleRefresh();\n });\n }\n\n const refetch = () => {\n handleFetch({ force: true });\n handleRefresh();\n };\n\n // ******************\n // Fetching lifecycle\n // ******************\n\n // This help us to check for currently running requests\n const getIsFetchingIdentity = () => {\n // We need to check if the queryKey have the same cacheKey elements ongoing\n return dispatcher\n .getRunningRequests(scopeKey(queryKey, request.scope))\n .some((running) => running.request.cacheKey === cacheKey);\n };\n\n /**\n * A suspended component mounts right after its own request resolved - fetching again on mount would\n * duplicate that request. Data received within the last moment counts as fresh, like the minimal stale time\n * applied by other suspense-enabled libraries.\n */\n const getHasJustResolvedSuspense = () => {\n if (!suspense) {\n return false;\n }\n if (resolvedBySuspense.current) {\n return true;\n }\n const cacheData = cache.get(scopeKey(cacheKey, request.scope));\n return !!cacheData && Date.now() - cacheData.responseTimestamp < suspenseFreshTime;\n };\n\n const initialFetchData = () => {\n if (getHasJustResolvedSuspense()) {\n return;\n }\n const hasStaleData = getStaleStatus();\n const isFetching = getIsFetchingIdentity();\n if ((revalidate || hasStaleData) && !isFetching) {\n handleFetch();\n }\n };\n\n const updateFetchData = () => {\n const hasStaleData = getStaleStatus();\n const shouldUpdate = !revalidate ? hasStaleData : true;\n /**\n * This is a hack to avoid double rendering in React 18\n * It renders initial mount event and allow us to consume only hook updates\n */\n if (!ignoreReact18DoubleRender.current && shouldUpdate) {\n /**\n * While debouncing we need to make sure that first request is not debounced when the cache is not available\n * This way it will not wait for debouncing but fetch data right away\n */\n if (bounce) {\n logger.debug({ title: `Bounce request with ${bounceType}`, type: \"system\", extra: { queryKey, request } });\n bounceFunction(() => handleFetch());\n } else {\n handleFetch();\n }\n } else {\n ignoreReact18DoubleRender.current = false;\n }\n };\n\n // ******************\n // Events\n // ******************\n\n const handleMountEvents = () => {\n addCacheDataListener(request as unknown as R);\n addLifecycleListeners(request as unknown as R);\n\n const focusUnmount = appManager.events.onFocus(() => {\n if (refetchOnFocus && !disabled) {\n handleFetch();\n handleRefresh();\n }\n });\n const blurUnmount = appManager.events.onBlur(() => {\n if (refetchOnBlur && !disabled) {\n handleFetch();\n handleRefresh();\n }\n });\n const onlineUnmount = appManager.events.onOnline(() => {\n if (refetchOnReconnect && !disabled) {\n handleFetch();\n handleRefresh();\n }\n });\n\n const invalidateUnmount = cache.events.onInvalidateByKey(cacheKey, handleFetch);\n const deletionUnmount = cache.events.onDeleteByKey(cacheKey, handleFetch);\n\n const unmount = () => {\n clearCacheDataListener();\n focusUnmount();\n blurUnmount();\n onlineUnmount();\n invalidateUnmount();\n deletionUnmount();\n };\n\n return unmount;\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n /**\n * Initialization of the events related to data exchange with cache and queue\n * This allows to share the state with other hooks and keep it related\n */\n useDidUpdate(handleMountEvents, [updateKey, disabled], true);\n\n /**\n * Initial fetch triggered once data is stale or we use the refetch strategy\n */\n useDidMount(initialFetchData);\n\n /**\n * Fetching logic for updates handling\n */\n useDidUpdate(updateFetchData, [updateKey, disabled, ...dependencies], true);\n\n /**\n * Refresh lifecycle handler\n */\n useDidUpdate(handleRefresh, [updateKey, ...dependencies, disabled, refresh, refreshTime], true);\n\n /**\n * Reset the ignore flag for React 18 strict mode\n */\n useWillUnmount(() => {\n ignoreReact18DoubleRender.current = true;\n });\n\n // ******************\n // Suspense\n // ******************\n if (suspense && !disabled) {\n const { promises: suspensePromiseMap, results: suspenseResultMap } = getSuspenseStore(client);\n const suspenseKey = scopeKey(cacheKey, request.scope);\n\n // Apply any cached suspense result (covers error responses that aren't stored in cache)\n const suspenseResult = suspenseResultMap.get(suspenseKey);\n if (suspenseResult) {\n suspenseResultMap.delete(suspenseKey);\n // Error responses are not cached, so the mount logic cannot see they just arrived\n resolvedBySuspense.current = true;\n if (suspenseResult.data !== null) {\n state.data = selectData(suspenseResult.data);\n }\n if (suspenseResult.error !== null) {\n state.error = suspenseResult.error;\n }\n if (suspenseResult.status !== null) {\n state.status = suspenseResult.status;\n }\n if (suspenseResult.extra !== null) {\n state.extra = suspenseResult.extra;\n }\n state.success = suspenseResult.success;\n // The response has arrived - nothing is loading unless another request for this key is running\n state.loading = dispatcher.hasRunningRequests(scopeKey(queryKey, request.scope));\n }\n\n const hasData = state.data !== null || state.error !== null;\n\n if (!hasData) {\n let entry = suspensePromiseMap.get(suspenseKey);\n if (!entry) {\n let resolvePromise: () => void;\n const promise = new Promise<void>((r) => {\n resolvePromise = r;\n });\n\n // Cache events are emitted by the logical cacheKey - skip data of other scopes\n const unsubscribe = cache.events.onDataByKey(cacheKey, (cacheData: any) => {\n if (!isSameScope(cacheData.scope, request.scope)) {\n return;\n }\n suspenseResultMap.set(suspenseKey, {\n data: cacheData.data ?? null,\n error: cacheData.error ?? null,\n status: cacheData.status ?? null,\n extra: cacheData.extra ?? null,\n success: cacheData.success ?? false,\n });\n resolvePromise();\n unsubscribe();\n suspensePromiseMap.delete(suspenseKey);\n });\n\n entry = { promise, resolve: resolvePromise!, cleanup: unsubscribe };\n suspensePromiseMap.set(suspenseKey, entry);\n }\n\n // Ensure the request is dispatched before suspending —\n // effects never run when a component suspends.\n // React may render a suspended component again before the queued request starts running,\n // so a queued request counts as dispatched too.\n const scopedQueryKey = scopeKey(queryKey, request.scope);\n if (!dispatcher.hasRunningRequests(scopedQueryKey) && !dispatcher.getIsActiveQueue(scopedQueryKey)) {\n dispatcher.add(request as unknown as R);\n }\n\n throw entry.promise;\n }\n\n // Data has arrived — clean up any leftover entry\n const entry = suspensePromiseMap.get(suspenseKey);\n if (entry) {\n entry.cleanup();\n suspensePromiseMap.delete(suspenseKey);\n }\n }\n\n // ******************\n // Error boundary\n // ******************\n if (throwOnError) {\n // The error has to be observed to rerender (and throw) even if the component does not read it\n setRenderKey(\"error\");\n setRenderKey(\"loading\");\n setRenderKey(\"success\");\n\n const details = getResponseDetails();\n // Errors of retried, canceled or offline (re-queued) requests are not final\n const isSettled = !state.loading && !details?.willRetry && !details?.isCanceled && !details?.isOffline;\n const hasError = !state.success && state.error !== null && state.error !== undefined;\n\n if (isSettled && hasError) {\n const error = state.error as ExtractErrorType<R>;\n if (typeof throwOnError === \"function\" ? throwOnError(error) : throwOnError) {\n throw error;\n }\n }\n }\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"loading\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n error: state.error,\n loading: state.loading,\n status: state.status as ExtractAdapterStatusType<ExtractAdapterType<R>>,\n success: state.success,\n extra: state.extra as ExtractAdapterExtraType<ExtractAdapterType<R>>,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n bounce: getBounceData(bounceData),\n ...actions,\n ...(callbacks as any),\n refetch,\n },\n trackedKeys,\n setRenderKey,\n ) as UseFetchReturnType<R, TSelected>;\n};\n","export const getRefreshTime = (refreshTime: number, dataTimestamp?: Date) => {\n if (dataTimestamp) {\n const timeDiff = Date.now() - +dataTimestamp;\n return timeDiff < refreshTime ? refreshTime - timeDiff : refreshTime;\n }\n return refreshTime;\n};\n","import type { RequestInstance, RequiredKeys } from \"@hyper-fetch/core\";\nimport { Time } from \"@hyper-fetch/core\";\nimport type { UseFetchOptionsType } from \"hooks/use-fetch\";\n\ntype DefaultOptionsType = RequiredKeys<Omit<UseFetchOptionsType<RequestInstance>, \"initialResponse\" | \"select\">> & {\n initialResponse: null;\n};\n\nexport const useFetchDefaultOptions: DefaultOptionsType = {\n suspense: false,\n dependencies: [],\n disabled: false,\n dependencyTracking: true,\n revalidate: true,\n initialResponse: null,\n keepPreviousData: \"auto\",\n refresh: false,\n refreshTime: Time.HOUR,\n refetchBlurred: true,\n refetchOnBlur: false,\n refetchOnFocus: false,\n refetchOnReconnect: false,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n bounceTimeout: 400,\n deepCompare: true,\n structuralSharing: true,\n throwOnError: false,\n};\n","import { Time } from \"@hyper-fetch/core\";\n\nimport type { UseInfiniteFetchConfigType } from \"./use-infinite-fetch.types\";\n\nexport const useInfiniteFetchDefaultOptions = {\n suspense: false,\n throwOnError: false,\n dependencies: [],\n disabled: false,\n dependencyTracking: true,\n // Pages restored from the cache are refetched only once they are stale\n revalidate: false,\n keepPreviousData: \"auto\",\n refresh: false,\n refreshTime: Time.HOUR,\n refetchBlurred: true,\n refetchOnBlur: false,\n refetchOnFocus: false,\n refetchOnReconnect: false,\n structuralSharing: true,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n bounceTimeout: 400,\n} satisfies Required<UseInfiniteFetchConfigType>;\n","import type { RequestInstance } from \"@hyper-fetch/core\";\nimport { getErrorMessage, mapResponseForSend, scopeKey } from \"@hyper-fetch/core\";\n\ntype LoadPageOptions = {\n request: RequestInstance;\n /** Skips requests started before this fetch was asked for */\n force: boolean;\n /** Filled with the functions stopping this fetch */\n cancellers: Set<VoidFunction>;\n isCancelled: () => boolean;\n};\n\n/**\n * Cancelled pages are not failures: the list simply did not need them anymore\n */\nexport const isCancelledResponse = (response: any) => {\n const message = response?.error?.message;\n return (\n !response?.success &&\n (message === getErrorMessage(\"abort\").message || message === getErrorMessage(\"deleted\").message)\n );\n};\n\n/**\n * Joins a request started elsewhere. Cancelling only stops waiting, the request belongs to someone else.\n */\nconst waitForResponse = (request: RequestInstance, requestId: string, cancellers: Set<VoidFunction>) => {\n const { requestManager } = request.client;\n\n return new Promise<any>((resolve) => {\n const finish = (response: any) => {\n unmountResponse();\n unmountRemove();\n cancellers.delete(cancel);\n resolve(response);\n };\n const cancel = () => finish(null);\n const unmountResponse = requestManager.events.onResponseById(requestId, ({ response, details }) => {\n if (response.success || (!details.willRetry && !details.isOffline)) {\n finish(response);\n }\n });\n const unmountRemove = requestManager.events.onRemoveById(requestId, cancel);\n\n cancellers.add(cancel);\n });\n};\n\nconst sendPage = async ({ request, force, cancellers }: LoadPageOptions) => {\n const { fetchDispatcher } = request.client;\n const pageRequest = force ? request.setDeduplicate(false) : request;\n let sentRequestId = \"\";\n\n const cancel = () => {\n fetchDispatcher.delete(\n scopeKey(request.queryKey, request.scope),\n sentRequestId,\n scopeKey(request.abortKey, request.scope),\n );\n };\n cancellers.add(cancel);\n\n const response = await (pageRequest as RequestInstance).send({\n dispatcherType: \"fetch\",\n onBeforeSent: ({ requestId }: { requestId: string }) => {\n sentRequestId = requestId;\n },\n } as any);\n\n cancellers.delete(cancel);\n return response;\n};\n\n/**\n * Loads a page, reusing the request already running for it\n */\nexport const loadPage = async (options: LoadPageOptions) => {\n const { request, force, cancellers, isCancelled } = options;\n\n // A forced fetch must not reuse a request started before it was asked for\n if (!force) {\n const running = request.client.fetchDispatcher\n .getRunningRequests(scopeKey(request.queryKey, request.scope))\n .find((item) => item.request.cacheKey === request.cacheKey);\n\n if (running) {\n const response = await waitForResponse(request, running.requestId, cancellers);\n if (response) {\n return mapResponseForSend(request, response);\n }\n if (isCancelled()) {\n return null;\n }\n }\n }\n\n return sendPage(options);\n};\n","import type {\n CacheValueType,\n ClientInstance,\n PaginationConfig,\n PaginationPageContext,\n RequestInstance,\n} from \"@hyper-fetch/core\";\nimport {\n getCachedPages,\n getHasNextPage,\n getHasPreviousPage,\n getInitialPageParam,\n getNextPageParam,\n getPageItems,\n getPageRequest,\n getPageTotal,\n getPaginationMode,\n getPreviousPageParam,\n replaceEqualDeep,\n scopeKey,\n stringifyKey,\n} from \"@hyper-fetch/core\";\nimport { isStaleCacheData } from \"helpers/use-tracked-state/use-tracked-state.utils\";\nimport { pickInitialCacheData } from \"hydrate/hydrate.utils\";\n\nimport { isCancelledResponse, loadPage } from \"./use-infinite-fetch.requests\";\nimport type {\n FetchedPage,\n InfinitePage,\n InfiniteSnapshot,\n InfiniteStoreOptions,\n Operation,\n OperationKind,\n} from \"./use-infinite-fetch.store.types\";\nimport type { InfinitePageEvent } from \"./use-infinite-fetch.types\";\n\n// Render and commit are separate steps, a store waits this long for the component that created it\nconst unusedStoreTime = 1000;\n\nconst stores = new WeakMap<ClientInstance, Map<string, InfiniteStore>>();\n\nconst getStores = (client: ClientInstance) => {\n let clientStores = stores.get(client);\n if (!clientStores) {\n clientStores = new Map();\n stores.set(client, clientStores);\n }\n return clientStores;\n};\n\nconst isSameSnapshot = (a: InfiniteSnapshot, b: InfiniteSnapshot) => {\n return (Object.keys(a) as (keyof InfiniteSnapshot)[]).every((key) => a[key] === b[key]);\n};\n\n/**\n * State of a single list. Hooks showing the same list share one store, so they stay in sync and never request\n * the same page twice. Pages are ordinary requests under their own cache keys - nothing extra is stored.\n *\n * Fetches run one at a time: every page depends on the list as it was when its value was computed.\n */\nexport class InfiniteStore {\n private listeners = new Set<VoidFunction>();\n private pageListeners = new Set<(event: InfinitePageEvent<any>) => void>();\n private pages: InfinitePage[] = [];\n // Values of pages dropped by `maxPages`, a cursor list may have no other way of going back to them\n private droppedParams: unknown[] = [];\n private queue: Operation[] = [];\n private running: Operation | null = null;\n private cancellers = new Set<VoidFunction>();\n // Pages being refetched - their cache events wait for the whole list to be swapped at once\n private refetchedKeys = new Set<string>();\n private unmountCacheListeners: VoidFunction | null = null;\n private unusedTimer: ReturnType<typeof setTimeout> | null = null;\n private started = false;\n private settled = false;\n private firstFetch: Promise<any> = Promise.resolve(null);\n private nextPageError = false;\n private previousPageError = false;\n private result: { error: any; status: any; extra: any; success: boolean } = {\n error: null,\n status: null,\n extra: null,\n success: false,\n };\n private snapshot: InfiniteSnapshot;\n\n constructor(\n readonly key: string,\n private options: InfiniteStoreOptions,\n ) {\n getPaginationMode(options.pagination);\n this.restorePages();\n this.snapshot = this.createSnapshot();\n }\n\n // ******************\n // State\n // ******************\n\n getSnapshot = () => this.snapshot;\n\n subscribe = (listener: VoidFunction) => {\n this.listeners.add(listener);\n if (this.listeners.size === 1) {\n this.attach();\n }\n\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) {\n this.detach();\n }\n };\n };\n\n onPage = (listener: (event: InfinitePageEvent<any>) => void) => {\n this.pageListeners.add(listener);\n return () => {\n this.pageListeners.delete(listener);\n };\n };\n\n /** Callbacks can capture values of the latest render */\n setPagination = (pagination: PaginationConfig) => {\n this.options.pagination = pagination;\n };\n\n hasPages = () => this.pages.length > 0;\n\n // ******************\n // Actions\n // ******************\n\n /**\n * Loads the list when it is first needed. Safe to call many times.\n */\n start = ({ revalidate }: { revalidate?: boolean } = {}) => {\n if (this.started) {\n return this.firstFetch;\n }\n this.started = true;\n\n if (this.pages.length === 0) {\n this.firstFetch = this.schedule(\"initial\");\n } else if (revalidate || this.getHasStalePages()) {\n this.revalidate();\n } else {\n this.settled = true;\n }\n this.publish();\n return this.firstFetch;\n };\n\n fetchNextPage = () => this.fetchDirection(\"next\");\n\n fetchPreviousPage = () => this.fetchDirection(\"previous\");\n\n /**\n * Refetch asked for by the user: anything already refetching is older than this call and gets replaced.\n */\n refetch = () => {\n if (this.pages.length === 0) {\n return this.revalidate();\n }\n this.getOperations(\"refetch\").forEach(this.cancelOperation);\n return this.schedule(\"refetch\");\n };\n\n /**\n * Automatic refetch: joins the one in progress\n */\n revalidate = () => {\n const kind = this.pages.length > 0 ? \"refetch\" : \"initial\";\n return this.getOperations(kind)[0]?.promise ?? this.schedule(kind);\n };\n\n reset = () => {\n this.cancelOperations();\n const startParam = stringifyKey(getInitialPageParam(this.options.request, this.options.pagination));\n\n this.pages = this.pages.filter((page) => stringifyKey(page.param) === startParam);\n this.droppedParams = [];\n this.nextPageError = false;\n this.previousPageError = false;\n this.settled = false;\n this.started = true;\n\n return this.schedule(this.pages.length > 0 ? \"refetch\" : \"initial\");\n };\n\n abort = () => {\n this.cancelOperations();\n this.settled = true;\n this.publish();\n };\n\n /** The list is no longer on screen - stop fetching its pages */\n cancelIfUnused = () => {\n if (this.listeners.size === 0) {\n this.cancelOperations();\n }\n };\n\n /** A store that threw its error starts over when the Error Boundary renders the component again */\n evictSoon = () => {\n setTimeout(this.evict, 0);\n };\n\n /** Stores created while rendering are removed when the component never mounts */\n scheduleUnusedCheck = () => {\n this.unusedTimer = setTimeout(() => {\n this.unusedTimer = null;\n if (this.running || this.queue.length > 0) {\n this.scheduleUnusedCheck();\n } else {\n this.evict();\n }\n }, unusedStoreTime);\n };\n\n // ******************\n // Operations\n // ******************\n\n private fetchDirection = (kind: \"next\" | \"previous\") => {\n if (this.pages.length === 0) {\n return this.getOperations(\"initial\")[0]?.promise ?? Promise.resolve(null);\n }\n const scheduled = this.getOperations(kind)[0];\n if (scheduled) {\n return scheduled.promise;\n }\n if (kind === \"next\" ? this.getNextParam() === undefined : !this.getPreviousTarget()) {\n return Promise.resolve(null);\n }\n if (kind === \"next\") {\n this.nextPageError = false;\n } else {\n this.previousPageError = false;\n }\n return this.schedule(kind);\n };\n\n private getOperations = (kind: OperationKind) => {\n const operations = this.running ? [this.running, ...this.queue] : this.queue;\n return operations.filter((operation) => operation.kind === kind && !operation.cancelled);\n };\n\n private schedule = (kind: OperationKind) => {\n const operation = { kind, cancelled: false } as Operation;\n operation.promise = new Promise<any>((resolve) => {\n operation.resolve = resolve;\n });\n\n if (kind === \"initial\") {\n this.settled = false;\n }\n this.queue.push(operation);\n this.pump();\n this.publish();\n return operation.promise;\n };\n\n private pump = async () => {\n if (this.running) {\n return;\n }\n const operation = this.queue.shift();\n if (!operation) {\n return;\n }\n\n this.running = operation;\n const previousPages = this.pages;\n let response = null;\n try {\n response = await this.perform(operation);\n } catch (error) {\n this.setFailure(error);\n }\n this.keepValidPages(previousPages);\n this.running = null;\n this.refetchedKeys.clear();\n\n if ((operation.kind === \"initial\" || operation.kind === \"refetch\") && !operation.cancelled) {\n this.settled = true;\n }\n\n operation.resolve(operation.cancelled ? null : response);\n this.pump();\n this.publish();\n };\n\n private cancelOperation = (operation: Operation) => {\n operation.cancelled = true;\n if (operation === this.running) {\n this.cancellers.forEach((cancel) => cancel());\n this.cancellers.clear();\n this.refetchedKeys.clear();\n } else {\n this.queue = this.queue.filter((item) => item !== operation);\n operation.resolve(null);\n }\n };\n\n private cancelOperations = () => {\n [...this.queue, ...(this.running ? [this.running] : [])].forEach(this.cancelOperation);\n };\n\n private perform = (operation: Operation) => {\n switch (operation.kind) {\n case \"next\": {\n return this.performNext(operation);\n }\n case \"previous\": {\n return this.performPrevious(operation);\n }\n case \"refetch\": {\n return this.performRefetch(operation);\n }\n default: {\n return this.performInitial(operation);\n }\n }\n };\n\n private performInitial = async (operation: Operation) => {\n const { request, pagination } = this.options;\n const fetched = await this.fetchPage(operation, getInitialPageParam(request, pagination));\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n if (fetched.response.success) {\n this.pages = [this.createPage(fetched)];\n }\n return fetched.response;\n };\n\n private performNext = async (operation: Operation) => {\n const param = this.getNextParam();\n if (param === undefined) {\n return null;\n }\n\n const fetched = await this.fetchPage(operation, param);\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n this.nextPageError = !fetched.response.success;\n if (fetched.response.success) {\n this.pages = [...this.pages, this.createPage(fetched)];\n this.trimPages(\"start\");\n }\n return fetched.response;\n };\n\n private performPrevious = async (operation: Operation) => {\n const target = this.getPreviousTarget();\n if (!target) {\n return null;\n }\n\n const { param } = target;\n const fetched = await this.fetchPage(operation, param);\n if (!fetched) {\n return null;\n }\n\n this.setResult(fetched.response);\n this.previousPageError = !fetched.response.success;\n if (fetched.response.success) {\n if (target.isDropped) {\n this.droppedParams = this.droppedParams.slice(0, -1);\n }\n this.pages = [this.createPage(fetched), ...this.pages];\n this.trimPages(\"end\");\n }\n return fetched.response;\n };\n\n private performRefetch = async (operation: Operation) => {\n const current = this.pages;\n current.forEach((page) => this.refetchedKeys.add(page.storageKey));\n\n return getPaginationMode(this.options.pagination) === \"cursor\"\n ? this.refetchInOrder(operation, current)\n : this.refetchAtOnce(operation, current);\n };\n\n /**\n * Page and offset values do not depend on other pages, so they can be requested together\n */\n private refetchAtOnce = async (operation: Operation, current: InfinitePage[]) => {\n const results = await Promise.all(current.map((page) => this.fetchPage(operation, page.param, true)));\n if (operation.cancelled) {\n return null;\n }\n\n const failed = results.find((fetched) => fetched && !fetched.response.success);\n const last = failed ?? results.findLast(Boolean);\n\n this.pages = current.map((page, index) => {\n const fetched = results[index];\n return fetched?.response.success ? this.createPage(fetched) : page;\n });\n if (last) {\n this.setResult(last.response);\n }\n return last?.response ?? null;\n };\n\n /**\n * Every cursor comes from the page before it, and the fresh data can hold different cursors than before.\n * The list is replaced only when the whole chain arrived, a failure leaves it as it was.\n */\n private refetchInOrder = async (operation: Operation, current: InfinitePage[]) => {\n const fresh: InfinitePage[] = [];\n let param = current[0].param;\n let response = null;\n\n while (fresh.length < current.length) {\n // Each request needs the response of the previous one\n // eslint-disable-next-line no-await-in-loop\n const fetched = await this.fetchPage(operation, param, true);\n if (!fetched) {\n return null;\n }\n\n response = fetched.response;\n this.setResult(response);\n if (!response.success) {\n return response;\n }\n\n const page = this.createPage(fetched);\n fresh.push(page);\n\n const context = this.getContext(page, fresh);\n if (!getHasNextPage(context)) {\n break;\n }\n param = getNextPageParam(context);\n }\n\n this.pages = fresh;\n return response;\n };\n\n private trimPages = (side: \"start\" | \"end\") => {\n const { maxPages } = this.options;\n if (!maxPages || this.pages.length <= maxPages) {\n return;\n }\n\n const overflow = this.pages.length - maxPages;\n if (side === \"start\") {\n this.droppedParams = [...this.droppedParams, ...this.pages.slice(0, overflow).map((page) => page.param)];\n this.pages = this.pages.slice(overflow);\n } else {\n this.pages = this.pages.slice(0, maxPages);\n }\n };\n\n // ******************\n // Requests\n // ******************\n\n private fetchPage = async (operation: Operation, param: unknown, force = false): Promise<FetchedPage | null> => {\n const request = getPageRequest(this.options.request, this.options.pagination, param);\n const response = await loadPage({\n request,\n force,\n cancellers: this.cancellers,\n isCancelled: () => operation.cancelled,\n });\n\n if (operation.cancelled || !response || isCancelledResponse(response)) {\n return null;\n }\n\n this.pageListeners.forEach((listener) => listener({ response, request, param }));\n return { param, request, response };\n };\n\n // ******************\n // Pages\n // ******************\n\n private getContext = (page: InfinitePage, pages: InfinitePage[] = this.pages): PaginationPageContext => ({\n request: this.options.request,\n pagination: this.options.pagination,\n data: page.data,\n param: page.param,\n pages: pages.map((item) => item.data),\n });\n\n private getNextParam = () => {\n const last = this.pages.at(-1);\n if (!last || !getHasNextPage(this.getContext(last))) {\n return;\n }\n return getNextPageParam(this.getContext(last));\n };\n\n // The first page of a cursor list has no cursor, so \"no value\" cannot mean \"no page\"\n private getPreviousTarget = (): { param: unknown; isDropped: boolean } | null => {\n const first = this.pages[0];\n if (!first) {\n return null;\n }\n if (this.droppedParams.length > 0) {\n return { param: this.droppedParams.at(-1), isDropped: true };\n }\n if (getHasPreviousPage(this.getContext(first))) {\n return { param: getPreviousPageParam(this.getContext(first)), isDropped: false };\n }\n return null;\n };\n\n private getHasStalePages = () => {\n return this.pages.some((page) => {\n const value = this.readValue(page.request);\n return !value || isStaleCacheData(value.staleTime, value.responseTimestamp);\n });\n };\n\n private readValue = (request: RequestInstance) => {\n const { client } = request;\n const storageKey = scopeKey(request.cacheKey, request.scope);\n return pickInitialCacheData<CacheValueType>(\n client.cache.get(storageKey),\n this.options.hydration?.get(client, storageKey),\n );\n };\n\n /** Responses go through the response mapper of the request, an asynchronous one cannot be read synchronously */\n private mapValue = (request: RequestInstance, value: CacheValueType) => {\n const mapped: any = request.unstable_responseMapper ? request.unstable_responseMapper(value as any) : value;\n return mapped instanceof Promise ? undefined : mapped;\n };\n\n private createPage = ({ param, request, response }: FetchedPage): InfinitePage => {\n // Reading the cache keeps changes made after the response arrived, like optimistic updates\n const value = this.readValue(request);\n const cached =\n value && value.responseTimestamp >= response.responseTimestamp ? this.mapValue(request, value) : null;\n\n return {\n param,\n request,\n storageKey: scopeKey(request.cacheKey, request.scope),\n data: cached?.success ? cached.data : response.data,\n responseTimestamp: response.responseTimestamp,\n };\n };\n\n private restorePages = () => {\n const { request, pagination, maxPages } = this.options;\n\n this.pages = getCachedPages({\n request,\n pagination,\n maxPages,\n read: (pageRequest) => {\n const value = this.readValue(pageRequest);\n const mapped = value ? this.mapValue(pageRequest, value) : null;\n return mapped?.success ? { ...value, data: mapped.data } : null;\n },\n }).map(({ param, request: pageRequest, value }) => ({\n param,\n request: pageRequest,\n storageKey: scopeKey(pageRequest.cacheKey, pageRequest.scope),\n data: value.data,\n responseTimestamp: Number(value.responseTimestamp),\n }));\n };\n\n /** Picks up everything that happened between rendering and mounting */\n private syncPages = () => {\n if (this.running || this.queue.length > 0) {\n return;\n }\n if (this.pages.length === 0) {\n this.restorePages();\n return;\n }\n\n this.pages = this.pages.map((page) => {\n const value = this.readValue(page.request);\n const mapped = value ? this.mapValue(page.request, value) : null;\n return mapped?.success\n ? { ...page, data: mapped.data, responseTimestamp: Number(value?.responseTimestamp) }\n : page;\n });\n };\n\n private setFailure = (error: unknown) => {\n this.result = { error, status: null, extra: null, success: false };\n };\n\n /**\n * Pagination callbacks read the data of every page. When one of them throws, the page that caused it is not\n * used and the error is reported instead of breaking the list.\n */\n private keepValidPages = (previousPages: InfinitePage[]) => {\n try {\n this.createSnapshot();\n } catch (error) {\n this.pages = previousPages;\n this.setFailure(error);\n }\n };\n\n private setResult = (response: any) => {\n this.result = {\n error: response.success ? null : response.error,\n status: response.status,\n extra: response.extra,\n success: response.success,\n };\n };\n\n // ******************\n // Cache\n // ******************\n\n private attach = () => {\n if (this.unusedTimer) {\n clearTimeout(this.unusedTimer);\n this.unusedTimer = null;\n }\n\n const { client } = this.options.request;\n const clientStores = getStores(client);\n if (!clientStores.has(this.key) && client.mode !== \"server\") {\n clientStores.set(this.key, this);\n }\n\n const { cache } = client;\n const unmountData = cache.events.onData(this.handleCacheData);\n const unmountInvalidate = cache.events.onInvalidate(this.handleCacheChange);\n const unmountDelete = cache.events.onDelete(this.handleCacheChange);\n\n this.unmountCacheListeners = () => {\n unmountData();\n unmountInvalidate();\n unmountDelete();\n };\n\n this.syncPages();\n this.publish();\n };\n\n private detach = () => {\n this.unmountCacheListeners?.();\n this.unmountCacheListeners = null;\n this.evict();\n };\n\n private evict = () => {\n if (this.listeners.size > 0) {\n return;\n }\n const clientStores = getStores(this.options.request.client);\n if (clientStores.get(this.key) === this) {\n clientStores.delete(this.key);\n }\n };\n\n private handleCacheData = (value: CacheValueType) => {\n const storageKey = scopeKey(value.cacheKey, value.scope ?? null);\n if (!value.success || this.refetchedKeys.has(storageKey)) {\n return;\n }\n\n const index = this.pages.findIndex((page) => page.storageKey === storageKey);\n const page = this.pages[index];\n const mapped = page ? this.mapValue(page.request, value) : null;\n if (!page || !mapped?.success) {\n return;\n }\n\n const previousPages = this.pages;\n this.pages = this.pages.map((item, itemIndex) => {\n return itemIndex === index\n ? { ...item, data: mapped.data, responseTimestamp: Number(value.responseTimestamp) }\n : item;\n });\n this.keepValidPages(previousPages);\n this.publish();\n };\n\n private hasInvalidation = false;\n\n /**\n * Invalidated data may have changed after a running refetch started, so that refetch is replaced.\n * Invalidating by a pattern reports every key on its own, all of them are handled by one refetch.\n */\n private handleCacheChange = (key: string) => {\n const isLoaded = this.pages.some((page) => page.storageKey === key || page.request.cacheKey === key);\n if (!isLoaded || this.hasInvalidation) {\n return;\n }\n\n this.hasInvalidation = true;\n queueMicrotask(() => {\n this.hasInvalidation = false;\n if (this.listeners.size > 0) {\n this.refetch();\n }\n });\n };\n\n // ******************\n // Snapshot\n // ******************\n\n private createSnapshot = (): InfiniteSnapshot => {\n const { structuralSharing = true } = this.options;\n const previous = this.snapshot as InfiniteSnapshot | undefined;\n const share = <T>(prev: T | undefined, next: T) =>\n structuralSharing && prev ? replaceEqualDeep(prev, next) : next;\n\n const contexts = this.pages.map((page) => this.getContext(page));\n const last = contexts.at(-1);\n const totals = contexts.map(getPageTotal).filter((total) => total !== null);\n const operations = [...this.queue, ...(this.running ? [this.running] : [])].filter((item) => !item.cancelled);\n const isRunning = (kind: OperationKind) => operations.some((item) => item.kind === kind);\n\n return {\n items: share(previous?.items, contexts.flatMap((context) => getPageItems(context))),\n data: share(previous?.data, this.pages.map((page) => page.data)),\n pageParams: share(previous?.pageParams, this.pages.map((page) => page.param)),\n total: totals.length > 0 ? (totals.at(-1) as number) : null,\n hasNextPage: !!last && this.getNextParam() !== undefined,\n hasPreviousPage: !!this.getPreviousTarget(),\n loading: this.pages.length === 0 && !this.settled,\n isFetching: operations.length > 0,\n isRefetching: isRunning(\"refetch\"),\n isFetchingNextPage: isRunning(\"next\"),\n isFetchingPreviousPage: isRunning(\"previous\"),\n isFetchNextPageError: this.nextPageError,\n isFetchPreviousPageError: this.previousPageError,\n ...this.result,\n };\n };\n\n private publish = () => {\n const snapshot = this.createSnapshot();\n if (isSameSnapshot(this.snapshot, snapshot)) {\n return;\n }\n this.snapshot = snapshot;\n this.listeners.forEach((listener) => listener());\n };\n}\n\n/**\n * Returns the store of the list, shared between all the mounted hooks showing it.\n * Server renders never share one: a client can serve many users at the same time.\n */\nexport const getInfiniteStore = (key: string, options: InfiniteStoreOptions) => {\n const { client } = options.request;\n if (client.mode === \"server\" || typeof window === \"undefined\") {\n return new InfiniteStore(key, options);\n }\n\n const clientStores = getStores(client);\n let store = clientStores.get(key);\n if (!store) {\n store = new InfiniteStore(key, options);\n clientStores.set(key, store);\n store.scheduleUnusedCheck();\n }\n return store;\n};\n","import type { RequestInstance } from \"@hyper-fetch/core\";\n\n/**\n * Identity of a list. Everything describing the request takes part in it, so a changed filter, sort, page size\n * or URL param starts a new list without anything having to be listed by hand.\n */\nexport const getInfiniteKey = (request: RequestInstance, pagination: unknown, maxPages?: number) => {\n return JSON.stringify([request.toJSON(), pagination, maxPages ?? null], (_key, value) => {\n return typeof value === \"function\" ? value.toString() : value;\n });\n};\n\n/**\n * Keeps the first occurrence of every item\n */\nexport const getUniqueItems = (items: unknown[], uniqueBy: unknown) => {\n if (uniqueBy === undefined) {\n return items;\n }\n\n const seen = new Set<unknown>();\n return items.filter((item: any) => {\n const identity = typeof uniqueBy === \"function\" ? uniqueBy({ item }) : item?.[uniqueBy as string];\n if (seen.has(identity)) {\n return false;\n }\n seen.add(identity);\n return true;\n });\n};\n\n/**\n * Decides if the previous list stays on screen while the new one loads its first page\n */\nexport const getShouldKeepPreviousList = (\n mode: \"auto\" | \"preserve\" | \"clean\",\n previous: RequestInstance,\n current: RequestInstance,\n) => {\n if (mode === \"auto\") {\n return previous.method === current.method && previous.endpoint === current.endpoint;\n }\n return mode === \"preserve\";\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n ExtractErrorType,\n Pagination,\n PaginationConfig,\n PaginationItem,\n RequestInstance,\n} from \"@hyper-fetch/core\";\nimport { replaceEqualDeep } from \"@hyper-fetch/core\";\nimport { useHydration } from \"hydrate/hydrate\";\nimport { useProvider } from \"provider\";\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\n\nimport { useInfiniteFetchDefaultOptions } from \"./use-infinite-fetch.constants\";\nimport type { InfiniteStore } from \"./use-infinite-fetch.store\";\nimport { getInfiniteStore } from \"./use-infinite-fetch.store\";\nimport type { InfiniteSnapshot } from \"./use-infinite-fetch.store.types\";\nimport type { UseInfiniteFetchOptionsType, UseInfiniteFetchReturnType } from \"./use-infinite-fetch.types\";\nimport { getInfiniteKey, getShouldKeepPreviousList, getUniqueItems } from \"./use-infinite-fetch.utils\";\n\n// What decides about a returned value - the list on screen also depends on the new list still loading\nconst trackedSources: Record<string, (keyof InfiniteSnapshot)[]> = {\n items: [\"items\", \"loading\"],\n pages: [\"data\", \"loading\"],\n pageParams: [\"pageParams\", \"loading\"],\n total: [\"total\", \"loading\"],\n isPreviousData: [\"data\", \"loading\"],\n loading: [\"data\", \"loading\"],\n};\n\nconst trackedKeys = [\n \"items\",\n \"pages\",\n \"pageParams\",\n \"total\",\n \"hasNextPage\",\n \"hasPreviousPage\",\n \"loading\",\n \"isFetching\",\n \"isRefetching\",\n \"isFetchingNextPage\",\n \"isFetchingPreviousPage\",\n \"isFetchNextPageError\",\n \"isFetchPreviousPageError\",\n \"isPreviousData\",\n \"error\",\n \"status\",\n \"extra\",\n \"success\",\n] as const;\n\n/**\n * Loads a list page by page. Say which fields page through the request, and the hook takes care of the rest:\n * every page is a normal request under its own cache key, and the hook glues them together.\n *\n * A changed filter, sort or URL param starts a new list on its own. When to load more is up to you - call\n * `fetchNextPage` from a button, an intersection observer, `onEndReached` or a virtualizer.\n *\n * @param request Request instance\n * @param options Hook options, `pagination` is required\n * @returns\n * @example\n * ```tsx\n * const { items, hasNextPage, fetchNextPage } = useInfiniteFetch(getFeed.setQueryParams({ topic }), {\n * pagination: { cursor: \"cursor\", next: \"nextCursor\", items: \"data\" },\n * });\n * ```\n */\nexport const useInfiniteFetch = <\n R extends RequestInstance,\n const P extends Pagination<R>,\n TSelected = PaginationItem<R, P>[],\n>(\n request: R,\n options: UseInfiniteFetchOptionsType<R, P, TSelected>,\n): UseInfiniteFetchReturnType<R, P, TSelected> => {\n const { config: globalConfig } = useProvider();\n const {\n pagination,\n uniqueBy,\n maxPages,\n select,\n suspense,\n throwOnError,\n dependencies,\n disabled,\n dependencyTracking,\n revalidate,\n keepPreviousData,\n refresh,\n refreshTime,\n refetchBlurred,\n refetchOnBlur,\n refetchOnFocus,\n refetchOnReconnect,\n structuralSharing,\n bounce,\n bounceType,\n bounceTime,\n bounceTimeout,\n } = {\n ...useInfiniteFetchDefaultOptions,\n ...globalConfig.useInfiniteFetchConfig,\n ...options,\n };\n\n const { client } = request;\n const hydration = useHydration();\n\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({ interval: bounceTime, timeout: bounceTimeout });\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n // ******************\n // Store\n // ******************\n\n const key = getInfiniteKey(request, pagination, maxPages);\n const storeRef = useRef<InfiniteStore | null>(null);\n const storeClientRef = useRef(client);\n\n if (!storeRef.current || storeRef.current.key !== key || storeClientRef.current !== client) {\n storeClientRef.current = client;\n storeRef.current = getInfiniteStore(key, {\n request,\n pagination: pagination as PaginationConfig,\n maxPages,\n structuralSharing,\n hydration,\n });\n }\n const store = storeRef.current;\n\n // Rerenders only when something the component reads has changed\n const usedKeys = useRef(new Set<string>()).current;\n const renderedRef = useRef<{ store: InfiniteStore; snapshot: InfiniteSnapshot } | null>(null);\n\n const getSnapshot = () => {\n const next = store.getSnapshot();\n const rendered = renderedRef.current;\n\n if (dependencyTracking && rendered?.store === store) {\n const hasChanged = [...usedKeys].some((usedKey) => {\n const sources = trackedSources[usedKey] ?? [usedKey as keyof InfiniteSnapshot];\n return sources.some((source) => rendered.snapshot[source] !== next[source]);\n });\n if (!hasChanged) {\n return rendered.snapshot;\n }\n }\n\n renderedRef.current = { store, snapshot: next };\n return next;\n };\n\n const snapshot = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);\n\n // ******************\n // Latest values\n // ******************\n\n const callbacks = useRef<{\n onSuccess?: (event: any) => void;\n onError?: (event: any) => void;\n onFinished?: (event: any) => void;\n onReset?: VoidFunction;\n }>({});\n\n const latest = useRef({ disabled, revalidate, refetchOnBlur, refetchOnFocus, refetchOnReconnect });\n latest.current = { disabled, revalidate, refetchOnBlur, refetchOnFocus, refetchOnReconnect };\n\n // ******************\n // Lifecycle\n // ******************\n\n useEffect(() => {\n store.setPagination(pagination as PaginationConfig);\n });\n\n useEffect(() => {\n return store.onPage((event) => {\n if (event.response.success) {\n callbacks.current.onSuccess?.(event);\n } else {\n callbacks.current.onError?.(event);\n }\n callbacks.current.onFinished?.(event);\n });\n }, [store]);\n\n /**\n * A new list stops the pages of the previous one, so a late response never gets in the way\n */\n const mountedStore = useRef<InfiniteStore | null>(null);\n\n useEffect(() => {\n const previous = mountedStore.current;\n mountedStore.current = store;\n\n if (previous && previous !== store) {\n previous.cancelIfUnused();\n callbacks.current.onReset?.();\n }\n if (disabled) {\n return;\n }\n\n if (bounce && previous && previous !== store && !store.hasPages()) {\n bounceFunction(() => store.start({ revalidate: latest.current.revalidate }));\n } else {\n store.start({ revalidate });\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [store, disabled]);\n\n useDidUpdate(() => {\n if (!disabled) {\n store.refetch();\n }\n }, dependencies);\n\n useEffect(() => {\n const { appManager } = client;\n const handle = (option: \"refetchOnBlur\" | \"refetchOnFocus\" | \"refetchOnReconnect\") => () => {\n if (latest.current[option] && !latest.current.disabled) {\n store.revalidate();\n }\n };\n\n const unmountFocus = appManager.events.onFocus(handle(\"refetchOnFocus\"));\n const unmountBlur = appManager.events.onBlur(handle(\"refetchOnBlur\"));\n const unmountOnline = appManager.events.onOnline(handle(\"refetchOnReconnect\"));\n\n return () => {\n unmountFocus();\n unmountBlur();\n unmountOnline();\n };\n }, [client, store]);\n\n useEffect(() => {\n if (!refresh || disabled) {\n return;\n }\n\n const timer = setInterval(() => {\n if (client.appManager.isFocused || refetchBlurred) {\n store.revalidate();\n }\n }, refreshTime);\n\n return () => clearInterval(timer);\n }, [client, store, refresh, refreshTime, refetchBlurred, disabled]);\n\n // ******************\n // Previous list\n // ******************\n\n const previousList = useRef<{ store: InfiniteStore; request: RequestInstance; snapshot: InfiniteSnapshot } | null>(\n null,\n );\n\n useEffect(() => {\n if (snapshot.data.length > 0) {\n previousList.current = { store, request, snapshot };\n }\n });\n\n const previous = previousList.current;\n const isPreviousData =\n !disabled &&\n snapshot.loading &&\n snapshot.data.length === 0 &&\n !!previous &&\n previous.store !== store &&\n getShouldKeepPreviousList(keepPreviousData, previous.request, request);\n\n const list = isPreviousData ? previous.snapshot : snapshot;\n\n // ******************\n // Suspense\n // ******************\n\n const isServer = client.mode === \"server\" || typeof window === \"undefined\";\n\n if (suspense && !disabled && !isServer && snapshot.loading && !isPreviousData) {\n throw store.start({ revalidate });\n }\n\n // ******************\n // Error boundary\n // ******************\n\n if (throwOnError) {\n usedKeys.add(\"error\");\n usedKeys.add(\"isFetching\");\n\n const error = snapshot.error as ExtractErrorType<R> | null;\n const shouldThrow = typeof throwOnError === \"function\" ? !!error && throwOnError(error) : !!error;\n\n if (shouldThrow && !snapshot.isFetching) {\n store.evictSoon();\n throw error;\n }\n }\n\n // ******************\n // Items\n // ******************\n\n const uniqueByRef = useRef(uniqueBy);\n uniqueByRef.current = uniqueBy;\n const uniqueByKey = typeof uniqueBy === \"function\" ? uniqueBy.toString() : uniqueBy;\n\n const uniqueItems = useMemo(() => {\n return getUniqueItems(list.items, uniqueByRef.current);\n // Inline functions change on every render, the key changes only with their code\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [list.items, uniqueByKey]);\n\n const selectedRef = useRef<unknown>(null);\n let items: unknown = uniqueItems;\n\n if (select) {\n const selected = select({ items: uniqueItems as PaginationItem<R, P>[], pages: list.data as any[] });\n items = structuralSharing ? replaceEqualDeep(selectedRef.current, selected) : selected;\n selectedRef.current = items;\n }\n\n // ******************\n // Actions\n // ******************\n\n const actions = useMemo(\n () => ({\n fetchNextPage: () => store.fetchNextPage(),\n fetchPreviousPage: () => store.fetchPreviousPage(),\n refetch: () => store.refetch(),\n reset: () => {\n callbacks.current.onReset?.();\n return store.reset();\n },\n abort: () => store.abort(),\n onSuccess: (callback: (event: any) => void) => {\n callbacks.current.onSuccess = callback;\n },\n onError: (callback: (event: any) => void) => {\n callbacks.current.onError = callback;\n },\n onFinished: (callback: (event: any) => void) => {\n callbacks.current.onFinished = callback;\n },\n onReset: (callback: VoidFunction) => {\n callbacks.current.onReset = callback;\n },\n }),\n [store],\n );\n\n return createTrackedProxy(\n {\n items,\n pages: list.data,\n pageParams: list.pageParams,\n total: list.total,\n hasNextPage: snapshot.hasNextPage,\n hasPreviousPage: snapshot.hasPreviousPage,\n loading: !disabled && snapshot.loading && !isPreviousData,\n isFetching: snapshot.isFetching,\n isRefetching: snapshot.isRefetching,\n isFetchingNextPage: snapshot.isFetchingNextPage,\n isFetchingPreviousPage: snapshot.isFetchingPreviousPage,\n isFetchNextPageError: snapshot.isFetchNextPageError,\n isFetchPreviousPageError: snapshot.isFetchPreviousPageError,\n isPreviousData,\n error: snapshot.error,\n status: snapshot.status,\n extra: snapshot.extra,\n success: snapshot.success,\n bounce: getBounceData(bounceData),\n ...actions,\n },\n trackedKeys,\n (usedKey) => usedKeys.add(usedKey),\n ) as unknown as UseInfiniteFetchReturnType<R, P, TSelected>;\n};\n","import { useDebounce, useThrottle } from \"@better-hooks/performance\";\nimport type {\n ExtractAdapterResolvedType,\n RequestInstance,\n ResponseType,\n ExtractResponseType,\n ExtractErrorType,\n RequestSendOptionsType,\n RequestSendType,\n ExtractAdapterType,\n} from \"@hyper-fetch/core\";\nimport { sendRequest } from \"@hyper-fetch/core\";\nimport type { UseTrackedStateType } from \"helpers\";\nimport { useTrackedState, useRequestEvents } from \"helpers\";\nimport type { UseSubmitOptionsType, UseSubmitReturnType } from \"hooks/use-submit\";\nimport { useSubmitDefaultOptions } from \"hooks/use-submit\";\nimport { useProvider } from \"provider\";\nimport { useEffect, useMemo, useRef } from \"react\";\nimport { createTrackedProxy, getBounceData } from \"utils\";\n\n/**\n * This hook aims to mutate data on the server. Unlike useFetch, it does not fire automatically -\n * call the returned `submit` function to trigger the request (e.g., on button click).\n * @param request\n * @param options\n * @returns\n */\nexport const useSubmit = <RequestType extends RequestInstance, TSelected = ExtractResponseType<RequestType>>(\n request: RequestType,\n options?: UseSubmitOptionsType<RequestType, TSelected>,\n): UseSubmitReturnType<RequestType, TSelected> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const mergedOptions: UseSubmitOptionsType<RequestType, TSelected> = useMemo(\n () => ({\n ...useSubmitDefaultOptions,\n ...globalConfig.useSubmitConfig,\n ...options,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [globalConfig.useSubmitConfig, JSON.stringify(options), options?.deepCompare],\n );\n const {\n disabled,\n dependencyTracking,\n initialResponse,\n bounce,\n bounceType,\n bounceTime,\n deepCompare,\n structuralSharing,\n } = mergedOptions;\n\n /**\n * Because of the dynamic cacheKey / queryKey signing within the request we need to store it's latest instance\n * so the events got triggered properly and show the latest result without mixing it up\n */\n const { client } = request;\n const { cache, submitDispatcher: dispatcher, loggerManager } = client;\n\n const logger = useRef(loggerManager.initialize(client, \"useSubmit\")).current;\n const requestDebounce = useDebounce({ delay: bounceTime });\n const requestThrottle = useThrottle({\n interval: bounceTime,\n timeout: \"bounceTimeout\" in mergedOptions ? mergedOptions.bounceTimeout : bounceTime,\n });\n const bounceResolver = useRef<\n (\n value: ResponseType<\n ExtractResponseType<RequestType>,\n ExtractErrorType<RequestType>,\n ExtractAdapterType<RequestType>\n >,\n ) => void\n >(() => null);\n\n const bounceData = bounceType === \"throttle\" ? requestThrottle : requestDebounce;\n const bounceFunction = bounceType === \"throttle\" ? requestThrottle.throttle : requestDebounce.debounce;\n\n /**\n * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues\n */\n const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<\n RequestType,\n TSelected\n >({\n logger,\n request,\n dispatcher,\n initialResponse,\n deepCompare: deepCompare as boolean,\n dependencyTracking: dependencyTracking as boolean,\n // Read directly from options - functions are not part of the memoized options key\n select: options?.select,\n structuralSharing,\n });\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [callbacks, listeners] = useRequestEvents({\n logger,\n actions,\n request,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners } = listeners;\n\n // ******************\n // Submitting\n // ******************\n\n const handleSubmit: RequestSendType<RequestType> = (submitOptions?: RequestSendOptionsType<RequestType>) => {\n const requestClone = request.clone(submitOptions as any) as unknown as RequestType;\n\n if (disabled) {\n logger.warning({ title: `Cannot submit request`, type: \"system\", extra: { disabled, submitOptions } });\n return Promise.resolve({\n data: null,\n error: new Error(\"Cannot submit request. Option 'disabled' is enabled\"),\n status: null,\n extra: request.client.adapter.defaultExtra,\n }) as Promise<\n ResponseType<ExtractResponseType<RequestType>, ExtractErrorType<RequestType>, ExtractAdapterType<RequestType>>\n >;\n }\n\n const triggerRequest = () => {\n addCacheDataListener(requestClone);\n\n const configuration: RequestSendOptionsType<RequestType> = {\n dispatcherType: \"submit\",\n ...(submitOptions as RequestSendOptionsType<RequestType>),\n onBeforeSent: (data) => {\n addLifecycleListeners(requestClone, data.requestId, data.mutationContext);\n submitOptions?.onBeforeSent?.(data);\n },\n };\n\n return sendRequest(requestClone, configuration);\n };\n\n return new Promise<ExtractAdapterResolvedType<RequestType>>((resolve) => {\n const performSubmit = async () => {\n logger.debug({ title: `Submitting request`, type: \"system\", extra: { disabled, submitOptions } });\n if (bounce) {\n const bouncedResolve = bounceResolver.current;\n // We need to keep the resolve of debounced requests to prevent memory leaks - we need to always resolve promise.\n // By default bounce method will prevent function to be triggered, but returned promise will still await to be resolved.\n // This way we can close previous promise, making sure our logic will not stuck in memory.\n bounceResolver.current = (\n value: ResponseType<\n ExtractResponseType<RequestType>,\n ExtractErrorType<RequestType>,\n ExtractAdapterType<RequestType>\n >,\n ) => {\n // Trigger previous awaiting calls to resolve together in bounced batches\n bouncedResolve(value);\n resolve(value);\n };\n\n // Start bounce\n bounceFunction(async () => {\n // We will always resolve previous calls as we stack the callbacks together until bounce function trigger\n const callback = bounceResolver.current;\n // Clean bounce resolvers to start the new stack\n bounceResolver.current = () => null;\n\n const value = await triggerRequest();\n callback(value);\n });\n } else {\n const value = await triggerRequest();\n resolve(value);\n }\n };\n\n performSubmit();\n });\n };\n\n // ******************\n // Invalidation\n // ******************\n\n const refetch = () => {\n cache.invalidate(request);\n };\n\n // ******************\n // Misc\n // ******************\n\n const handlers = {\n onSubmitSuccess: callbacks.onSuccess,\n onSubmitError: callbacks.onError,\n onSubmitFinished: callbacks.onFinished,\n onSubmitRequestStart: callbacks.onRequestStart,\n onSubmitResponseStart: callbacks.onResponseStart,\n onSubmitDownloadProgress: callbacks.onDownloadProgress,\n onSubmitUploadProgress: callbacks.onUploadProgress,\n onSubmitOfflineError: callbacks.onOfflineError,\n onSubmitAbort: callbacks.onAbort,\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without the cache subscription\n useEffect(() => {\n addCacheDataListener(request);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const setSubmitRenderKey = (key: string) => {\n setRenderKey((key === \"submitting\" ? \"loading\" : key) as keyof UseTrackedStateType);\n };\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"submitting\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n submit: handleSubmit,\n data: state.data,\n error: state.error,\n submitting: state.loading,\n status: state.status,\n success: state.success,\n extra: state.extra,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n abort: callbacks.abort,\n ...actions,\n ...handlers,\n bounce: getBounceData(bounceData),\n refetch,\n },\n trackedKeys,\n setSubmitRenderKey,\n ) as UseSubmitReturnType<RequestType, TSelected>;\n};\n","import type { RequestInstance, RequiredKeys } from \"@hyper-fetch/core\";\n\nimport type { UseSubmitOptionsType } from \"./use-submit.types\";\n\ntype DefaultOptionsType = RequiredKeys<Omit<UseSubmitOptionsType<RequestInstance>, \"initialResponse\" | \"select\">> & {\n initialResponse: null;\n};\n\nexport const useSubmitDefaultOptions: DefaultOptionsType = {\n disabled: false,\n dependencyTracking: true,\n initialResponse: null,\n bounce: false,\n bounceType: \"debounce\",\n bounceTime: 400,\n deepCompare: true,\n structuralSharing: true,\n};\n","import type { RequestInstance, ResolvedQueueItemType, QueueDataType, QueueItemType } from \"@hyper-fetch/core\";\nimport { Request, getRequestDispatcher, scopeKey } from \"@hyper-fetch/core\";\nimport type { UseQueueOptionsType, QueueRequest, UseQueueReturnType } from \"hooks/use-queue\";\nimport { useQueueDefaultOptions } from \"hooks/use-queue\";\nimport { useProvider } from \"provider\";\nimport { useState, useEffect, useCallback } from \"react\";\n\nconst canUpdate = (\n item: Pick<QueueRequest<RequestInstance>, \"success\" | \"failed\" | \"canceled\" | \"removed\" | \"resolved\">,\n) => {\n if (item.success || item.failed) {\n return false;\n }\n return true;\n};\n\n/**\n * This hook allows you to monitor and control dispatcher request queues for a given request,\n * including starting, stopping, pausing, and inspecting pending/in-flight items.\n * @param request\n * @param options\n * @returns\n */\nexport const useQueue = <Request extends RequestInstance>(\n request: Request,\n options?: UseQueueOptionsType,\n): UseQueueReturnType<Request> => {\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const { dispatcherType, keepFinishedRequests } = {\n ...useQueueDefaultOptions,\n ...globalConfig.useQueueConfig,\n ...options,\n };\n\n const { abortKey: rawAbortKey, queryKey: rawQueryKey, scope, client } = request;\n const abortKey = scopeKey(rawAbortKey, scope);\n const queryKey = scopeKey(rawQueryKey, scope);\n const { requestManager } = client;\n\n const [dispatcher] = getRequestDispatcher(request, dispatcherType);\n\n const [stopped, setStopped] = useState(false);\n const [requests, setRequests] = useState<QueueRequest<Request>[]>([]);\n\n // ******************\n // Mapping\n // ******************\n\n const createRequestsArray = useCallback(\n (\n queueElements: ResolvedQueueItemType<Request>[],\n prevRequests?: QueueRequest<Request>[],\n ): QueueRequest<Request>[] => {\n const newRequests = queueElements\n // Keep only unique requests\n .filter((el) => !prevRequests?.some((prevEl) => prevEl.requestId === el.requestId))\n .map<QueueRequest<Request>>((req) => ({\n failed: false,\n canceled: false,\n removed: false,\n success: false,\n ...req,\n downloading: {\n progress: 0,\n timeLeft: 0,\n sizeLeft: 0,\n total: 0,\n loaded: 0,\n startTimestamp: 0,\n },\n uploading: {\n progress: 0,\n timeLeft: 0,\n sizeLeft: 0,\n total: 0,\n loaded: 0,\n startTimestamp: 0,\n },\n stopRequest: () => dispatcher.stopRequest(queryKey, req.requestId),\n startRequest: () => dispatcher.startRequest(queryKey, req.requestId),\n deleteRequest: () => dispatcher.delete(queryKey, req.requestId, abortKey),\n }));\n\n if (keepFinishedRequests && prevRequests) {\n return [...prevRequests, ...newRequests];\n }\n\n return newRequests;\n },\n [abortKey, dispatcher, queryKey, keepFinishedRequests],\n );\n\n const mergePayloadType = useCallback((requestId: string, data: Partial<QueueRequest<Request>>) => {\n setRequests((prev) =>\n prev.map((el) => {\n if (el.requestId === requestId && canUpdate(el)) {\n return { ...el, ...data };\n }\n return el;\n }),\n );\n }, []);\n\n // ******************\n // State\n // ******************\n\n const getInitialState = () => {\n const requestQueue = dispatcher.getQueue<Request>(queryKey);\n\n setStopped(requestQueue.stopped);\n setRequests(createRequestsArray(requestQueue.requests));\n };\n\n const resolveQueueItems = useCallback(\n (items: QueueItemType<Request>[]): ResolvedQueueItemType<Request>[] => {\n return items.map((item) => {\n if (item.request instanceof Request) {\n return item as ResolvedQueueItemType<Request>;\n }\n return { ...item, request: client.fromJSON(item.request) as Request };\n });\n },\n [client],\n );\n\n const updateQueueState = useCallback(\n (values: QueueDataType<Request>) => {\n setStopped(values.stopped);\n setRequests((prev) => createRequestsArray(resolveQueueItems(values.requests), prev));\n },\n [createRequestsArray, resolveQueueItems],\n );\n\n // ******************\n // Events\n // ******************\n\n const mountEvents = () => {\n const unmountChange = dispatcher.events.onQueueChangeByKey<Request>(queryKey, updateQueueState);\n const unmountStatus = dispatcher.events.onQueueStatusChangeByKey<Request>(queryKey, updateQueueState);\n\n const unmountFailed = requestManager.events.onResponse(({ requestId, response }) => {\n if (!response.success) {\n setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, failed: true } : el)));\n } else {\n setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, success: true } : el)));\n }\n });\n const unmountCanceled = requestManager.events.onAbort(({ requestId }) => {\n setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, canceled: true } : el)));\n });\n\n const unmountRemoved = requestManager.events.onRemove(({ requestId }) => {\n setRequests((prev) =>\n prev.map((el) => (el.requestId === requestId && canUpdate(el) ? { ...el, removed: true } : el)),\n );\n });\n\n const unmountDownload = requestManager.events.onDownloadProgress(\n ({ progress, timeLeft, sizeLeft, total, loaded, startTimestamp, requestId }) => {\n mergePayloadType(requestId, { downloading: { progress, timeLeft, sizeLeft, total, loaded, startTimestamp } });\n },\n );\n\n const unmountUpload = requestManager.events.onUploadProgress(\n ({ progress, timeLeft, sizeLeft, total, loaded, startTimestamp, requestId }) => {\n mergePayloadType(requestId, { uploading: { progress, timeLeft, sizeLeft, total, loaded, startTimestamp } });\n },\n );\n\n const unmount = () => {\n unmountStatus();\n unmountChange();\n unmountDownload();\n unmountUpload();\n unmountFailed();\n unmountCanceled();\n unmountRemoved();\n };\n\n return unmount;\n };\n\n // ******************\n // Lifecycle\n // ******************\n\n useEffect(getInitialState, [createRequestsArray, dispatcher, queryKey]);\n\n useEffect(mountEvents, [\n stopped,\n requests,\n setRequests,\n setStopped,\n queryKey,\n dispatcher.events,\n requestManager.events,\n updateQueueState,\n mergePayloadType,\n ]);\n\n return {\n stopped,\n requests,\n dispatcher,\n stop: () => dispatcher.stop(queryKey),\n pause: () => dispatcher.pause(queryKey),\n start: () => dispatcher.start(queryKey),\n };\n};\n","import type { RequiredKeys } from \"@hyper-fetch/core\";\nimport type { UseQueueOptionsType } from \"hooks/use-queue\";\n\nexport const useQueueDefaultOptions: RequiredKeys<UseQueueOptionsType> = {\n dispatcherType: \"auto\",\n keepFinishedRequests: false,\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { ExtractResponseType, RequestInstance } from \"@hyper-fetch/core\";\nimport { getRequestDispatcher } from \"@hyper-fetch/core\";\nimport { useRequestEvents, useTrackedState } from \"helpers\";\nimport type { UseCacheOptionsType, UseCacheReturnType } from \"hooks/use-cache\";\nimport { useCacheDefaultOptions } from \"hooks/use-cache\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\n\n/** Subscribe to cache updates for a given request without triggering network activity. */\nexport const useCache = <T extends RequestInstance, TSelected = ExtractResponseType<T>>(\n request: T,\n options?: UseCacheOptionsType<T, TSelected>,\n): UseCacheReturnType<T, TSelected> => {\n const { cacheKey, client } = request;\n\n const { cache, loggerManager } = client;\n const logger = useRef(loggerManager.initialize(client, \"useCache\")).current;\n const [dispatcher] = getRequestDispatcher(request);\n const updateKey = JSON.stringify(request.toJSON());\n\n // Build the configuration options\n const { config: globalConfig } = useProvider();\n const { dependencyTracking, initialResponse, deepCompare, structuralSharing } = {\n ...useCacheDefaultOptions,\n ...globalConfig.useCacheConfig,\n ...options,\n };\n\n /**\n * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues\n */\n const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<T, TSelected>({\n logger,\n request,\n dispatcher,\n initialResponse,\n deepCompare,\n dependencyTracking,\n select: options?.select,\n structuralSharing,\n });\n\n /**\n * Handles the data exchange with the core logic - responses, loading, downloading etc\n */\n const [, listeners] = useRequestEvents({\n logger,\n actions,\n request,\n dispatcher,\n setCacheData,\n getIsDataProcessing,\n });\n\n const { addCacheDataListener, addLifecycleListeners } = listeners;\n\n const handleMountEvents = () => {\n const unmountDataListener = addCacheDataListener(request);\n const unmountLifecycleListener = addLifecycleListeners(request);\n return () => {\n unmountDataListener();\n unmountLifecycleListener();\n };\n };\n\n useDidUpdate(\n () => {\n return handleMountEvents();\n },\n [updateKey],\n true,\n );\n\n const invalidate = (cacheKeys?: string | RegExp | RequestInstance | (string | RegExp | RequestInstance)[]) => {\n cache.invalidate(cacheKeys ?? cacheKey);\n };\n\n const trackedKeys = [\n \"data\",\n \"error\",\n \"loading\",\n \"status\",\n \"success\",\n \"extra\",\n \"retries\",\n \"responseTimestamp\",\n \"requestTimestamp\",\n ] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n error: state.error,\n loading: state.loading,\n status: state.status,\n success: state.success,\n extra: state.extra,\n retries: state.retries,\n responseTimestamp: state.responseTimestamp,\n requestTimestamp: state.requestTimestamp,\n ...actions,\n invalidate,\n },\n trackedKeys,\n setRenderKey,\n ) as UseCacheReturnType<T, TSelected>;\n};\n","export const useCacheDefaultOptions = {\n dependencyTracking: true,\n initialResponse: null,\n deepCompare: true,\n structuralSharing: true,\n};\n","import type { RequestInstance, ExtractAdapterExtraType, ExtractAdapterType, ExtractErrorType } from \"@hyper-fetch/core\";\nimport { scopeKey } from \"@hyper-fetch/core\";\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\n\nimport type { UseStreamOptionsType, UseStreamReturnType } from \"./use-stream.types\";\n\ntype StreamState<T extends RequestInstance> = {\n text: string;\n chunks: Uint8Array[];\n streaming: boolean;\n done: boolean;\n error: ExtractErrorType<T> | null;\n extra: ExtractAdapterExtraType<ExtractAdapterType<T>> | null;\n status: number | null;\n};\n\nconst getInitialState = <T extends RequestInstance>(): StreamState<T> => ({\n text: \"\",\n chunks: [],\n streaming: false,\n done: false,\n error: null,\n extra: null,\n status: null,\n});\n\n/**\n * Hook for consuming streaming responses chunk-by-chunk.\n * Works with any request that uses the fetch adapter's `streaming: true` option.\n *\n * Provides both accumulated `text` (for LLM/SSE use cases) and raw `chunks`\n * (for binary streaming / file downloads).\n */\nexport const useStream = <T extends RequestInstance>(\n request: T,\n options?: UseStreamOptionsType,\n): UseStreamReturnType<T> => {\n const { autoStart = false } = options || {};\n\n const state = useRef<StreamState<T>>(getInitialState<T>());\n const abortRef = useRef<(() => void) | null>(null);\n const startedRef = useRef(false);\n\n // useSyncExternalStore for re-renders\n const versionRef = useRef(0);\n const listenerRef = useRef<(() => void) | null>(null);\n\n const subscribe = useCallback((listener: () => void) => {\n listenerRef.current = listener;\n return () => {\n listenerRef.current = null;\n };\n }, []);\n\n const getSnapshot = useCallback(() => versionRef.current, []);\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const emitChange = () => {\n versionRef.current += 1;\n listenerRef.current?.();\n };\n\n const consumeStream = async (stream: ReadableStream<Uint8Array>) => {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {break;}\n\n state.current.chunks = [...state.current.chunks, value];\n state.current.text += decoder.decode(value, { stream: true });\n emitChange();\n }\n\n state.current.streaming = false;\n state.current.done = true;\n emitChange();\n } catch (error) {\n state.current.streaming = false;\n state.current.error = error as ExtractErrorType<T>;\n emitChange();\n }\n };\n\n const start = useCallback(() => {\n if (state.current.streaming) {return;}\n\n state.current = {\n ...getInitialState<T>(),\n streaming: true,\n };\n emitChange();\n\n const streamingRequest = request.setOptions({ streaming: true } as any);\n\n streamingRequest.send().then((response) => {\n const { data, error, status, extra } = response;\n\n state.current.status = status as number | null;\n state.current.extra = extra as ExtractAdapterExtraType<ExtractAdapterType<T>> | null;\n\n if (error) {\n state.current.streaming = false;\n state.current.error = error;\n emitChange();\n return;\n }\n\n if (data && typeof (data as any).getReader === \"function\") {\n consumeStream(data as unknown as ReadableStream<Uint8Array>);\n } else {\n state.current.streaming = false;\n state.current.text = typeof data === \"string\" ? data : JSON.stringify(data);\n state.current.done = true;\n emitChange();\n }\n });\n\n abortRef.current = () => {\n request.client.requestManager.abortByKey(scopeKey(request.abortKey, request.scope));\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [request]);\n\n const abort = useCallback(() => {\n abortRef.current?.();\n state.current.streaming = false;\n emitChange();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const reset = useCallback(() => {\n abortRef.current?.();\n state.current = getInitialState<T>();\n startedRef.current = false;\n emitChange();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (autoStart && !startedRef.current) {\n startedRef.current = true;\n start();\n }\n }, [autoStart, start]);\n\n return {\n text: state.current.text,\n chunks: state.current.chunks,\n streaming: state.current.streaming,\n done: state.current.done,\n error: state.current.error,\n extra: state.current.extra,\n status: state.current.status,\n start,\n abort,\n reset,\n };\n};\n","import { useDidUpdate, useWillUnmount } from \"@better-hooks/lifecycle\";\nimport { replaceEqualDeep } from \"@hyper-fetch/core\";\nimport type { ListenerInstance, ExtractListenerDeliveredType } from \"@hyper-fetch/sockets\";\nimport { getDeliveryKey } from \"@hyper-fetch/sockets\";\nimport { useSocketState } from \"helpers\";\nimport type { UseListenerOptionsType } from \"hooks/use-listener\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\n\n/** Subscribe to incoming socket messages on a given listener topic with tracked connection state and callbacks. */\nexport const useListener = <\n ListenerType extends ListenerInstance,\n TSelected = ExtractListenerDeliveredType<ListenerType>,\n>(\n listener: ListenerType,\n options?: UseListenerOptionsType<ExtractListenerDeliveredType<ListenerType>, TSelected>,\n) => {\n const { config: globalConfig } = useProvider();\n const { dependencyTracking = true, structuralSharing = true } = { ...globalConfig.useListener, ...options };\n const select = options?.select;\n const [state, actions, callbacks, { setRenderKey, getState, rerender }] = useSocketState<\n TSelected,\n ListenerType[\"socket\"]\n >(listener.socket, { dependencyTracking });\n const removeListenerRef = useRef<ReturnType<typeof listener.listen> | null>(null);\n\n /**\n * Selection\n */\n\n const selectRef = useRef(select);\n selectRef.current = select;\n const appliedSelect = useRef(select);\n // Last message data before applying the selector - allows to re-run it when the selector changes\n const rawData = useRef<{ data: ExtractListenerDeliveredType<ListenerType> } | null>(null);\n const selectError = useRef<{ error: unknown } | null>(null);\n\n const selectData = (data: ExtractListenerDeliveredType<ListenerType>): TSelected => {\n if (!selectRef.current) {\n return data as unknown as TSelected;\n }\n const selected = selectRef.current(data);\n return structuralSharing ? replaceEqualDeep(getState().data, selected) : selected;\n };\n\n // Selector failed while processing a message - surface it to the closest error boundary\n if (selectError.current) {\n const { error } = selectError.current;\n selectError.current = null;\n throw error;\n }\n\n // Selector changed (e.g. it closes over a new prop) - re-run it against the last message\n if (appliedSelect.current !== select) {\n appliedSelect.current = select;\n if (rawData.current) {\n state.data = selectData(rawData.current.data);\n }\n }\n\n /**\n * Callbacks\n */\n\n const onEventCallback = useRef<\n null | ((response: { data: ExtractListenerDeliveredType<ListenerType>; extra: Record<string, any> }) => void)\n >(null);\n\n /**\n * Actions\n */\n\n const stopListener = () => {\n removeListenerRef.current?.();\n };\n\n const listen = () => {\n stopListener();\n removeListenerRef.current = listener.listen(({ data, extra }) => {\n onEventCallback.current?.({ data, extra });\n rawData.current = { data };\n appliedSelect.current = selectRef.current;\n\n let selected: TSelected;\n try {\n selected = selectData(data);\n } catch (error) {\n // Never throw inside of the socket events - rethrow it on render instead\n selectError.current = { error };\n rerender();\n return;\n }\n\n // With a selector, data is updated only when the selected value changed\n if (!selectRef.current || !Object.is(selected, getState().data)) {\n actions.setData(selected);\n }\n actions.setExtra(extra);\n actions.setTimestamp(Date.now());\n });\n };\n\n const additionalCallbacks = {\n onEvent: (callback: NonNullable<typeof onEventCallback.current>) => {\n onEventCallback.current = callback;\n },\n };\n\n /**\n * Lifecycle\n */\n\n useDidUpdate(\n () => {\n listen();\n },\n // Topic already contains resolved params. Delivery presets compare by value, custom strategies by identity.\n [listener.topic, JSON.stringify(listener.options), getDeliveryKey(listener.delivery)],\n true,\n );\n\n useWillUnmount(() => {\n stopListener();\n });\n\n const trackedKeys = [\"data\", \"extra\", \"connected\", \"connecting\", \"timestamp\"] as const;\n\n return createTrackedProxy(\n {\n data: state.data,\n extra: state.extra,\n connected: state.connected,\n connecting: state.connecting,\n timestamp: state.timestamp,\n ...actions,\n ...callbacks,\n ...additionalCallbacks,\n listen,\n },\n trackedKeys,\n setRenderKey,\n );\n};\n","import { useDidUpdate } from \"@better-hooks/lifecycle\";\nimport type { EmitterInstance, EmitterCallbackErrorType, EmitType } from \"@hyper-fetch/sockets\";\nimport { useSocketState } from \"helpers\";\nimport type { UseEmitterOptionsType } from \"hooks/use-emitter\";\nimport { useProvider } from \"provider\";\nimport { useRef } from \"react\";\nimport { createTrackedProxy } from \"utils\";\n\n/** Send messages through a socket emitter with tracked connection state and lifecycle callbacks. */\nexport const useEmitter = <EmitterType extends EmitterInstance>(\n emitter: EmitterType,\n options?: UseEmitterOptionsType,\n) => {\n const { config: globalConfig } = useProvider();\n const { dependencyTracking = true } = { ...globalConfig.useEmitter, ...options };\n\n const [state, actions, callbacks, { setRenderKey }] = useSocketState(emitter.socket, { dependencyTracking });\n\n /**\n * Callbacks\n */\n const onEventStartCallback = useRef<null | ((emitter: EmitterType) => void)>(null);\n const onEventErrorCallback = useRef<null | EmitterCallbackErrorType>(null);\n\n useDidUpdate(\n () => {\n const onEventStart = () => {\n return emitter.socket.events.onEmitterStartEventByTopic(emitter, () => {\n onEventStartCallback.current?.(emitter);\n });\n };\n\n const onEventError = () => {\n return emitter.socket.events.onEmitterErrorByTopic(emitter, ({ error }) => {\n onEventErrorCallback.current?.({ error });\n });\n };\n\n const unmountEventStart = onEventStart();\n const unmountEventError = onEventError();\n\n return () => {\n unmountEventStart();\n unmountEventError();\n };\n },\n [emitter.topic, onEventStartCallback.current, onEventErrorCallback.current],\n true,\n );\n\n /**\n * Emitter\n */\n\n const emit: EmitType<EmitterType> = (emitOptions: Parameters<EmitType<EmitterType>>[0]) => {\n return emitter.emit(emitOptions as any);\n };\n\n const onEmit = (callback: (emitter: EmitterType) => void) => {\n onEventStartCallback.current = callback;\n };\n\n const onEmitError = (callback: EmitterCallbackErrorType) => {\n onEventErrorCallback.current = callback;\n };\n\n const trackedKeys = [\"connected\", \"connecting\"] as const;\n\n return createTrackedProxy(\n {\n connected: state.connected,\n connecting: state.connecting,\n ...actions,\n ...callbacks,\n onEmit,\n onEmitError,\n emit,\n },\n trackedKeys,\n setRenderKey,\n );\n};\n","import type { ClientInstance } from \"@hyper-fetch/core\";\nimport type { UseAppManagerReturnType } from \"hooks/use-app-manager\";\nimport { useEffect, useState } from \"react\";\n\n/** Track the application's online/offline and focus/blur state through the client's AppManager. */\nexport const useAppManager = <Client extends ClientInstance>(client: Client): UseAppManagerReturnType => {\n const [online, setIsOnline] = useState(client.appManager.isOnline);\n const [focused, setIsFocused] = useState(client.appManager.isFocused);\n\n const mountEvents = () => {\n // Catch up with anything that happened between the render and the subscription\n setIsOnline(client.appManager.isOnline);\n setIsFocused(client.appManager.isFocused);\n\n const unmountIsOnline = client.appManager.events.onOnline(() => setIsOnline(true));\n const unmountIsOffline = client.appManager.events.onOffline(() => setIsOnline(false));\n const unmountIsFocus = client.appManager.events.onFocus(() => setIsFocused(true));\n const unmountIsBlur = client.appManager.events.onBlur(() => setIsFocused(false));\n\n return () => {\n unmountIsOnline();\n unmountIsOffline();\n unmountIsFocus();\n unmountIsBlur();\n };\n };\n\n const setOnline = (isOnline: boolean) => {\n client.appManager.setOnline(isOnline);\n };\n\n const setFocused = (isFocused: boolean) => {\n client.appManager.setFocused(isFocused);\n };\n\n // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,\n // so a mount-once guard would leave the hook without any subscriptions\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(mountEvents, [client]);\n\n return { isOnline: online, isFocused: focused, setOnline, setFocused };\n};\n","import type { AdapterInstance, ClientInstance, Dispatcher } from \"@hyper-fetch/core\";\nimport type { UseIsFetchingOptionsType } from \"hooks/use-is-fetching\";\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\n\nconst useRunningRequestsCount = (\n dispatcher: Dispatcher<AdapterInstance>,\n options?: UseIsFetchingOptionsType,\n): number => {\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const subscribe = useCallback(\n (listener: () => void) => dispatcher.events.onRunningRequestsChange(listener),\n [dispatcher],\n );\n\n const getCount = () => {\n const { queryKey, predicate } = optionsRef.current || {};\n return dispatcher.getAllRunningRequests().filter(({ request }) => {\n if (typeof queryKey === \"string\" && request.queryKey !== queryKey) {\n return false;\n }\n if (queryKey instanceof RegExp && !queryKey.test(request.queryKey)) {\n return false;\n }\n return !predicate || predicate(request);\n }).length;\n };\n\n return useSyncExternalStore(subscribe, getCount, getCount);\n};\n\n/**\n * Count of the currently running fetch requests (useFetch, useCache and fetch dispatcher). Useful for global loading indicators.\n * @param client Client instance\n * @param options Filters for the counted requests\n * @returns number of running requests\n */\nexport const useIsFetching = (client: ClientInstance, options?: UseIsFetchingOptionsType): number => {\n return useRunningRequestsCount(client.fetchDispatcher, options);\n};\n\n/**\n * Count of the currently running submit requests (useSubmit and submit dispatcher). Useful for global saving indicators.\n * @param client Client instance\n * @param options Filters for the counted requests\n * @returns number of running requests\n */\nexport const useIsSubmitting = (client: ClientInstance, options?: UseIsFetchingOptionsType): number => {\n return useRunningRequestsCount(client.submitDispatcher, options);\n};\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;AAAkG,IAAwJ,IAAE,SAAS,GAAE;CAAC,IAAI,IAAEA,OAAE,CAAC,EAAE;AAAC,YAAG,WAAU;AAAC,MAAG,CAAC,EAAE,QAAQ,QAAO,EAAE,UAAQ,CAAC,GAAE,GAAG;KAAG,EAAE,CAAC;GAAE,IAAE,SAAS,GAAE,GAAE,GAAE;AAAC,MAAK,MAAI,MAAI,IAAE,CAAC;CAAG,IAAI,IAAEA,OAAE,EAAE;AAAC,YAAG,WAAU;AAAC,MAAG,EAAE,QAAQ,QAAO,GAAG;AAAC,IAAE,UAAQ,CAAC;KAAI,EAAE;GAAMC,MAAE,WAAU;CAAC,IAAI,IAAE,SAAS,GAAE,GAAE;EAAC,IAAI,IAAE,cAAY,OAAO,UAAQ,EAAE,OAAO;AAAU,MAAG,CAAC,EAAE,QAAO;EAAE,IAAI,GAAE,GAAE,IAAE,EAAE,KAAK,EAAE,EAAC,IAAE,EAAE;AAAC,MAAG;AAAC,WAAM,KAAK,MAAI,KAAG,MAAK,MAAI,EAAE,IAAE,EAAE,MAAM,EAAE,MAAM,GAAE,KAAK,EAAE,MAAM;WAAO,GAAE;AAAC,OAAE,EAAC,OAAM,GAAE;YAAQ;AAAC,OAAG;AAAC,SAAG,CAAC,EAAE,SAAO,IAAE,EAAE,WAAS,EAAE,KAAK,EAAE;aAAQ;AAAC,QAAG,EAAE,OAAM,EAAE;;;AAAO,SAAO;GAAGC,SAAE,EAAE,EAAC,EAAE,CAAC;AAAG,QAAOC,aAAG,WAAU;AAAC,KAAG,SAAS,GAAE;AAAC,UAAO,IAAE;KAAI;KAAG,EAAE,CAAC;GAAEC,MAAE,WAAU;CAAC,IAAI,IAAEJ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