@hyper-fetch/core 9.5.0 → 9.5.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.
- package/__tests__/features/request/request.optimistic-settlement.spec.ts +1027 -0
- package/dist/index.mjs +91 -11
- package/dist/index.mjs.map +1 -1
- package/dist/request/request.d.ts +4 -4
- package/dist/request/request.types.d.ts +20 -3
- package/dist/request/request.types.d.ts.map +1 -1
- package/dist/request/request.utils.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/request/request.ts +4 -4
- package/src/request/request.types.ts +15 -3
- package/src/request/request.utils.ts +128 -17
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/plugin/plugin.ts","../src/constants/time.constants.ts","../src/request/request.hooks.ts","../src/mocker/mocker.ts","../src/adapter/adapter.bindings.ts","../src/utils/uuid.utils.ts","../../../node_modules/.pnpm/events@3.3.0/node_modules/events/events.js","../src/utils/emitter.utils.ts","../src/managers/app/app.manager.ts","../src/managers/app/app.manager.utils.ts","../src/managers/app/app.manager.events.ts","../src/managers/app/app.manager.constants.ts","../src/managers/request/request.manager.ts","../src/managers/request/request.manager.utils.ts","../src/managers/request/request.manager.events.ts","../src/managers/logger/logger.manager.ts","../src/managers/logger/logger.manager.utils.ts","../src/managers/logger/logger.manager.constants.ts","../src/adapter/adapter.utils.ts","../src/adapter/adapter.ts","../src/constants/http.constants.ts","../src/request/request.utils.ts","../src/request/request.ts","../src/cache/cache.ts","../src/cache/cache.utils.ts","../src/cache/cache.events.ts","../src/dispatcher/dispatcher.constants.ts","../src/dispatcher/dispatcher.events.ts","../src/dispatcher/dispatcher.ts","../src/dispatcher/dispatcher.utils.ts","../src/http-adapter/http-adapter.constants.ts","../src/http-adapter/http-adapter.utils.ts","../src/http-adapter/http-adapter.fetch.ts","../src/http-adapter/http-adapter.ts","../src/client/client.utils.ts","../src/client/client.ts","../src/client/client.constants.ts","../src/client/client.create.ts","../src/sdk/sdk.ts"],"sourcesContent":["import type { ClientInstance } from \"client\";\nimport type { PluginMethodParameters, PluginMethods, PluginOptionsType } from \"plugin\";\n\n/**\n * Base class for plugins that hook into the request, cache, dispatcher, and adapter lifecycle.\n * Extend this to build devtools, logging, analytics, or custom side-effect plugins.\n */\nexport class Plugin<Client extends ClientInstance = ClientInstance, PluginData = void> {\n public name: string;\n public data: PluginData;\n\n public client: Client | undefined = undefined;\n\n private pluginMethods: Partial<PluginMethods<Client>> = {};\n\n constructor(public config: PluginOptionsType<PluginData>) {\n this.name = config.name;\n if (config.data) {\n this.data = config.data;\n }\n }\n\n /** Bind the plugin to a client instance. Called automatically when the plugin is added via `client.addPlugin()`. */\n initialize = (client: Client) => {\n this.client = client;\n return this;\n };\n\n /** Invoke a registered plugin method by name. Used internally by the client to dispatch lifecycle events. */\n trigger = <Key extends keyof PluginMethods<Client>>(method: Key, data: PluginMethodParameters<Key, Client>) => {\n const callback = this.pluginMethods[method];\n if (callback) {\n callback(data as any);\n }\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Plugin lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /**\n * Callback that will be executed when plugin is mounted\n */\n onMount = (callback: PluginMethods<Client>[\"onMount\"]) => {\n this.pluginMethods.onMount = callback;\n return this;\n };\n\n /**\n * Callback that will be executed when plugin is unmounted\n */\n onUnmount = (callback: PluginMethods<Client>[\"onUnmount\"]) => {\n this.pluginMethods.onUnmount = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Request lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /**\n * Callback that will be executed when request is created\n */\n onRequestCreate = (callback: PluginMethods<Client>[\"onRequestCreate\"]) => {\n this.pluginMethods.onRequestCreate = callback;\n return this;\n };\n /**\n * Callback that will be executed when request gets triggered\n */\n onRequestTrigger = (callback: PluginMethods<Client>[\"onRequestTrigger\"]) => {\n this.pluginMethods.onRequestTrigger = callback;\n return this;\n };\n /**\n * Callback that will be executed when request starts\n */\n onRequestStart = (callback: PluginMethods<Client>[\"onRequestStart\"]) => {\n this.pluginMethods.onRequestStart = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is successful\n */\n onRequestSuccess = (callback: PluginMethods<Client>[\"onRequestSuccess\"]) => {\n this.pluginMethods.onRequestSuccess = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is failed\n */\n onRequestError = (callback: PluginMethods<Client>[\"onRequestError\"]) => {\n this.pluginMethods.onRequestError = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is finished\n */\n onRequestFinished = (callback: PluginMethods<Client>[\"onRequestFinished\"]) => {\n this.pluginMethods.onRequestFinished = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Dispatcher lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when the dispatcher storage is fully cleared */\n onDispatcherCleared = (callback: PluginMethods<Client>[\"onDispatcherCleared\"]) => {\n this.pluginMethods.onDispatcherCleared = callback;\n return this;\n };\n\n /** Called when a dispatcher queue has no more pending requests */\n onDispatcherQueueDrained = (callback: PluginMethods<Client>[\"onDispatcherQueueDrained\"]) => {\n this.pluginMethods.onDispatcherQueueDrained = callback;\n return this;\n };\n\n /** Called when a dispatcher queue transitions to running, paused, or stopped */\n onDispatcherQueueRunning = (callback: PluginMethods<Client>[\"onDispatcherQueueRunning\"]) => {\n this.pluginMethods.onDispatcherQueueRunning = callback;\n return this;\n };\n\n /** Called when a new item is added to a dispatcher queue */\n onDispatcherItemAdded = (callback: PluginMethods<Client>[\"onDispatcherItemAdded\"]) => {\n this.pluginMethods.onDispatcherItemAdded = callback;\n return this;\n };\n\n /** Called when an item is removed from a dispatcher queue */\n onDispatcherItemDeleted = (callback: PluginMethods<Client>[\"onDispatcherItemDeleted\"]) => {\n this.pluginMethods.onDispatcherItemDeleted = callback;\n return this;\n };\n\n /** Called when a new dispatcher queue is created */\n onDispatcherQueueCreated = (callback: PluginMethods<Client>[\"onDispatcherQueueCreated\"]) => {\n this.pluginMethods.onDispatcherQueueCreated = callback;\n return this;\n };\n\n /** Called when an entire dispatcher queue is cleared */\n onDispatcherQueueCleared = (callback: PluginMethods<Client>[\"onDispatcherQueueCleared\"]) => {\n this.pluginMethods.onDispatcherQueueCleared = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Cache lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when a cache entry is created or updated */\n onCacheItemChange = (callback: PluginMethods<Client>[\"onCacheItemChange\"]) => {\n this.pluginMethods.onCacheItemChange = callback;\n return this;\n };\n\n /** Called when a cache entry is deleted */\n onCacheItemDelete = (callback: PluginMethods<Client>[\"onCacheItemDelete\"]) => {\n this.pluginMethods.onCacheItemDelete = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Adapter lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when the adapter fetcher is about to execute a request */\n onAdapterFetch = (callback: PluginMethods<Client>[\"onAdapterFetch\"]) => {\n this.pluginMethods.onAdapterFetch = callback;\n return this;\n };\n}\n","export enum Time {\n SEC = 1e3,\n MIN = 6e4,\n HOUR = 3.6e6,\n DAY = 8.64e7,\n WEEK = 6.048e8,\n MONTH_30 = 2.592e9,\n MONTH_31 = 2.6784e9,\n YEAR = 3.1536e10,\n YEAR_LEAP = 3.162_24e10,\n}\n","import type { RequestEventType, RequestProgressEventType, RequestResponseEventType } from \"managers\";\n\nimport type { RequestInstance } from \"./request.types\";\n\ntype HookName =\n | \"onBeforeSent\"\n | \"onRequestStart\"\n | \"onResponseStart\"\n | \"onUploadProgress\"\n | \"onDownloadProgress\"\n | \"onResponse\"\n | \"onRemove\";\n\nexport interface RequestHooks<R extends RequestInstance> {\n onBeforeSent: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onRequestStart: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onResponseStart: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onUploadProgress: (cb: (eventData: RequestProgressEventType<R>) => void) => () => void;\n onDownloadProgress: (cb: (eventData: RequestProgressEventType<R>) => void) => () => void;\n onResponse: (cb: (eventData: RequestResponseEventType<R>) => void) => () => void;\n onRemove: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n /** @internal Invoke all registered listeners for a given hook */\n __emit: (name: HookName, data: any) => void;\n /** @internal Get a snapshot of all registered listeners (used by clone) */\n __snapshot: () => Record<HookName, ((...args: any[]) => void)[]>;\n}\n\nconst HOOK_NAMES: HookName[] = [\n \"onBeforeSent\",\n \"onRequestStart\",\n \"onResponseStart\",\n \"onUploadProgress\",\n \"onDownloadProgress\",\n \"onResponse\",\n \"onRemove\",\n];\n\nexport function createRequestHooks<R extends RequestInstance>(\n initial?: Record<HookName, ((...args: any[]) => void)[]>,\n): RequestHooks<R> {\n const listeners: Record<HookName, ((...args: any[]) => void)[]> = {\n onBeforeSent: [],\n onRequestStart: [],\n onResponseStart: [],\n onUploadProgress: [],\n onDownloadProgress: [],\n onResponse: [],\n onRemove: [],\n };\n\n if (initial) {\n HOOK_NAMES.forEach((name) => {\n listeners[name] = [...initial[name]];\n });\n }\n\n const subscribe = (name: HookName) => {\n return (cb: (...args: any[]) => void) => {\n listeners[name].push(cb);\n return () => {\n const idx = listeners[name].indexOf(cb);\n if (idx !== -1) {listeners[name].splice(idx, 1);}\n };\n };\n };\n\n return {\n onBeforeSent: subscribe(\"onBeforeSent\"),\n onRequestStart: subscribe(\"onRequestStart\"),\n onResponseStart: subscribe(\"onResponseStart\"),\n onUploadProgress: subscribe(\"onUploadProgress\"),\n onDownloadProgress: subscribe(\"onDownloadProgress\"),\n onResponse: subscribe(\"onResponse\"),\n onRemove: subscribe(\"onRemove\"),\n __emit(name: HookName, data: any) {\n listeners[name].forEach((cb) => {\n cb(data);\n });\n },\n __snapshot() {\n const snap = {} as Record<HookName, ((...args: any[]) => void)[]>;\n HOOK_NAMES.forEach((name) => {\n snap[name] = [...listeners[name]];\n });\n return snap;\n },\n };\n}\n","import type { getAdapterBindings, AdapterInstance } from \"adapter\";\nimport { RequestProcessingError } from \"adapter\";\nimport type { ExtractAdapterExtraType, ExtractAdapterStatusType } from \"types\";\n\nexport const mocker = async <T extends AdapterInstance>({\n request,\n requestId,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n onResponseProgress,\n onRequestProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onSuccess,\n onAbortError,\n adapter,\n}: Awaited<ReturnType<typeof getAdapterBindings<T>>>) => {\n if (!request.unstable_mock) {\n throw new RequestProcessingError(\"Mock should be defined when calling mocker\");\n }\n\n let thrown = false;\n\n const {\n requestTime = 20,\n responseTime = 20,\n totalUploaded = 1000,\n totalDownloaded = 1000,\n timeout,\n } = request.unstable_mock.config;\n const result = await request.unstable_mock.fn({ request, requestId });\n\n const { data, error, status, success = true, extra = request.client.adapter.defaultExtra } = result;\n\n createAbortListener({\n status: adapter.systemErrorStatus,\n extra: adapter.systemErrorExtra,\n onAbort: () => {\n thrown = true;\n },\n });\n\n onBeforeRequest();\n onRequestStart();\n\n const progress = (\n totalTime: number,\n totalSize: number,\n progressFunction: typeof onResponseProgress | typeof onRequestProgress,\n ) =>\n new Promise((resolveProgress) => {\n if (thrown) {\n resolveProgress(true);\n return;\n }\n\n const interval = 20;\n const dataStart = Date.now();\n const intervals = Math.ceil(totalTime / interval);\n const chunkSize = Math.ceil(totalSize / intervals);\n let currentlyLoaded = 0;\n const timer = setInterval(function handleProgressInterval() {\n if (thrown) {\n resolveProgress(true);\n clearInterval(timer);\n }\n\n const currentTime = Math.min(totalTime, Date.now() - dataStart);\n currentlyLoaded += currentlyLoaded + chunkSize >= totalSize ? totalSize - currentlyLoaded : chunkSize;\n progressFunction({\n total: totalSize,\n loaded: currentTime >= totalTime ? totalSize : currentlyLoaded,\n });\n\n if (currentTime >= totalTime) {\n resolveProgress(true);\n clearInterval(timer);\n }\n }, interval);\n });\n\n if (typeof timeout === \"number\") {\n setTimeout(() => {\n thrown = true;\n onTimeoutError({\n status: 0 as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n }, timeout);\n }\n if (!thrown) {\n await progress(requestTime, totalUploaded, onRequestProgress);\n }\n if (!thrown) {\n onRequestEnd();\n onResponseStart();\n }\n if (!thrown) {\n await progress(responseTime, totalDownloaded, onResponseProgress);\n }\n if (thrown) {\n onAbortError({\n status: adapter.systemErrorStatus,\n extra: adapter.systemErrorExtra,\n });\n } else if (success || (error && data)) {\n onSuccess({\n data,\n error,\n status: status as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n } else {\n onError({\n error,\n status: status as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n }\n if (!thrown) {\n onResponseEnd();\n }\n};\n","import type { ResponseSuccessType, ResponseErrorType, ProgressDataType, AdapterInstance } from \"adapter\";\nimport { getErrorMessage, RequestProcessingError } from \"adapter\";\nimport type { LoggerMethods } from \"managers\";\nimport type { RequestInstance, ProgressEventType } from \"request\";\nimport { getProgressData, scopeKey } from \"request\";\nimport type {\n ExtractResponseType,\n ExtractErrorType,\n ExtractPayloadType,\n ExtractAdapterOptionsType,\n ExtractAdapterStatusType,\n ExtractAdapterExtraType,\n} from \"types\";\n\nexport const getAdapterBindings = async <T extends AdapterInstance>({\n request: baseRequest,\n requestId,\n resolve,\n onStartTime,\n internalErrorMapping,\n}: {\n request: RequestInstance;\n requestId: string;\n resolve: (value: ResponseSuccessType<any, T> | ResponseErrorType<any, T>) => void;\n onStartTime: (timestamp: number) => void;\n internalErrorMapping: (error: ReturnType<typeof getErrorMessage>) => any;\n}) => {\n const { requestManager, loggerManager } = baseRequest.client;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { unstable_payloadMapper } = baseRequest.client.adapter;\n\n const logger = loggerManager.initialize(baseRequest.client, \"Adapter\");\n\n let requestStartTimestamp: null | number = null;\n let responseStartTimestamp: null | number = null;\n let request = baseRequest;\n\n // Progress\n let requestTotal = 1;\n let responseTotal = 1;\n let previousRequestTotal = 0;\n let previousResponseTotal = 0;\n\n // Pre request modifications\n logger.debug({\n title: `Running middleware callbacks`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n\n request = await request.client.unstable_modifyRequest(request);\n\n if (request.auth) {\n request = await request.client.unstable_modifyAuth(request);\n }\n\n if (request.unstable_requestMapper) {\n request = await request.unstable_requestMapper(request, requestId);\n }\n\n // Request Setup\n const { client, abortKey } = request;\n const scopedAbortKey = scopeKey(abortKey, request.scope);\n\n // eslint-disable-next-line prefer-destructuring\n let payload = request.payload;\n\n if (request.unstable_payloadMapper) {\n payload = await request.unstable_payloadMapper<ExtractPayloadType<RequestInstance>>(request.payload);\n } else if (unstable_payloadMapper) {\n payload = await unstable_payloadMapper(payload);\n }\n\n const adapterOptions = request.options as ExtractAdapterOptionsType<T> | undefined;\n const startTime = Date.now();\n onStartTime(startTime);\n\n const getRequestStartTimestamp = () => {\n return requestStartTimestamp;\n };\n\n const getResponseStartTimestamp = () => {\n return responseStartTimestamp;\n };\n\n // Progress\n\n const getTotal = (previousTotal: number, progress?: ProgressDataType) => {\n if (!progress) {return previousTotal;}\n const total = Number(progress.total || 0);\n const loaded = Number(progress.loaded || 0);\n return Math.max(total, loaded, previousTotal);\n };\n\n const handleRequestProgress = (\n startTimestamp: number,\n progressTimestamp: number,\n progressEvent: ProgressEventType,\n ) => {\n const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);\n\n if (previousRequestTotal !== 100) {\n previousRequestTotal = progress.total;\n requestManager.events.emitUploadProgress({ ...progress, requestId, request });\n }\n };\n\n const handleResponseProgress = (\n startTimestamp: number,\n progressTimestamp: number,\n progressEvent: ProgressEventType,\n ) => {\n const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);\n\n if (previousResponseTotal !== 100) {\n previousResponseTotal = progress.total;\n requestManager.events.emitDownloadProgress({ ...progress, requestId, request });\n }\n };\n\n // Pre-request\n\n const onBeforeRequest = () => {\n logger.debug({\n title: `Request about to be sent`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n client.triggerPlugins(\"onRequestTrigger\", { request });\n };\n\n // Request\n\n const onRequestStart = (progress?: ProgressDataType) => {\n logger.info({\n title: `Request start`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n client.triggerPlugins(\"onRequestStart\", { request });\n\n if (progress?.total) {\n requestTotal = getTotal(requestTotal, progress);\n }\n\n const initialPayload = {\n total: requestTotal,\n loaded: progress?.loaded || 0,\n };\n requestStartTimestamp = Date.now();\n handleRequestProgress(requestStartTimestamp, requestStartTimestamp, initialPayload);\n requestManager.events.emitRequestStart({ requestId, request });\n return requestStartTimestamp;\n };\n\n const onRequestProgress = (progress: ProgressDataType) => {\n if (!requestStartTimestamp) {\n requestStartTimestamp = Date.now();\n }\n requestTotal = getTotal(requestTotal, progress);\n\n const progressTimestamp = Date.now();\n\n handleRequestProgress(requestStartTimestamp, progressTimestamp, {\n total: requestTotal,\n loaded: progress.loaded || 0,\n });\n return progressTimestamp;\n };\n\n const onRequestEnd = () => {\n if (!requestStartTimestamp) {\n requestStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n handleRequestProgress(requestStartTimestamp, progressTimestamp, {\n total: requestTotal,\n loaded: requestTotal,\n });\n return progressTimestamp;\n };\n\n // Response\n\n const onResponseStart = (progress?: ProgressDataType) => {\n responseStartTimestamp = Date.now();\n\n responseTotal = getTotal(responseTotal, progress);\n\n const initialPayload = {\n total: responseTotal,\n loaded: progress?.loaded || 0,\n };\n\n handleResponseProgress(responseStartTimestamp, responseStartTimestamp, initialPayload);\n requestManager.events.emitResponseStart({ requestId, request });\n return responseStartTimestamp;\n };\n\n const onResponseProgress = (progress: ProgressDataType) => {\n if (!responseStartTimestamp) {\n responseStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n responseTotal = getTotal(responseTotal, progress);\n\n handleResponseProgress(responseStartTimestamp, progressTimestamp, {\n total: progress.total || responseTotal,\n loaded: progress.loaded || 0,\n });\n return progressTimestamp;\n };\n\n const onResponseEnd = () => {\n if (!responseStartTimestamp) {\n responseStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n handleResponseProgress(responseStartTimestamp, progressTimestamp, {\n total: responseTotal,\n loaded: responseTotal,\n });\n return progressTimestamp;\n };\n\n // Success\n\n const onSuccess = async ({\n data,\n error,\n status,\n extra,\n }: {\n data: any;\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n error?: ExtractErrorType<T>;\n }): Promise<ResponseSuccessType<ExtractResponseType<T>, T>> => {\n let response: ResponseSuccessType<ExtractResponseType<T>, T> = {\n data,\n error: error ?? null,\n success: true,\n status,\n extra,\n requestTimestamp: startTime,\n responseTimestamp: Date.now(),\n };\n response = (await request.client.unstable_modifyResponse?.(response, request)) as typeof data;\n response = (await request.client.unstable_modifySuccessResponse?.(response, request)) as typeof data;\n\n client.triggerPlugins(\"onRequestSuccess\", { response, request });\n client.triggerPlugins(\"onRequestFinished\", { response, request });\n\n resolve(response);\n\n logger.info({\n title: `Response success`,\n type: \"response\",\n extra: {\n request,\n requestId,\n response,\n },\n });\n return response;\n };\n\n // Errors\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n const onError = getAdapterOnError({\n request,\n requestId,\n startTime,\n logger,\n resolve,\n });\n\n const onAbortError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Abort error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = internalErrorMapping(getErrorMessage(\"abort\"));\n return onError({ error, status, extra });\n };\n\n const onTimeoutError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Timeout error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = getErrorMessage(\"timeout\");\n return onError({ error, status, extra });\n };\n\n const onUnexpectedError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Unexpected error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = getErrorMessage();\n return onError({ error, status, extra });\n };\n\n // Abort\n\n const getAbortController = () => {\n return requestManager.getAbortController(scopedAbortKey, requestId);\n };\n\n const createAbortListener = ({\n status,\n extra,\n onAbort = () => {},\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n onAbort?: () => void;\n }) => {\n const controller = getAbortController();\n if (!controller) {\n throw new RequestProcessingError(\"Controller is not found\");\n }\n\n const abort = () => {\n onAbortError({ status, extra });\n onAbort();\n requestManager.events.emitAbort({ requestId, request });\n };\n\n // Instant abort when we stack many requests triggered at once, and we receive aborted controller\n if (controller.signal.aborted) {\n abort();\n }\n\n // Abort during the request\n controller.signal.addEventListener(\"abort\", abort);\n\n return () => controller.signal.removeEventListener(\"abort\", abort);\n };\n\n logger.debug({\n title: `Mounted adapter bindings`,\n type: \"request\",\n extra: {\n request,\n requestId,\n payload,\n adapterOptions,\n },\n });\n\n const queryParams = baseRequest.client.adapter.unstable_queryParamsMapper(request.queryParams);\n const endpoint = baseRequest.client.adapter.unstable_endpointMapper(request.endpoint);\n const headers = baseRequest.client.adapter.unstable_headerMapper(request);\n const { url } = baseRequest.client;\n\n return {\n request,\n requestId,\n url,\n endpoint,\n queryParams,\n payload,\n headers,\n adapter: baseRequest.client.adapter,\n adapterOptions,\n getAbortController,\n getRequestStartTimestamp,\n getResponseStartTimestamp,\n createAbortListener,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onRequestEnd,\n onResponseStart,\n onResponseProgress,\n onResponseEnd,\n onSuccess,\n onAbortError,\n onTimeoutError,\n onUnexpectedError,\n onError,\n };\n};\n\nexport function getAdapterOnError<T extends AdapterInstance>({\n request,\n requestId,\n startTime,\n resolve,\n logger,\n}: {\n request: RequestInstance;\n requestId: string;\n startTime: number;\n logger: LoggerMethods;\n resolve: (value: ResponseSuccessType<any, T> | ResponseErrorType<any, T>) => void;\n}) {\n const { client } = request;\n\n return async ({\n error,\n status,\n extra,\n }: {\n error: any;\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }): Promise<ResponseErrorType<any, T>> => {\n let response: ResponseErrorType<any, T> = {\n data: null,\n status,\n error,\n success: false,\n extra,\n requestTimestamp: startTime,\n responseTimestamp: Date.now(),\n };\n\n response = (await client.unstable_modifyResponse(response, request)) as typeof response;\n response = (await client.unstable_modifyErrorResponse(response, request)) as typeof response;\n\n client.triggerPlugins(\"onRequestError\", { response, request });\n client.triggerPlugins(\"onRequestFinished\", { response, request });\n\n resolve(response);\n\n logger.error({\n title: `Request error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n response,\n },\n });\n\n return response;\n };\n}\n","import type { RequestInstance } from \"request\";\n\nexport const getUniqueRequestId = (request: Pick<RequestInstance, \"queryKey\">) => {\n return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","import Emitter from \"events\";\n\nconst getListenName = (event: string | symbol) => `listen_${String(event)}`;\n\nexport class EventEmitter extends Emitter {\n emitCallbacks: ((event: string, data: any, isTriggeredExternally?: true) => void)[] = [];\n\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(options?: ConstructorParameters<typeof Emitter>[0]) {\n super(options);\n }\n\n emit(type: string, data: any, isTriggeredExternally: boolean) {\n const params: [string, any, true?] = [type, data];\n\n if (isTriggeredExternally) {\n params.push(isTriggeredExternally);\n }\n\n this.emitCallbacks?.forEach((callback) => callback(...params));\n return super.emit(...params);\n }\n\n onEmit = (callback: (event: string, data: any, isTriggeredExternally?: true) => void) => {\n this.emitCallbacks?.push(callback);\n return () => {\n this.emitCallbacks = this.emitCallbacks?.filter((cb) => cb !== callback);\n };\n };\n\n onListener = (event: string, listener: (count: number) => void) => {\n super.on(getListenName(event), listener);\n return () => {\n super.off(getListenName(event), listener);\n };\n };\n\n on = (event: string | symbol, listener: (...args: any[]) => void) => {\n super.on(event, listener);\n super.emit(getListenName(event), super.listeners(event).length);\n return this;\n };\n\n off = (event: string | symbol, listener: (...args: any[]) => void) => {\n super.off(event, listener);\n super.emit(getListenName(event), super.listeners(event).length);\n return this;\n };\n\n addListener = this.on;\n removeListener = this.off;\n}\n","import type { AppManagerOptionsType } from \"managers\";\nimport { appManagerInitialOptions, getAppManagerEvents, hasDocument } from \"managers\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * App manager handles main application states - focus and online. Those two values can answer questions:\n * - Is the tab or current view instance focused and visible for user?\n * - Is our application online or offline?\n * With the app manager it is not a problem to get the valid answer for this question.\n *\n * @caution\n * Make sure to apply valid focus/online handlers for different environments like for example for native mobile applications.\n */\nexport class AppManager {\n emitter = new EventEmitter();\n events = getAppManagerEvents(this.emitter);\n\n isBrowser: boolean;\n isOnline: boolean;\n isFocused: boolean;\n\n private unmountCallbacks: VoidFunction[] = [];\n\n constructor(public options?: AppManagerOptionsType) {\n this.emitter?.setMaxListeners(1000);\n const {\n initiallyFocused = appManagerInitialOptions.initiallyFocused,\n initiallyOnline = appManagerInitialOptions.initiallyOnline,\n } = this.options || appManagerInitialOptions;\n\n this.setInitialFocus(initiallyFocused);\n this.setInitialOnline(initiallyOnline);\n\n this.isBrowser = hasDocument();\n }\n\n /**\n * Subscribes to the environment focus and network changes. Calling it again replaces the previous subscriptions,\n * so the listeners are never registered twice.\n */\n initialize = () => {\n const { focusEvent = appManagerInitialOptions.focusEvent, onlineEvent = appManagerInitialOptions.onlineEvent } =\n this.options || appManagerInitialOptions;\n\n this.unmount();\n\n [focusEvent(this.setFocused), onlineEvent(this.setOnline)].forEach((unmount) => {\n if (typeof unmount === \"function\") {\n this.unmountCallbacks.push(unmount);\n }\n });\n };\n\n /**\n * Removes the environment listeners registered by `initialize()`. Listeners added with `events` are kept.\n */\n unmount = () => {\n const callbacks = this.unmountCallbacks;\n this.unmountCallbacks = [];\n callbacks.forEach((unmount) => unmount());\n };\n\n private setInitialFocus = async (initValue: Exclude<AppManagerOptionsType[\"initiallyFocused\"], undefined>) => {\n if (typeof initValue !== \"function\") {\n this.isFocused = initValue;\n return;\n }\n\n // Synchronous getters apply right away, so there is no moment with a wrong value\n const value = initValue();\n if (typeof value === \"boolean\") {\n this.isFocused = value;\n } else {\n this.isFocused = false;\n this.isFocused = await value;\n }\n };\n\n private setInitialOnline = async (initValue: Exclude<AppManagerOptionsType[\"initiallyOnline\"], undefined>) => {\n if (typeof initValue !== \"function\") {\n this.isOnline = initValue;\n return;\n }\n\n // Synchronous getters apply right away, so there is no moment with a wrong value\n const value = initValue();\n if (typeof value === \"boolean\") {\n this.isOnline = value;\n } else {\n this.isOnline = false;\n this.isOnline = await value;\n }\n };\n\n setFocused = (isFocused: boolean) => {\n this.isFocused = isFocused;\n\n if (isFocused) {\n this.events.emitFocus();\n } else {\n this.events.emitBlur();\n }\n };\n\n setOnline = (isOnline: boolean) => {\n this.isOnline = isOnline;\n\n if (isOnline) {\n this.events.emitOnline();\n } else {\n this.events.emitOffline();\n }\n };\n}\n","export const hasWindow = () => {\n try {\n return Boolean(window && window.addEventListener);\n } catch {\n /* istanbul ignore next */\n return false;\n }\n};\n\nexport const hasDocument = () => {\n try {\n return Boolean(hasWindow() && window.document && window.document.addEventListener);\n } catch {\n /* istanbul ignore next */\n return false;\n }\n};\n\n/**\n * Reads the current network state from the browser. Falls back to `true` when it is unknown - e.g. in Node.js or\n * React Native, where `navigator.onLine` is not available.\n */\nexport const isNavigatorOnline = () => {\n try {\n return typeof navigator.onLine === \"boolean\" ? navigator.onLine : true;\n } catch {\n /* istanbul ignore next */\n return true;\n }\n};\n\nexport const onWindowEvent = <K extends keyof WindowEventMap>(\n key: K,\n listener: (this: Window, ev: WindowEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions | undefined,\n): VoidFunction => {\n /* istanbul ignore next */\n if (hasWindow()) {\n window.addEventListener(key, listener, options);\n return () => window.removeEventListener(key, listener, options);\n }\n /* istanbul ignore next */\n return () => null;\n};\n\nexport const onDocumentEvent = <K extends keyof DocumentEventMap>(\n key: K,\n listener: (this: Document, ev: DocumentEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions | undefined,\n): VoidFunction => {\n /* istanbul ignore next */\n if (hasDocument()) {\n window.document.addEventListener(key, listener, options);\n return () => window.document.removeEventListener(key, listener, options);\n }\n /* istanbul ignore next */\n return () => null;\n};\n","import type EventEmitter from \"events\";\nimport { AppEvents } from \"managers\";\n\n/** Create event emitters and listeners for application-level focus, blur, online, and offline state changes. */\nexport const getAppManagerEvents = (emitter: EventEmitter) => ({\n /** Emit when the application window gains focus */\n emitFocus: (): void => {\n emitter.emit(AppEvents.FOCUS);\n },\n /** Emit when the application window loses focus */\n emitBlur: (): void => {\n emitter.emit(AppEvents.BLUR);\n },\n /** Emit when the application transitions to online state */\n emitOnline: (): void => {\n emitter.emit(AppEvents.ONLINE);\n },\n /** Emit when the application transitions to offline state */\n emitOffline: (): void => {\n emitter.emit(AppEvents.OFFLINE);\n },\n /** Listen for focus events */\n onFocus: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.FOCUS, callback);\n return () => emitter.removeListener(AppEvents.FOCUS, callback);\n },\n /** Listen for blur events */\n onBlur: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.BLUR, callback);\n return () => emitter.removeListener(AppEvents.BLUR, callback);\n },\n /** Listen for online state transitions */\n onOnline: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.ONLINE, callback);\n return () => emitter.removeListener(AppEvents.ONLINE, callback);\n },\n /** Listen for offline state transitions */\n onOffline: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.OFFLINE, callback);\n return () => emitter.removeListener(AppEvents.OFFLINE, callback);\n },\n});\n","import type { AppManagerOptionsType } from \"managers\";\nimport type { RequiredKeys } from \"types\";\n\nimport { onWindowEvent, onDocumentEvent, isNavigatorOnline } from \"./app.manager.utils\";\n\nexport enum AppEvents {\n FOCUS = \"focus\",\n BLUR = \"blur\",\n ONLINE = \"online\",\n OFFLINE = \"offline\",\n}\n\nexport const appManagerInitialOptions: RequiredKeys<AppManagerOptionsType> = {\n initiallyFocused: true,\n initiallyOnline: isNavigatorOnline,\n focusEvent: (setFocused) => {\n const unmountVisibility = onDocumentEvent(\"visibilitychange\", () => setFocused(true));\n const unmountFocus = onWindowEvent(\"focus\", () => setFocused(true));\n const unmountBlur = onWindowEvent(\"blur\", () => setFocused(false));\n\n return () => {\n unmountVisibility();\n unmountFocus();\n unmountBlur();\n };\n },\n onlineEvent: (setOnline) => {\n const unmountOnline = onWindowEvent(\"online\", () => setOnline(true));\n const unmountOffline = onWindowEvent(\"offline\", () => setOnline(false));\n\n return () => {\n unmountOnline();\n unmountOffline();\n };\n },\n};\n","import { getRequestManagerEvents } from \"managers\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * **Request Manager** is used to emit `request lifecycle events` like - request start, request end, upload and download progress.\n * It is also the place of `request aborting` system, here we store all the keys and controllers that are isolated for each client instance.\n */\nexport class RequestManager {\n emitter = new EventEmitter();\n events = getRequestManagerEvents(this.emitter);\n\n constructor() {\n this.emitter?.setMaxListeners(1000);\n }\n\n abortControllers = new Map<string, Map<string, AbortController>>();\n\n addAbortController = (abortKey: string, requestId: string) => {\n let abortGroup = this.abortControllers.get(abortKey);\n if (!abortGroup) {\n const newAbortGroup = new Map();\n abortGroup = newAbortGroup;\n this.abortControllers.set(abortKey, newAbortGroup);\n }\n\n const abortController = abortGroup.get(requestId);\n if (!abortController || abortController.signal.aborted) {\n abortGroup.set(requestId, new AbortController());\n }\n };\n\n getAbortController = (abortKey: string, requestId: string) => {\n return this.abortControllers.get(abortKey)?.get(requestId);\n };\n\n removeAbortController = (abortKey: string, requestId: string) => {\n this.abortControllers.get(abortKey)?.delete(requestId);\n };\n\n // Aborting\n\n useAbortController = (abortKey: string, requestId: string) => {\n const controller = this.abortControllers.get(abortKey)?.get(requestId);\n controller?.abort();\n };\n\n abortByKey = (abortKey: string) => {\n const controllers = this.abortControllers.get(abortKey);\n\n if (controllers) {\n const entries = [...controllers.entries()];\n entries.forEach(([key]) => {\n this.useAbortController(abortKey, key);\n });\n }\n };\n\n abortByRequestId = (abortKey: string, requestId: string) => {\n this.useAbortController(abortKey, requestId);\n };\n\n abortAll = () => {\n const entries = [...this.abortControllers.entries()];\n entries.forEach(([abortKey, value]) => {\n const controllers = [...value.entries()];\n controllers.forEach(([requestId]) => {\n this.useAbortController(abortKey, requestId);\n });\n });\n };\n}\n","// Events\n\nexport const getLoadingKey = (): string => `loading-event-any`;\nexport const getLoadingByQueryKey = (queryKey: string): string => `${queryKey}-loading-event`;\nexport const getLoadingByCacheKey = (cacheKey: string): string => `${cacheKey}-loading-cache-event`;\nexport const getLoadingByIdKey = (id: string): string => `${id}-loading-event-by-id`;\nexport const getRemoveKey = (): string => `remove-event-any`;\nexport const getRemoveByQueryKey = (queryKey: string): string => `${queryKey}-remove-event`;\nexport const getRemoveByIdKey = (id: string): string => `${id}-remove-event-by-id`;\nexport const getAbortKey = () => `request-abort-any`;\nexport const getAbortByAbortKey = (abortKey: string) => `${abortKey}-request-abort`;\nexport const getAbortByIdKey = (id: string) => `${id}-request-abort-by-id`;\nexport const getResponseKey = () => `response-any`;\nexport const getResponseByCacheKey = (cacheKey: string) => `${cacheKey}-response`;\nexport const getResponseByIdKey = (id: string) => `${id}-response-by-id`;\nexport const getRequestStartKey = () => `request-start-any`;\nexport const getRequestStarByQueryKey = (queryKey: string) => `${queryKey}-request-start`;\nexport const getRequestStartByIdKey = (id: string) => `${id}-request-start-by-id`;\nexport const getResponseStartKey = () => `response-start-any`;\nexport const getResponseStartByQueryKey = (queryKey: string) => `${queryKey}-response-start`;\nexport const getResponseStartByIdKey = (id: string) => `${id}-response-start-by-id`;\nexport const getUploadProgressKey = () => `request-progress-any`;\nexport const getUploadProgressByQueryKey = (queryKey: string) => `${queryKey}-request-progress`;\nexport const getUploadProgressByIdKey = (id: string) => `${id}-request-progress-by-id`;\nexport const getDownloadProgressKey = () => `response-progress-any`;\nexport const getDownloadProgressByQueryKey = (queryKey: string) => `${queryKey}-response-progress`;\nexport const getDownloadProgressByIdKey = (id: string) => `${id}-response-progress-by-id`;\nexport const getRequestDeduplicatedKey = () => `request-deduplicated-any`;\nexport const getRequestDeduplicatedByQueryKey = (queryKey: string) => `${queryKey}-query-request-deduplicated`;\nexport const getRequestDeduplicatedByCacheKey = (cacheKey: string) => `${cacheKey}-cache-request-deduplicated`;\nexport const getRequestDeduplicatedByIdKey = (id: string) => `${id}-request-deduplicated-by-id`;\n","import type { AdapterInstance } from \"adapter\";\nimport type { Client } from \"client\";\n/* eslint-disable max-params */\nimport type EventEmitter from \"events\";\nimport type {\n RequestEventType,\n RequestLoadingEventType,\n RequestProgressEventType,\n RequestResponseEventType,\n RequestRemovedEventType,\n RequestDeduplicatedEventType,\n} from \"managers\";\nimport {\n getRequestStarByQueryKey,\n getResponseStartByQueryKey,\n getDownloadProgressByQueryKey,\n getUploadProgressByQueryKey,\n getResponseByIdKey,\n getAbortByAbortKey,\n getAbortByIdKey,\n getResponseByCacheKey,\n getUploadProgressByIdKey,\n getDownloadProgressByIdKey,\n getResponseStartByIdKey,\n getRequestStartByIdKey,\n getLoadingByQueryKey,\n getLoadingByIdKey,\n getRemoveByQueryKey,\n getRemoveByIdKey,\n getLoadingKey,\n getRequestStartKey,\n getUploadProgressKey,\n getDownloadProgressKey,\n getResponseKey,\n getAbortKey,\n getRemoveKey,\n getResponseStartKey,\n getLoadingByCacheKey,\n getRequestDeduplicatedKey,\n getRequestDeduplicatedByIdKey,\n getRequestDeduplicatedByCacheKey,\n getRequestDeduplicatedByQueryKey,\n} from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtendRequest } from \"types\";\n\n/** Create event emitters and listeners for the request lifecycle: loading, progress, response, abort, deduplication, and removal. */\nexport const getRequestManagerEvents = (emitter: EventEmitter) => ({\n /**\n * Emitters\n */\n\n /** Emit when a request is deduplicated (skipped because an identical one is in-flight) */\n emitDeduplicated: (data: RequestDeduplicatedEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRequestDeduplicatedKey(), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit loading state changes for a request */\n emitLoading: (data: RequestLoadingEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getLoadingKey(), data, isTriggeredExternally);\n emitter.emit(getLoadingByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getLoadingByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n emitter.emit(getLoadingByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request starts being sent */\n emitRequestStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRequestStartKey(), data, isTriggeredExternally);\n emitter.emit(getRequestStartByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRequestStarByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n /** Emit when the response starts being received */\n emitResponseStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getResponseStartKey(), data, isTriggeredExternally);\n emitter.emit(getResponseStartByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getResponseStartByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit upload progress updates */\n emitUploadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getUploadProgressKey(), data, isTriggeredExternally);\n emitter.emit(getUploadProgressByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getUploadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n /** Emit download progress updates */\n emitDownloadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getDownloadProgressKey(), data, isTriggeredExternally);\n emitter.emit(getDownloadProgressByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getDownloadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit when a response is received */\n emitResponse: <Adapter extends AdapterInstance>(\n data: RequestResponseEventType<ExtendRequest<RequestInstance, { client: Client<any, Adapter> }>>,\n isTriggeredExternally = false,\n ): void => {\n emitter.emit(getResponseKey(), data, isTriggeredExternally);\n emitter.emit(getResponseByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getResponseByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request is aborted */\n emitAbort: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getAbortKey(), data, isTriggeredExternally);\n emitter.emit(getAbortByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getAbortByAbortKey(data.request.abortKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request is removed from the dispatcher queue */\n emitRemove: (data: RequestRemovedEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRemoveKey(), data, isTriggeredExternally);\n emitter.emit(getRemoveByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRemoveByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /**\n * Listeners\n */\n\n /** Listen for deduplicated request events */\n onDeduplicated: <T extends RequestInstance>(\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedKey(), callback);\n return () => emitter.removeListener(getRequestDeduplicatedKey(), callback);\n },\n onDeduplicatedByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByQueryKey(queryKey), callback);\n },\n onDeduplicatedByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByCacheKey(cacheKey), callback);\n },\n onDeduplicatedById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByIdKey(requestId), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByIdKey(requestId), callback);\n },\n\n // Loading\n onLoading: <T extends RequestInstance>(callback: (data: RequestLoadingEventType<T>) => void): VoidFunction => {\n emitter.on(getLoadingKey(), callback);\n return () => emitter.removeListener(getLoadingKey(), callback);\n },\n onLoadingByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getLoadingByQueryKey(queryKey), callback);\n },\n onLoadingByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getLoadingByCacheKey(cacheKey), callback);\n },\n onLoadingById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByIdKey(requestId), callback);\n return () => emitter.removeListener(getLoadingByIdKey(requestId), callback);\n },\n\n // Request Start\n onRequestStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void): VoidFunction => {\n emitter.on(getRequestStartKey(), callback);\n return () => emitter.removeListener(getRequestStartKey(), callback);\n },\n onRequestStartByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestStarByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRequestStarByQueryKey(queryKey), callback);\n },\n onRequestStartById: <T extends RequestInstance>(\n requestId: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestStartByIdKey(requestId), callback);\n return () => emitter.removeListener(getRequestStartByIdKey(requestId), callback);\n },\n\n // Response Start\n onResponseStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void): VoidFunction => {\n emitter.on(getResponseStartKey(), callback);\n return () => emitter.removeListener(getResponseStartKey(), callback);\n },\n onResponseStartByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseStartByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getResponseStartByQueryKey(queryKey), callback);\n },\n onResponseStartById: <T extends RequestInstance>(\n requestId: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseStartByIdKey(requestId), callback);\n return () => emitter.removeListener(getResponseStartByIdKey(requestId), callback);\n },\n\n // Progress\n onUploadProgress: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressKey(), callback);\n return () => emitter.removeListener(getUploadProgressKey(), callback);\n },\n onUploadProgressByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getUploadProgressByQueryKey(queryKey), callback);\n },\n onUploadProgressById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressByIdKey(requestId), callback);\n return () => emitter.removeListener(getUploadProgressByIdKey(requestId), callback);\n },\n\n onDownloadProgress: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressKey(), callback);\n return () => emitter.removeListener(getDownloadProgressKey(), callback);\n },\n onDownloadProgressByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getDownloadProgressByQueryKey(queryKey), callback);\n },\n onDownloadProgressById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressByIdKey(requestId), callback);\n return () => emitter.removeListener(getDownloadProgressByIdKey(requestId), callback);\n },\n\n // Response\n onResponse: <T extends RequestInstance>(callback: (data: RequestResponseEventType<T>) => void): VoidFunction => {\n emitter.on(getResponseKey(), callback);\n return () => emitter.removeListener(getResponseKey(), callback);\n },\n onResponseByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestResponseEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getResponseByCacheKey(cacheKey), callback);\n },\n onResponseById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestResponseEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseByIdKey(requestId), callback);\n return () => emitter.removeListener(getResponseByIdKey(requestId), callback);\n },\n\n // Abort\n onAbort: <T extends RequestInstance = RequestInstance>(\n callback: (request: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortKey(), callback);\n return () => emitter.removeListener(getAbortKey(), callback);\n },\n onAbortByKey: <T extends RequestInstance = RequestInstance>(\n abortKey: string,\n callback: (request: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortByAbortKey(abortKey), callback);\n return () => emitter.removeListener(getAbortByAbortKey(abortKey), callback);\n },\n onAbortById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortByIdKey(requestId), callback);\n return () => emitter.removeListener(getAbortByIdKey(requestId), callback);\n },\n\n // Remove\n onRemove: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveKey(), callback);\n return () => emitter.removeListener(getRemoveKey(), callback);\n },\n onRemoveByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRemoveByQueryKey(queryKey), callback);\n },\n onRemoveById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveByIdKey(requestId), callback);\n return () => emitter.removeListener(getRemoveByIdKey(requestId), callback);\n },\n});\n","import type { ClientInstance } from \"client\";\nimport EventEmitter from \"events\";\nimport type { LogLevel, LoggerOptionsType, LoggerType, LoggerMethods } from \"managers\";\nimport { logger, logLevelOrder } from \"managers\";\n\n/**\n * This class is used across the Hyper Fetch library to provide unified logging system with necessary setup per each client.\n * We can set up the logging level based on available values. This manager enable to initialize the logging instance per individual module\n * like Client, Request etc. Which can give you better feedback on the logging itself.\n */\nexport class LoggerManager {\n logger: LoggerType;\n level: LogLevel;\n modules: string[] | undefined;\n\n public emitter = new EventEmitter();\n\n private client: Pick<ClientInstance, \"debug\">;\n\n constructor(private options?: LoggerOptionsType) {\n this.emitter?.setMaxListeners(1000);\n this.logger = this.options?.logger || logger;\n this.level = this.options?.level || \"warning\";\n this.modules = this.options?.modules;\n }\n\n setSeverity = (level: LogLevel) => {\n this.level = level;\n };\n\n setModules = (modules: string[] | undefined) => {\n this.modules = modules;\n };\n\n initialize = (client: Pick<ClientInstance, \"debug\">, module: string): LoggerMethods => {\n this.client = client;\n\n return {\n error: (data) => this.log({ ...data, level: \"error\", module }),\n warning: (data) => this.log({ ...data, level: \"warning\", module }),\n info: (data) => this.log({ ...data, level: \"info\", module }),\n debug: (data) => this.log({ ...data, level: \"debug\", module }),\n };\n };\n\n private log: LoggerType = (data) => {\n if (!this.client.debug) {\n return;\n }\n if (logLevelOrder.indexOf(this.level) <= logLevelOrder.indexOf(data.level)) {\n return;\n }\n if (this.modules && !this.modules.includes(data.module)) {\n return;\n }\n this.logger(data);\n };\n}\n","/* eslint-disable no-console */\nimport type { LoggerType } from \"managers\";\nimport { loggerColors, loggerStyles } from \"managers\";\n\nexport const getTime = () => {\n const d = new Date();\n return `${d.toLocaleTimeString()}`;\n};\n\nconst getModuleName = (data: Parameters<LoggerType>[0]) => {\n if (data.type === \"request\" || data.type === \"response\") {\n return `${data.extra.request.endpoint}`;\n }\n return `[${data.module}]`;\n};\n\n// Logger\nexport const logger: LoggerType = (log) => {\n const styles = loggerStyles[log.level];\n const color = loggerColors[log.level];\n const message = `%c[${getTime()}]%c${log.title}%c${getModuleName(log)}`;\n\n const style1 = `${styles}${color}font-weight:600;border-radius: 4px 0 0 4px;`;\n const style2 = `${styles}${color}font-weight:600;`;\n const style3 = `${styles}font-weight:normal;border-radius: 0 4px 4px 0;`;\n\n if (log.extra ? Object.keys(log.extra)?.length : false) {\n console.groupCollapsed(message, style1, style2, style3);\n console.log(log.extra);\n console.groupEnd();\n } else {\n console.log(message, styles);\n }\n};\n","import type { LogLevel } from \"./logger.manager.types\";\n\nexport const logLevelOrder: LogLevel[] = [\"error\", \"warning\", \"info\", \"debug\"];\n\nconst defaultStyles = \"padding:2px 5px;\";\n\nexport const loggerStyles: Record<LogLevel, string> = {\n error: `${defaultStyles};background:#db252520;`,\n warning: `${defaultStyles};background:#e1941e20;`,\n info: `${defaultStyles};background:#1e74e120;`,\n debug: `${defaultStyles};background:#00000020;`,\n};\n\nexport const loggerColors: Record<LogLevel, string> = {\n error: \"color:#ff3737;\",\n warning: \"color:#ffc107;\",\n info: \"color:#34a8ff;\",\n debug: \"color:#cccccc;\",\n};\n","/* eslint-disable max-classes-per-file */\n// Utils\nimport { hasWindow } from \"managers\";\nimport type { RequestInstance } from \"request\";\n\nexport class TimeoutError extends Error {\n constructor() {\n super(\"Request timeout\");\n this.name = \"TimeoutError\";\n }\n}\n\nexport class AbortError extends Error {\n constructor() {\n super(\"Request aborted\");\n this.name = \"AbortError\";\n }\n}\n\nexport class DeletedError extends Error {\n constructor() {\n super(\"Request deleted\");\n this.name = \"DeletedError\";\n }\n}\n\nexport class RequestProcessingError extends Error {\n description?: string = undefined;\n\n constructor(description?: string) {\n super(\"Request processing error\");\n this.description = description;\n this.name = \"RequestProcessingError\";\n }\n}\n\nexport class UnexpectedError extends Error {\n description?: string = undefined;\n\n constructor(description?: string) {\n super(\"Unexpected error\");\n this.description = description;\n this.name = \"UnexpectedError\";\n }\n}\n\nexport const getErrorMessage = (errorCase?: \"timeout\" | \"abort\" | \"deleted\" | \"processing\" | \"unexpected\") => {\n if (errorCase === \"timeout\") {\n return new TimeoutError();\n }\n if (errorCase === \"abort\") {\n return new AbortError();\n }\n if (errorCase === \"deleted\") {\n return new DeletedError();\n }\n if (errorCase === \"processing\") {\n return new RequestProcessingError();\n }\n return new UnexpectedError();\n};\n\n// Mappers\n\nexport const stringifyValue = (response: string | unknown): string => {\n try {\n return JSON.stringify(response as string);\n } catch {\n return \"\";\n }\n};\n\nexport const getAdapterHeaders = (request: RequestInstance) => {\n const isFormData = hasWindow() && request.payload instanceof FormData;\n const isObject = typeof request.payload === \"object\" && request.payload !== null;\n const headers: HeadersInit = {};\n\n if (!isFormData && isObject) {headers[\"Content-Type\"] = \"application/json\";}\n\n Object.assign(headers, request.headers);\n return headers as HeadersInit;\n};\n\nexport const getAdapterPayload = (data: unknown): string | FormData => {\n const isFormData = hasWindow() && data instanceof FormData;\n if (isFormData) {return data;}\n\n return stringifyValue(data);\n};\n","import type { Client, ClientInstance } from \"client\";\nimport type { LoggerMethods } from \"managers\";\nimport { mocker } from \"mocker\";\nimport type { RequestInstance, RequestOptionsType } from \"request\";\n/* eslint-disable class-methods-use-this */\nimport type { EmptyTypes, ExtendRequest } from \"types\";\n\nimport { getAdapterOnError, getAdapterBindings } from \"./adapter.bindings\";\nimport type {\n EndpointMapper,\n AdapterFetcherType,\n AdapterPayloadMappingType,\n HeaderMappingType,\n QueryParamsMapper,\n QueryParamsType,\n RequestResponseType,\n ResponseType,\n} from \"./adapter.types\";\nimport type { getErrorMessage } from \"./adapter.utils\";\nimport { getAdapterHeaders, getAdapterPayload, RequestProcessingError } from \"./adapter.utils\";\n\nexport type DefaultMapperType = <V, C = undefined>(value: V, config?: C) => V;\nexport const defaultMapper: DefaultMapperType = (value) => value;\n\n/**\n * Base adapter class responsible for executing HTTP requests. Adapters handle endpoint resolution,\n * header/payload/query-params mapping, and the actual fetch call. Extend or configure this class\n * to integrate custom transport layers (e.g., axios, graphql, firebase).\n */\nexport class Adapter<\n AdapterOptions,\n MethodType extends string,\n StatusType extends number | string,\n Extra extends Record<string, any>,\n QueryParams = QueryParamsType | string | EmptyTypes,\n DefaultQueryParams = undefined,\n EndpointType = string,\n EndpointMapperType extends EndpointMapper<EndpointType> | DefaultMapperType = DefaultMapperType,\n QueryParamsMapperType extends QueryParamsMapper<QueryParams> | DefaultMapperType = DefaultMapperType,\n HeaderMapperType extends HeaderMappingType | DefaultMapperType = DefaultMapperType,\n PayloadMapperType extends AdapterPayloadMappingType | DefaultMapperType = DefaultMapperType,\n RequestOptions extends Record<string, any> = {},\n> {\n /** Fetching function */\n public unstable_fetcher: AdapterFetcherType<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n\n /**\n * ********************\n * Defaults\n * ********************\n */\n\n public name: string;\n public defaultMethod: MethodType;\n public defaultExtra: Extra;\n public systemErrorStatus: StatusType;\n public systemErrorExtra: Extra;\n public defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType> = undefined;\n public logger: LoggerMethods;\n public initialized = false;\n public client: ClientInstance;\n\n public unstable_onInitializeCallback?: (options: { client: ClientInstance }) => void = undefined;\n\n public unstable_queryParamsMapperConfig: Parameters<QueryParamsMapperType>[1];\n public unstable_headerMapperConfig: Parameters<HeaderMapperType>[1];\n public unstable_payloadMapperConfig: Parameters<PayloadMapperType>[1];\n public unstable_endpointMapperConfig: Parameters<EndpointMapperType>[1];\n\n /**\n * Type-only carrier of the additional `createRequest` fields declared by this adapter.\n * It has no runtime value - adapters read those fields from `request.requestOptions`.\n */\n public unstable_requestOptionsType?: RequestOptions = undefined;\n\n constructor(\n public options: {\n name: string;\n defaultMethod: MethodType;\n defaultExtra: Extra;\n systemErrorStatus: StatusType;\n systemErrorExtra: Extra;\n defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType>;\n },\n ) {\n this.name = options.name;\n this.defaultMethod = options.defaultMethod;\n this.defaultExtra = options.defaultExtra;\n this.systemErrorStatus = options.systemErrorStatus;\n this.systemErrorExtra = options.systemErrorExtra;\n this.defaultRequestOptions = options.defaultRequestOptions;\n }\n\n /** Initialize the adapter with a client reference and set up logging. Called automatically when the client is created. */\n initialize = (client: ClientInstance) => {\n this.logger = client.loggerManager.initialize(client, \"Adapter\");\n this.initialized = true;\n this.client = client;\n\n this.unstable_onInitializeCallback?.({ client });\n return this;\n };\n\n /** Register a callback invoked once the adapter is initialized with a client. */\n onInitialize = (callback: (options: { client: ClientInstance }) => void) => {\n this.unstable_onInitializeCallback = callback;\n return this;\n };\n\n /**\n * ********************\n * Options Setters\n * ********************\n */\n\n public unstable_internalErrorMapping: (error: ReturnType<typeof getErrorMessage>) => any = (error) => error;\n /** Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats. */\n public unstable_headerMapper: HeaderMapperType = getAdapterHeaders as HeaderMapperType;\n /** Method to get request data and transform them to the required format. It handles FormData and JSON by default. */\n public unstable_payloadMapper: PayloadMapperType = getAdapterPayload as PayloadMapperType;\n /** Method to get the endpoint for the adapter request. */\n public unstable_endpointMapper: EndpointMapperType = defaultMapper as EndpointMapperType;\n /** Method to get request data and transform them to the required format. */\n public unstable_queryParamsMapper: QueryParamsMapperType = defaultMapper as QueryParamsMapperType;\n /** Get default adapter options for the request. */\n public unstable_getAdapterDefaults?: (\n request: ExtendRequest<\n RequestInstance,\n {\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n ) => AdapterOptions = undefined;\n /** Get default request options for the request. */\n public unstable_getRequestDefaults?: (\n options: RequestOptionsType<EndpointType, AdapterOptions, MethodType>,\n ) => Partial<RequestOptionsType<EndpointType, AdapterOptions, MethodType>> = undefined;\n /**\n * Get formatted endpoint name of the request.\n * Helpful in displaying long endpoints like in case of graphql schemas etc.\n */\n public unstable_devtoolsEndpointGetter: (endpoint: string, requestOptions?: Record<string, any>) => string = (\n endpoint,\n ) => endpoint;\n\n /**\n * ********************\n * Methods\n * ********************\n */\n\n /** Set the default HTTP method used when a request does not specify one. */\n setDefaultMethod = (method: MethodType) => {\n this.defaultMethod = method;\n return this;\n };\n\n /** Set the default extra metadata attached to every request response (e.g., headers, status). */\n setDefaultExtra = (extra: Extra) => {\n this.defaultExtra = extra;\n return this;\n };\n\n /** Set a function that formats the endpoint string for display in devtools. */\n setDevtoolsEndpointGetter = (callback: (endpoint: string, requestOptions?: Record<string, any>) => string) => {\n this.unstable_devtoolsEndpointGetter = callback;\n return this;\n };\n\n /**\n * This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.\n */\n setRequestDefaults = (callback: typeof this.unstable_getRequestDefaults): this => {\n this.unstable_getRequestDefaults = callback;\n return this;\n };\n\n /**\n * Set the adapter default options added to every sent request\n */\n setAdapterDefaults = (\n callback: (\n request: ExtendRequest<\n RequestInstance,\n {\n // No need for global error type, because we haven't sent the request yet\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n ) => AdapterOptions,\n ): this => {\n this.unstable_getAdapterDefaults = callback;\n return this;\n };\n\n /** Set a custom mapping for internal adapter errors before they are returned in the response. */\n setInternalErrorMapping = (callback: (error: ReturnType<typeof getErrorMessage>) => any) => {\n this.unstable_internalErrorMapping = callback;\n return this;\n };\n\n /**\n * Set the custom header mapping function\n */\n setHeaderMapper = <NewMapper extends HeaderMappingType>(headerMapper: NewMapper) => {\n this.unstable_headerMapper = ((req: Parameters<NewMapper>[0]) =>\n headerMapper(req, this.unstable_headerMapperConfig as Parameters<NewMapper>[1])) as unknown as HeaderMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n NewMapper,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /**\n * Set the request payload mapping function which gets triggered before request is send\n */\n setPayloadMapper = <NewMapper extends AdapterPayloadMappingType>(payloadMapper: NewMapper) => {\n this.unstable_payloadMapper = ((req: Parameters<NewMapper>[0]) =>\n payloadMapper(\n req,\n this.unstable_payloadMapperConfig as Parameters<NewMapper>[1],\n )) as unknown as PayloadMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n NewMapper,\n RequestOptions\n >;\n };\n\n /**\n * Set the endpoint mapping function which transforms the endpoint string before the request is sent\n */\n setEndpointMapper = <NewEndpointMapper extends EndpointMapper<EndpointType>>(endpointMapper: NewEndpointMapper) => {\n this.unstable_endpointMapper = ((endpoint: Parameters<NewEndpointMapper>[0]) =>\n endpointMapper(\n endpoint,\n this.unstable_endpointMapperConfig as Parameters<NewEndpointMapper>[1],\n )) as unknown as EndpointMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n NewEndpointMapper,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /**\n * Set the query params mapping function which get triggered before request get sent\n */\n setQueryParamsMapper = <NewQueryParamsMapper extends QueryParamsMapper<QueryParams>>(\n queryParamsMapper: NewQueryParamsMapper,\n ) => {\n this.unstable_queryParamsMapper = ((queryParams: Parameters<NewQueryParamsMapper>[0]) =>\n queryParamsMapper(\n queryParams,\n this.unstable_queryParamsMapperConfig as Parameters<NewQueryParamsMapper>[1],\n )) as unknown as QueryParamsMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n NewQueryParamsMapper,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /** Set the configuration object passed as the second argument to the query params mapper. */\n setQueryParamsMapperConfig = <NewQueryParamsMapperConfig extends Parameters<QueryParamsMapperType>[1]>(\n config: NewQueryParamsMapperConfig,\n ) => {\n this.unstable_queryParamsMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the header mapper. */\n setHeaderMapperConfig = <NewHeaderMapperConfig extends Parameters<HeaderMapperType>[1]>(\n config: NewHeaderMapperConfig,\n ) => {\n this.unstable_headerMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the endpoint mapper. */\n setEndpointMapperConfig = <NewEndpointMapperConfig extends Parameters<EndpointMapperType>[1]>(\n config: NewEndpointMapperConfig,\n ) => {\n this.unstable_endpointMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the payload mapper. */\n setPayloadMapperConfig = <NewPayloadMapperConfig extends Parameters<PayloadMapperType>[1]>(\n config: NewPayloadMapperConfig,\n ) => {\n this.unstable_payloadMapperConfig = config;\n return this;\n };\n\n /**\n * ********************\n * Fetching\n * ********************\n */\n\n /** Set the fetcher function that performs the actual network request. Must be called before any request can be executed. */\n public setFetcher(\n fetcher: AdapterFetcherType<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >,\n ) {\n this.unstable_fetcher = fetcher.bind(this);\n return this;\n }\n\n /** Execute a request through the adapter pipeline: maps endpoint/headers/payload, runs plugins, then calls the fetcher. */\n public async fetch(\n request: ExtendRequest<\n RequestInstance,\n {\n // No need for global error type, it doesn't matter to the fetcher itself\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n requestId: string,\n ): Promise<RequestResponseType<RequestInstance>> {\n let startTime: number | undefined;\n\n const execute = async (resolve: (value: ResponseType<any, any, any>) => void) => {\n try {\n if (!this.initialized) {\n throw new RequestProcessingError(`Adapter ${this.options.name} is not initialized`);\n }\n\n if (!this.unstable_fetcher) {\n throw new RequestProcessingError(`Fetcher for ${this.options.name} adapter is not set`);\n }\n\n this.client.triggerPlugins(\"onAdapterFetch\", {\n adapter: this,\n request,\n requestId,\n });\n\n const bindings = await getAdapterBindings<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >({\n request,\n requestId,\n resolve,\n internalErrorMapping: this.unstable_internalErrorMapping,\n onStartTime: (time) => {\n startTime = time;\n },\n });\n\n if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) {\n return await mocker<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >(bindings);\n }\n\n return this.unstable_fetcher(bindings);\n } catch (error) {\n const onError = getAdapterOnError({\n request,\n requestId,\n startTime: startTime || Date.now(),\n logger: this.logger,\n resolve,\n });\n\n return onError({\n error: this.unstable_internalErrorMapping(error as ReturnType<typeof getErrorMessage>),\n status: this.options.systemErrorStatus,\n extra: this.options.systemErrorExtra,\n });\n }\n };\n\n const promise = new Promise((resolve) => {\n execute(resolve);\n });\n\n return promise as Promise<RequestResponseType<RequestInstance>>;\n }\n}\n","export enum HttpMethods {\n GET = \"GET\",\n POST = \"POST\",\n PUT = \"PUT\",\n PATCH = \"PATCH\",\n DELETE = \"DELETE\",\n /** Safe, idempotent read with a request body (IETF draft-ietf-httpbis-safe-method-w-body). */\n QUERY = \"QUERY\",\n}\n\n/** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */\nexport const SAFE_HTTP_METHODS: string[] = [HttpMethods.GET, HttpMethods.QUERY];\n","import { getErrorMessage } from \"adapter\";\nimport type { AdapterInstance, ProgressType, RequestResponseType, ResponseType } from \"adapter\";\nimport { SAFE_HTTP_METHODS } from \"constants/http.constants\";\nimport type { Dispatcher } from \"dispatcher\";\nimport type { ExtractAdapterType, ExtractErrorType } from \"types\";\n\nimport type {\n OptimisticCallbackResult,\n ProgressEventType,\n RequestInstance,\n RequestJSON,\n RequestSendOptionsType,\n} from \"./request.types\";\n\nexport const scopeKey = (key: string, scope: string | null): string => {\n return scope ? `${scope}__${key}` : key;\n};\n\nexport const stringifyKey = (value: unknown): string => {\n try {\n if (typeof value === \"string\") {return value;}\n if (value === undefined || value === null) {return \"\";}\n const data = JSON.stringify(value);\n if (typeof data !== \"string\") {throw new TypeError();}\n return data;\n } catch {\n return \"\";\n }\n};\n\nexport const getProgressValue = ({ loaded, total }: ProgressEventType): number => {\n if (!loaded || !total) {return 0;}\n return Number(((loaded * 100) / total).toFixed(0));\n};\n\nexport const getRequestEta = (\n startDate: Date,\n progressDate: Date,\n { total, loaded }: ProgressEventType,\n): { sizeLeft: number; timeLeft: number | null } => {\n const timeElapsed = +progressDate - +startDate || 1;\n const uploadSpeed = loaded / timeElapsed;\n const totalValue = Math.max(total, loaded);\n const sizeLeft = totalValue - loaded;\n const estimatedTimeValue = uploadSpeed ? sizeLeft / uploadSpeed : null;\n const timeLeft = totalValue === loaded ? 0 : estimatedTimeValue;\n\n return { timeLeft, sizeLeft };\n};\n\nexport const getProgressData = (\n requestStartTime: Date,\n progressDate: Date,\n progressEvent: ProgressEventType,\n): ProgressType => {\n const { total, loaded } = progressEvent;\n if (Number.isNaN(total) || Number.isNaN(loaded)) {\n return {\n progress: 0,\n timeLeft: 0,\n sizeLeft: 0,\n total: 0,\n loaded: 0,\n startTimestamp: +requestStartTime,\n };\n }\n\n const { timeLeft, sizeLeft } = getRequestEta(requestStartTime, progressDate, progressEvent);\n\n return {\n progress: getProgressValue(progressEvent),\n timeLeft,\n sizeLeft,\n total,\n loaded,\n startTimestamp: +requestStartTime,\n };\n};\n\n// Keys\nexport const getSimpleKey = (request: RequestInstance | RequestJSON<RequestInstance>): string => {\n return `${request.method}_${request.requestOptions.endpoint}_${request.cancelable}`;\n};\n\n/**\n * Cache instance for individual request that collects individual requests responses from\n * the same endpoint (they may differ base on the custom key, endpoint params etc)\n * @param request\n * @param useInitialValues\n * @returns\n */\nexport const getRequestKey = (\n request: RequestInstance | RequestJSON<RequestInstance>,\n useInitialValues?: boolean,\n): string => {\n /**\n * Below stringified values allow to match the response by method, endpoint and query params.\n * That's because we have shared endpoint, but data with queryParams '?user=1' will not match regular request without queries.\n * We want both results to be cached in separate places to not override each other.\n *\n * Values to be stringified:\n *\n * endpoint: string;\n * queryParams: string;\n * params: string;\n */\n const methodKey = stringifyKey(request.method);\n const endpointKey = useInitialValues ? request.requestOptions.endpoint : stringifyKey(request.endpoint);\n const queryParamsKey = useInitialValues ? \"\" : stringifyKey(request.queryParams);\n\n return `${methodKey}_${endpointKey}_${queryParamsKey}`;\n};\n\nexport const getRequestDispatcher = <Request extends RequestInstance>(\n request: Request,\n dispatcherType: \"auto\" | \"fetch\" | \"submit\" = \"auto\",\n): [Dispatcher<ExtractAdapterType<Request>>, isFetchDispatcher: boolean] => {\n const { fetchDispatcher, submitDispatcher } = request.client;\n const isSafeRead = SAFE_HTTP_METHODS.includes(request.method as string);\n const isFetchDispatcher = (dispatcherType === \"auto\" && isSafeRead) || dispatcherType === \"fetch\";\n const dispatcher = isFetchDispatcher ? fetchDispatcher : submitDispatcher;\n\n return [dispatcher, isFetchDispatcher];\n};\n\nexport const mapResponseForSend = async <Request extends RequestInstance>(\n request: Request,\n response: ResponseType<any, any, AdapterInstance>,\n): Promise<RequestResponseType<Request>> => {\n const mapping = request.unstable_responseMapper?.(response as ResponseType<any, any, ExtractAdapterType<Request>>);\n\n if (mapping instanceof Promise) {\n return (await mapping) as RequestResponseType<Request>;\n }\n\n return (mapping || response) as RequestResponseType<Request>;\n};\n\nexport const sendRequest = async <Request extends RequestInstance>(\n request: Request,\n options?: RequestSendOptionsType<Request>,\n): Promise<RequestResponseType<Request>> => {\n const { client } = request;\n const { requestManager } = client;\n const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);\n\n let mutationContext: OptimisticCallbackResult<any> | undefined;\n\n if (request.optimistic) {\n try {\n mutationContext = await request.optimistic({\n request,\n client: request.client,\n payload: request.payload,\n });\n } catch (error) {\n return {\n data: null,\n error: new Error(\n `Optimistic callback failed: ${error instanceof Error ? error.message : error}`,\n ) as unknown as ExtractErrorType<Request>,\n status: null,\n success: false,\n extra: client.adapter.defaultExtra,\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n };\n }\n }\n\n return new Promise<RequestResponseType<Request>>((resolve) => {\n let isResolved = false;\n const requestId = dispatcher.add(request);\n const { $hooks } = request;\n const beforeSentData = { requestId, request, mutationContext };\n options?.onBeforeSent?.(beforeSentData);\n $hooks.__emit(\"onBeforeSent\", beforeSentData);\n\n const unmountRequestStart = requestManager.events.onRequestStartById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n options?.onRequestStart?.(enriched);\n $hooks.__emit(\"onRequestStart\", enriched);\n });\n\n const unmountResponseStart = requestManager.events.onResponseStartById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n options?.onResponseStart?.(enriched);\n $hooks.__emit(\"onResponseStart\", enriched);\n });\n\n const unmountUpload = requestManager.events.onUploadProgressById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n options?.onUploadProgress?.(enriched);\n $hooks.__emit(\"onUploadProgress\", enriched);\n });\n\n const unmountDownload = requestManager.events.onDownloadProgressById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n options?.onDownloadProgress?.(enriched);\n $hooks.__emit(\"onDownloadProgress\", enriched);\n });\n\n // When resolved\n const unmountResponse = requestManager.events.onResponseById<Request>(requestId, (values) => {\n const { details, response } = values;\n isResolved = true;\n const enrichedValues = { ...values, mutationContext };\n\n const mapping = request.unstable_responseMapper?.(\n response as ResponseType<any, any, ExtractAdapterType<Request>>,\n );\n\n const isOfflineStatus = request.offline && details.isOffline;\n const { willRetry } = details;\n\n const handleResponse = (success: boolean, data: ResponseType<any, any, ExtractAdapterType<Request>>) => {\n // When going offline we can't handle the request as it will be postponed to later resolve\n if (!success && isOfflineStatus) {return;}\n\n // When request is in retry mode we need to listen for retries end\n if (!success && willRetry) {return;}\n\n options?.onResponse?.(enrichedValues);\n $hooks.__emit(\"onResponse\", enrichedValues);\n resolve(data);\n\n // Unmount Listeners\n // eslint-disable-next-line @typescript-eslint/no-use-before-define, @typescript-eslint/no-use-before-define\n umountAll();\n };\n\n // Create async await ONLY when we make a promise mapper\n if (mapping instanceof Promise) {\n (async () => {\n const responseData = await mapping;\n\n const { success } = responseData;\n handleResponse(success, responseData as ResponseType<any, any, ExtractAdapterType<Request>>);\n })();\n }\n // For sync mapping operations we should not use async actions\n else {\n const data = mapping || response;\n const { success } = data;\n handleResponse(success, data as ResponseType<any, any, ExtractAdapterType<Request>>);\n }\n });\n\n // When removed from queue storage we need to clean event listeners and return proper error\n const unmountRemoveQueueElement = requestManager.events.onRemoveById<Request>(requestId, (data) => {\n if (!isResolved) {\n const enriched = { ...data, mutationContext };\n options?.onRemove?.(enriched);\n $hooks.__emit(\"onRemove\", enriched);\n resolve({\n data: null,\n status: null,\n success: false,\n error: getErrorMessage(\"deleted\") as unknown as ExtractErrorType<Request>,\n extra: request.client.adapter.defaultExtra,\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n });\n\n // Unmount Listeners\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n umountAll();\n }\n });\n\n function umountAll() {\n unmountRequestStart();\n unmountResponseStart();\n unmountUpload();\n unmountDownload();\n unmountResponse();\n unmountRemoveQueueElement();\n }\n });\n};\n","import type { ResponseErrorType, ResponseSuccessType, ResponseType } from \"adapter\";\nimport type { ClientInstance } from \"client\";\nimport { Time } from \"constants/time.constants\";\nimport type { MockerConfigType, MockResponseType } from \"mocker\";\nimport type {\n ExtractAdapterType,\n ExtractClientAdapterType,\n ExtractClientGlobalError,\n ExtractEndpointType,\n ExtractParamsType,\n ExtractPayloadType,\n ExtractQueryParamsType,\n EmptyTypes,\n ExtractAdapterMethodType,\n ExtractAdapterOptionsType,\n HydrateDataType,\n SyncOrAsync,\n} from \"types\";\n\nimport type { RequestHooks } from \"./request.hooks\";\nimport { createRequestHooks } from \"./request.hooks\";\n/* eslint-disable max-lines */\nimport type {\n RequestSendOptionsType,\n ParamsType,\n RequestSendType,\n PayloadType,\n RequestJSON,\n RequestOptionsType,\n RequestConfigurationType,\n PayloadMapperType,\n RequestInstance,\n RequestMapper,\n ResponseMapper,\n ExtractUrlParams,\n RetryOnErrorCallbackType,\n OptimisticCallback,\n} from \"./request.types\";\nimport { mapResponseForSend, sendRequest, scopeKey } from \"./request.utils\";\n\ntype ClientAdapterOptions<C extends ClientInstance> = ExtractAdapterOptionsType<ExtractClientAdapterType<C>>;\ntype ClientAdapterMethod<C extends ClientInstance> = ExtractAdapterMethodType<ExtractClientAdapterType<C>>;\ntype ClientRequestOptions<E, C extends ClientInstance> = RequestOptionsType<\n E,\n ClientAdapterOptions<C>,\n ClientAdapterMethod<C>\n>;\n\n/**\n * Request is a class that represents a request sent to the server. It contains all the necessary information to make a request, like endpoint, method, headers, data, and much more.\n * It is executed at any time via methods like `send` or `exec`.\n *\n * We can set it up with options like endpoint, method, headers and more.\n * We can choose some of advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.\n *\n * @info We should not use this class directly in the standard development flow.\n * We can initialize it using the `createRequest` method on the **Client** class.\n *\n * @attention The most important thing about the request is that it keeps data in the format that can be dumped.\n * This is necessary for the persistence and different dispatcher storage types.\n * This class doesn't have any callback methods by design and communicate with dispatcher and cache by events.\n *\n * It should be serializable to JSON and deserializable back to the class.\n * Serialization should not affect the result of the request, so it's methods and functional part should be only syntax sugar for given runtime.\n */\n\nexport class Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string,\n Client extends ClientInstance,\n HasPayload extends true | false = false,\n HasParams extends true | false = false,\n HasQuery extends true | false = false,\n MutationContext = undefined,\n> {\n endpoint: Endpoint;\n headers?: HeadersInit = undefined;\n auth: boolean;\n method: ClientAdapterMethod<Client>;\n params: ExtractUrlParams<Endpoint> | EmptyTypes;\n payload: PayloadType<Payload>;\n queryParams: QueryParams | EmptyTypes;\n options?: ClientAdapterOptions<Client> | undefined = undefined;\n cancelable: boolean;\n retry: number;\n retryTime: number;\n cacheTime: number;\n cache: boolean;\n staleTime: number;\n queued: boolean;\n offline: boolean;\n abortKey: string;\n cacheKey: string;\n queryKey: string;\n used: boolean;\n deduplicate: boolean;\n deduplicateTime: number | null;\n structuralSharing: boolean;\n scope: string | null;\n\n /**\n * Instance-level lifecycle hooks. These callbacks fire for every `send()` / `exec()` call\n * made on this request instance (and its clones), without needing to pass them to `send()` each time.\n * Useful for cross-cutting concerns like logging, analytics, or toast notifications.\n *\n * Each method registers a callback and returns an unsubscribe function.\n * Multiple listeners per hook are supported.\n */\n $hooks: RequestHooks<RequestInstance> = createRequestHooks();\n\n isMockerEnabled = false;\n\n static readonly OPTIONAL_FIELDS = [\n \"unstable_mock\",\n \"unstable_payloadMapper\",\n \"unstable_requestMapper\",\n \"unstable_responseMapper\",\n \"retryOnError\",\n \"optimistic\",\n ] as const;\n\n // The `= undefined` initializers below are load-bearing. Metro (React Native) compiles\n // class properties in loose mode, which drops field declarations that have no initializer,\n // and the SDK proxy relies on an `in` check to tell request properties apart from deeper\n // API path segments (see OPTIONAL_REQUEST_FIELDS in sdk/sdk.ts).\n unstable_mock?: {\n fn: (options: {\n request: RequestInstance;\n requestId: string;\n }) => MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;\n config: MockerConfigType;\n } = undefined;\n /** @internal */\n unstable_payloadMapper?: PayloadMapperType<Payload> = undefined;\n /** @internal */\n unstable_requestMapper?: RequestMapper<any, any> = undefined;\n /** @internal */\n unstable_responseMapper?: ResponseMapper<this, ResponseSuccessType<any, any> | ResponseErrorType<any, any>> =\n undefined;\n /** @internal */\n retryOnError?: RetryOnErrorCallbackType<RequestInstance> = undefined;\n /** @internal */\n optimistic?: OptimisticCallback<RequestInstance, any> = undefined;\n\n unstable_hasParams: HasParams = false as HasParams;\n unstable_hasPayload: HasPayload = false as HasPayload;\n unstable_hasQuery: HasQuery = false as HasQuery;\n unstable_hasMutationContext: MutationContext = undefined as MutationContext;\n\n private updatedAbortKey: boolean;\n private updatedCacheKey: boolean;\n private updatedQueryKey: boolean;\n\n constructor(\n readonly client: Client,\n readonly requestOptions: ClientRequestOptions<Endpoint, Client>,\n readonly initialRequestConfiguration?:\n | RequestConfigurationType<\n Payload,\n Endpoint extends string ? ExtractUrlParams<Endpoint> : never,\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n >\n | undefined,\n ) {\n const configuration: ClientRequestOptions<Endpoint, Client> = {\n ...(this.client.adapter.unstable_getRequestDefaults?.(requestOptions) as ClientRequestOptions<Endpoint, Client>),\n ...requestOptions,\n };\n const {\n endpoint,\n headers,\n auth = true,\n method = client.adapter.defaultMethod,\n options,\n cancelable = false,\n retry = 0,\n retryTime = 500,\n cacheTime = Time.MIN * 5,\n cache = true,\n staleTime = Time.MIN * 5,\n queued = false,\n offline = true,\n abortKey,\n cacheKey,\n queryKey,\n deduplicate = false,\n deduplicateTime = null,\n structuralSharing = true,\n } = configuration;\n this.endpoint = initialRequestConfiguration?.endpoint ?? endpoint;\n this.headers = initialRequestConfiguration?.headers ?? headers;\n this.auth = initialRequestConfiguration?.auth ?? auth;\n this.method = method as ExtractAdapterMethodType<ExtractClientAdapterType<Client>>;\n this.params = initialRequestConfiguration?.params;\n this.payload = initialRequestConfiguration?.payload;\n this.queryParams = initialRequestConfiguration?.queryParams;\n this.options = initialRequestConfiguration?.options ?? options;\n this.cancelable = initialRequestConfiguration?.cancelable ?? cancelable;\n this.retry = initialRequestConfiguration?.retry ?? retry;\n this.retryTime = initialRequestConfiguration?.retryTime ?? retryTime;\n this.cacheTime = initialRequestConfiguration?.cacheTime ?? cacheTime;\n this.cache = initialRequestConfiguration?.cache ?? cache;\n this.staleTime = initialRequestConfiguration?.staleTime ?? staleTime;\n this.queued = initialRequestConfiguration?.queued ?? queued;\n this.offline = initialRequestConfiguration?.offline ?? offline;\n this.abortKey = initialRequestConfiguration?.abortKey ?? abortKey ?? this.client.unstable_abortKeyMapper(this);\n this.cacheKey = initialRequestConfiguration?.cacheKey ?? cacheKey ?? this.client.unstable_cacheKeyMapper(this);\n this.queryKey = initialRequestConfiguration?.queryKey ?? queryKey ?? this.client.unstable_queryKeyMapper(this);\n this.used = initialRequestConfiguration?.used ?? false;\n this.deduplicate = initialRequestConfiguration?.deduplicate ?? deduplicate;\n this.deduplicateTime = initialRequestConfiguration?.deduplicateTime ?? deduplicateTime;\n this.structuralSharing = initialRequestConfiguration?.structuralSharing ?? structuralSharing;\n this.scope = initialRequestConfiguration?.scope ?? null;\n this.updatedAbortKey = initialRequestConfiguration?.updatedAbortKey ?? false;\n this.updatedCacheKey = initialRequestConfiguration?.updatedCacheKey ?? false;\n this.updatedQueryKey = initialRequestConfiguration?.updatedQueryKey ?? false;\n }\n\n /** Set the request headers. Returns a cloned request with the new headers applied. */\n public setHeaders = (headers: HeadersInit) => {\n return this.clone({ headers });\n };\n\n /** Set whether authentication interceptors should run for this request. */\n public setAuth = (auth: boolean) => {\n return this.clone({ auth });\n };\n\n /** Set the URL path parameters (e.g., `:userId`). */\n public setParams = <P extends ExtractParamsType<this>>(params: P) => {\n return this.clone<HasPayload, P extends null ? false : true, HasQuery>({ params });\n };\n\n /** Set the request body payload. */\n public setPayload = <P extends Payload>(payload: P) => {\n return this.clone<P extends null ? false : true, HasParams, HasQuery>({\n payload,\n });\n };\n\n /** Set the query parameters appended to the URL. */\n public setQueryParams = (queryParams: QueryParams) => {\n return this.clone<HasPayload, HasParams, true>({ queryParams });\n };\n\n /** Set adapter-specific options (e.g., axios config, fetch init). */\n public setOptions = (options: ClientAdapterOptions<Client>) => {\n return this.clone<HasPayload, HasParams, true>({ options });\n };\n\n /**\n * Set a scope identifier for this request.\n * All keys (cache, queue, abort) are prefixed with this scope, isolating\n * the request from other scopes. In \"server\" client mode, setting a scope\n * also enables caching (which is otherwise disabled to prevent cross-request leaks).\n */\n public setScope = (scopeId: string) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.scope = scopeId;\n return cloned;\n };\n\n /** Set whether in-flight requests with the same abort key are cancelled when a new one is dispatched. */\n public setCancelable = (cancelable: boolean) => {\n return this.clone({ cancelable });\n };\n\n /** Set the number of retry attempts on failure. */\n public setRetry = (retry: ClientRequestOptions<Endpoint, Client>[\"retry\"]) => {\n return this.clone({ retry });\n };\n\n /** Set the delay in milliseconds between retry attempts. */\n public setRetryTime = (retryTime: ClientRequestOptions<Endpoint, Client>[\"retryTime\"]) => {\n return this.clone({ retryTime });\n };\n\n /**\n * Set a callback that controls whether a failed request should be retried.\n * Called on each failed attempt before scheduling the next retry.\n * Return `true` to allow the retry, `false` to stop retrying immediately.\n */\n public setRetryOnError = (\n callback: RetryOnErrorCallbackType<\n Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>\n >,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.retryOnError = callback as RetryOnErrorCallbackType<RequestInstance>;\n return cloned;\n };\n\n /**\n * Configure optimistic update behavior for this request.\n * The callback runs before the request is sent (in React's `useSubmit`) and receives\n * the request, client, and payload. Return `context` (available in submit callbacks),\n * `rollback` (called automatically on failure/abort), and `invalidate` (cache keys\n * invalidated on success).\n */\n public setOptimistic = <Ctx>(callback: OptimisticCallback<this, Ctx>) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.optimistic = callback as OptimisticCallback<RequestInstance, any>;\n return cloned as unknown as Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint,\n Client,\n HasPayload,\n HasParams,\n HasQuery,\n Ctx\n >;\n };\n\n /** Set how long (in ms) the response remains in cache before being garbage collected. */\n public setCacheTime = (cacheTime: ClientRequestOptions<Endpoint, Client>[\"cacheTime\"]) => {\n return this.clone({ cacheTime });\n };\n\n /** Set whether this request should use the cache. */\n public setCache = (cache: ClientRequestOptions<Endpoint, Client>[\"cache\"]) => {\n return this.clone({ cache });\n };\n\n /** Set how long (in ms) cached data is considered fresh before triggering a revalidation. */\n public setStaleTime = (staleTime: ClientRequestOptions<Endpoint, Client>[\"staleTime\"]) => {\n return this.clone({ staleTime });\n };\n\n /** Set whether the request should be queued and executed sequentially rather than immediately. */\n public setQueued = (queued: boolean) => {\n return this.clone({ queued });\n };\n\n /** Override the abort key used to cancel this request. */\n public setAbortKey = (abortKey: string) => {\n this.updatedAbortKey = true;\n return this.clone({ abortKey });\n };\n\n /** Override the cache key used to store/retrieve the response. */\n public setCacheKey = (cacheKey: string) => {\n this.updatedCacheKey = true;\n return this.clone({ cacheKey });\n };\n\n /** Override the query key that identifies this request in the dispatcher queue. */\n public setQueryKey = (queryKey: string) => {\n this.updatedQueryKey = true;\n return this.clone({ queryKey });\n };\n\n /** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */\n public setDeduplicate = (deduplicate: boolean) => {\n return this.clone({ deduplicate });\n };\n\n /** Set the time window (in ms) during which identical requests are deduplicated. */\n public setDeduplicateTime = (deduplicateTime: number) => {\n return this.clone({ deduplicateTime });\n };\n\n /** Enable or disable structural sharing - keeping references of unchanged parts of the response data in cache. */\n public setStructuralSharing = (structuralSharing: boolean) => {\n return this.clone({ structuralSharing });\n };\n\n /** Mark the request as used (prevents automatic refetching in hooks). */\n public setUsed = (used: boolean) => {\n return this.clone({ used });\n };\n\n /** Set whether the request should be stored in the offline queue when there is no network connection. */\n public setOffline = (offline: boolean) => {\n return this.clone({ offline });\n };\n\n /** Attach a mock handler to this request. When mocking is enabled, the handler is called instead of the real adapter. */\n public setMock = (\n fn: (options: {\n request: Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;\n requestId: string;\n }) => SyncOrAsync<\n MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n >,\n config: MockerConfigType = {},\n ) => {\n this.unstable_mock = { fn, config } as typeof this.unstable_mock;\n this.isMockerEnabled = true;\n return this;\n };\n\n /** Remove any attached mock handler and disable mocking for this request. */\n public clearMock = () => {\n this.unstable_mock = undefined;\n this.isMockerEnabled = false;\n return this;\n };\n\n /** Enable or disable the mocker for this request without removing the mock handler. */\n public setMockingEnabled = (isMockerEnabled: boolean) => {\n this.isMockerEnabled = isMockerEnabled;\n return this;\n };\n\n /**\n * Map data before it gets send to the server\n * @param payloadMapper\n * @returns\n */\n public setPayloadMapper = <MappedPayload extends any | Promise<any>>(\n payloadMapper: (data: Payload) => MappedPayload,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_payloadMapper = payloadMapper as typeof this.unstable_payloadMapper;\n\n return cloned;\n };\n\n /**\n * Map request before it gets send to the server\n * @param requestMapper mapper of the request\n * @returns new request\n */\n public setRequestMapper = <NewRequest extends RequestInstance>(requestMapper: RequestMapper<this, NewRequest>) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_requestMapper = requestMapper;\n\n return cloned;\n };\n\n /**\n * Map the response to the new interface\n * @param responseMapper our mapping callback\n * @returns new response\n */\n public setResponseMapper = <MappedResponse extends ResponseSuccessType<any, any> | ResponseErrorType<any, any>>(\n responseMapper?: ResponseMapper<this, MappedResponse>,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_responseMapper = responseMapper as typeof cloned.unstable_responseMapper;\n\n return cloned as unknown as Request<\n MappedResponse extends ResponseType<infer R, any, any> ? R : Response,\n Payload,\n QueryParams,\n MappedResponse extends ResponseType<any, infer E, any> ? E : LocalError,\n Endpoint,\n Client,\n HasPayload,\n HasParams,\n HasQuery,\n MutationContext\n >;\n };\n\n private paramsMapper = (params: ParamsType | null | undefined): Endpoint => {\n const { endpoint } = this.requestOptions;\n\n let stringEndpoint = String(endpoint);\n if (params) {\n Object.entries(params).forEach(([key, value]) => {\n stringEndpoint = stringEndpoint.replaceAll(new RegExp(`:${key}`, \"g\"), String(value));\n });\n }\n\n return stringEndpoint as Endpoint;\n };\n\n /** Serialize the request configuration into a plain JSON object for persistence or transfer. */\n public toJSON(): RequestJSON<this> {\n return {\n requestOptions: this.requestOptions as unknown as RequestOptionsType<\n ExtractEndpointType<this>,\n ExtractAdapterOptionsType<ExtractAdapterType<this>>,\n ExtractAdapterMethodType<ExtractAdapterType<this>>\n >,\n endpoint: this.endpoint as ExtractEndpointType<this>,\n headers: this.headers,\n auth: this.auth,\n // TODO: fix this type\n method: this.method as any,\n params: this.params as ExtractParamsType<this>,\n payload: this.payload as ExtractPayloadType<this>,\n queryParams: this.queryParams as ExtractQueryParamsType<this>,\n options: this.options,\n cancelable: this.cancelable,\n retry: this.retry,\n retryTime: this.retryTime,\n cacheTime: this.cacheTime,\n cache: this.cache,\n staleTime: this.staleTime,\n queued: this.queued,\n offline: this.offline,\n abortKey: this.abortKey,\n cacheKey: this.cacheKey,\n queryKey: this.queryKey,\n used: this.used,\n disableResponseInterceptors: this.requestOptions.disableResponseInterceptors,\n disableRequestInterceptors: this.requestOptions.disableRequestInterceptors,\n updatedAbortKey: this.updatedAbortKey,\n updatedCacheKey: this.updatedCacheKey,\n updatedQueryKey: this.updatedQueryKey,\n deduplicate: this.deduplicate,\n deduplicateTime: this.deduplicateTime,\n structuralSharing: this.structuralSharing,\n scope: this.scope,\n isMockerEnabled: this.isMockerEnabled,\n hasMock: !!this.unstable_mock,\n };\n }\n\n /** Create a new request instance with optional configuration overrides. Used internally by all setter methods. */\n public clone<\n NewData extends true | false = HasPayload,\n NewParams extends true | false = HasParams,\n NewQueryParams extends true | false = HasQuery,\n >(\n configuration?: RequestConfigurationType<\n Payload,\n (typeof this)[\"params\"],\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n >,\n ) {\n const json = this.toJSON();\n const initialRequestConfiguration: RequestConfigurationType<\n Payload,\n Endpoint extends string ? ExtractUrlParams<Endpoint> : never,\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n > = {\n ...json,\n ...configuration,\n options: configuration?.options || this.options,\n abortKey: this.updatedAbortKey ? configuration?.abortKey || this.abortKey : undefined,\n cacheKey: this.updatedCacheKey ? configuration?.cacheKey || this.cacheKey : undefined,\n queryKey: this.updatedQueryKey ? configuration?.queryKey || this.queryKey : undefined,\n endpoint: this.paramsMapper(configuration?.params || this.params),\n queryParams: configuration?.queryParams || this.queryParams,\n payload: configuration?.payload || this.payload,\n params: (configuration?.params || this.params) as\n | EmptyTypes\n | (Endpoint extends string ? ExtractUrlParams<Endpoint> : never),\n };\n\n const cloned = new Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint,\n Client,\n NewData,\n NewParams,\n NewQueryParams,\n MutationContext\n >(this.client, this.requestOptions, initialRequestConfiguration);\n\n // Inherit methods\n cloned.unstable_payloadMapper = this.unstable_payloadMapper;\n cloned.unstable_responseMapper = this.unstable_responseMapper as typeof cloned.unstable_responseMapper;\n cloned.unstable_requestMapper = this.unstable_requestMapper;\n cloned.retryOnError = this.retryOnError;\n\n cloned.unstable_mock = this.unstable_mock;\n cloned.isMockerEnabled = this.isMockerEnabled;\n cloned.optimistic = this.optimistic;\n cloned.$hooks = createRequestHooks(this.$hooks.__snapshot());\n\n return cloned;\n }\n\n /** Abort all in-flight requests sharing this request's abort key. */\n public abort = () => {\n const { requestManager } = this.client;\n requestManager.abortByKey(scopeKey(this.abortKey, this.scope));\n\n return this.clone();\n };\n\n /** Extract the current cache data for this request into a portable hydration payload (useful for SSR). */\n public dehydrate = (config?: {\n /** in case of using adapter without cache we can provide response to dehydrate */\n response?: ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;\n /** override cache data */\n override?: boolean;\n }):\n | HydrateDataType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n | undefined => {\n const { response, override = true } = config || {};\n\n if (response) {\n return {\n override,\n cacheTime: this.cacheTime,\n staleTime: this.staleTime,\n cacheKey: this.cacheKey,\n scope: this.scope,\n timestamp: Date.now(),\n hydrated: true,\n cache: true,\n response,\n };\n }\n\n const cacheData = this.client.cache.get<Response, LocalError | ExtractClientGlobalError<Client>>(\n scopeKey(this.cacheKey, this.scope),\n );\n\n if (!cacheData) {\n return undefined;\n }\n\n return {\n override,\n cacheTime: this.cacheTime,\n staleTime: this.staleTime,\n cacheKey: this.cacheKey,\n scope: this.scope,\n timestamp: Date.now(),\n hydrated: true,\n cache: true,\n response: {\n data: cacheData.data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra,\n requestTimestamp: cacheData.requestTimestamp,\n responseTimestamp: cacheData.responseTimestamp,\n },\n };\n };\n\n /**\n * Read the response from cache data\n *\n * If it returns error and data at the same time, it means that latest request was failed\n * and we show previous data from cache together with error received from actual request\n */\n public read():\n | ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n | undefined {\n const cacheData = this.client.cache.get<Response, LocalError | ExtractClientGlobalError<Client>>(\n scopeKey(this.cacheKey, this.scope),\n );\n\n if (cacheData) {\n return {\n data: cacheData.data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra,\n requestTimestamp: cacheData.requestTimestamp,\n responseTimestamp: cacheData.responseTimestamp,\n };\n }\n return undefined;\n }\n\n /**\n * Method to use the request WITHOUT adding it to cache and queues. This mean it will make simple request without queue side effects.\n * @param options\n * @disableReturns\n * @returns\n * ```tsx\n * Promise<[Data | null, Error | null, HttpStatus]>\n * ```\n */\n public exec: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {\n const { adapter, requestManager } = this.client;\n const request = this.clone(options);\n\n const requestId = this.client.unstable_requestIdMapper(this);\n\n const scopedAbortKey = scopeKey(this.abortKey, this.scope);\n\n // Listen for aborting\n requestManager.addAbortController(scopedAbortKey, requestId);\n\n const response = await adapter.fetch(request, requestId);\n\n // Stop listening for aborting\n requestManager.removeAbortController(scopedAbortKey, requestId);\n\n if (request.unstable_responseMapper) {\n return request.unstable_responseMapper(response);\n }\n\n return response;\n };\n\n /**\n * Method used to perform requests with usage of cache and queues\n * @param options\n * @param requestCallback\n * @disableReturns\n * @returns\n * ```tsx\n * Promise<{ data: Data | null, error: Error | null, status: HttpStatus, ... }>\n * ```\n */\n public send: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {\n const { dispatcherType: _dispatcherType, cachePolicy = \"network-only\", ...configuration } = options || {};\n\n const request = this.clone(configuration) as unknown as this;\n\n const sendRequestOptions = options === undefined ? undefined : { ...options, cachePolicy: undefined };\n\n if (cachePolicy === \"network-only\") {\n return sendRequest(request, sendRequestOptions);\n }\n\n const cached = request.read();\n\n if (cachePolicy === \"cache-first\") {\n if (cached) {\n return mapResponseForSend(request, cached);\n }\n return sendRequest(request, sendRequestOptions);\n }\n\n // revalidate\n if (cached) {\n const resolved = await mapResponseForSend(request, cached);\n // Background revalidation; promise from send() already resolved with cache snapshot\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n sendRequest(request, sendRequestOptions);\n return resolved;\n }\n\n return sendRequest(request, sendRequestOptions);\n };\n\n /** Reconstruct a Request instance from a previously serialized JSON representation. */\n static fromJSON = <\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint extends string,\n NewClient extends ClientInstance,\n NewHasPayload extends true | false = false,\n NewHasParams extends true | false = false,\n NewHasQuery extends true | false = false,\n >(\n client: NewClient,\n json: RequestJSON<\n Request<\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint,\n NewClient,\n NewHasPayload,\n NewHasParams,\n NewHasQuery\n >\n >,\n ) => {\n return new Request<\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint,\n NewClient,\n NewHasPayload,\n NewHasParams,\n NewHasQuery\n >(client, json.requestOptions, json);\n };\n}\n","import type { AdapterInstance, ResponseType } from \"adapter\";\nimport type {\n CacheOptionsType,\n CacheAsyncStorageType,\n CacheStorageType,\n CacheValueType,\n CacheSetState,\n RequestCacheType,\n} from \"cache\";\nimport { getCacheData, getCacheEvents, replaceEqualDeep } from \"cache\";\nimport type { ClientInstance } from \"client\";\nimport type { ResponseDetailsType, LoggerMethods } from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport { Request, scopeKey } from \"request\";\nimport type { ExtractAdapterType, ExtractErrorType, ExtractResponseType } from \"types\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * Cache class handles the data exchange with the dispatchers.\n *\n * @note\n * Keys used to save the values are created dynamically on the Request class\n *\n */\nexport class Cache<Adapter extends AdapterInstance> {\n public emitter = new EventEmitter();\n public events: ReturnType<typeof getCacheEvents>;\n\n public storage: CacheStorageType;\n public lazyStorage?: CacheAsyncStorageType = undefined;\n public version: string;\n public garbageCollectors = new Map<string, ReturnType<typeof setTimeout>>();\n private logger: LoggerMethods;\n private client: ClientInstance<{ adapter: Adapter }>;\n\n constructor(public options?: CacheOptionsType) {\n const { storage = new Map<string, CacheValueType>(), lazyStorage, version = \"0.0.1\" } = options ?? {};\n\n this.emitter?.setMaxListeners(1000);\n this.events = getCacheEvents(this.emitter);\n\n this.storage = storage;\n this.version = version;\n this.lazyStorage = lazyStorage;\n }\n\n /** Initialize the cache with a client reference, set up logging, and start garbage collection. */\n initialize = (client: ClientInstance<{ adapter: Adapter }>) => {\n this.client = client;\n this.logger = client.loggerManager.initialize(client, \"Cache\");\n\n // Going back from offline should re-trigger garbage collection\n client.appManager.events.onOnline(() => {\n [...this.storage.keys()].forEach(this.scheduleGarbageCollector);\n });\n\n [...this.storage.keys()].forEach(this.scheduleGarbageCollector);\n\n return this;\n };\n\n /**\n * Set the cache data to the storage\n * @param request\n * @param response\n * @returns\n */\n set = <Request extends RequestCacheType<RequestInstance>>(\n request: Request,\n response: CacheSetState<\n ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>> &\n ResponseDetailsType\n > & { hydrated?: boolean },\n ): void => {\n this.logger.debug({ title: \"Processing cache response\", type: \"system\", extra: { request, response } });\n const { cacheKey, cache, staleTime, cacheTime, scope } = request;\n const storageKey = scopeKey(cacheKey, scope);\n const previousCacheData = this.storage.get<\n ExtractResponseType<Request>,\n ExtractErrorType<Request>,\n ExtractAdapterType<Request>\n >(storageKey);\n\n // Once refresh error occurs we don't want to override already valid data in our cache with the thrown error\n // We need to check it against cache and return last valid data we have\n const processedResponse = typeof response === \"function\" ? response(previousCacheData || null) : response;\n const data = getCacheData(previousCacheData, processedResponse);\n\n // Keep references of the unchanged data parts, so deeply equal responses don't produce new objects\n if (request.structuralSharing !== false && previousCacheData) {\n data.data = replaceEqualDeep(previousCacheData.data, data.data);\n }\n\n const newCacheData: CacheValueType<any, any, ExtractAdapterType<Request>> = {\n ...data,\n scope,\n staleTime,\n version: this.version,\n cacheKey,\n cacheTime,\n cached: !!request.cache,\n };\n\n const isServerMode = this.client.mode === \"server\";\n const isCachingAllowed = cache && (!isServerMode || !!(request as any).scope);\n\n // Only success data is valid for the cache store\n if (processedResponse.success && isCachingAllowed) {\n this.logger.debug({ title: \"Saving response to cache storage\", type: \"system\", extra: { request, data } });\n this.storage.set<Response, Error, ExtractAdapterType<Request>>(storageKey, newCacheData);\n this.lazyStorage?.set<Response, Error, ExtractAdapterType<Request>>(storageKey, newCacheData);\n this.client.triggerPlugins(\"onCacheItemChange\", {\n cache: this,\n cacheKey,\n prevData: (previousCacheData || null) as CacheValueType<any, any, AdapterInstance>,\n newData: newCacheData as CacheValueType<any, any, AdapterInstance>,\n });\n\n this.scheduleGarbageCollector(storageKey);\n } else {\n // If request should not use cache - just emit response data\n this.logger.debug({ title: \"Prevented saving response to cache\", type: \"system\", extra: { request, data } });\n }\n\n this.logger.debug({ title: \"Emitting cache response\", type: \"system\", extra: { request, data } });\n this.events.emitCacheData<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>(\n newCacheData,\n );\n };\n\n /**\n * Update the cache data with partial response data\n * @param request\n * @param partialResponse\n * @returns\n */\n update = <Request extends RequestCacheType<RequestInstance>>(\n request: Request,\n partialResponse: CacheSetState<\n Partial<\n ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>> &\n ResponseDetailsType\n >\n >,\n ): void => {\n this.logger.debug({ title: \"Processing cache update\", type: \"system\", extra: { request, partialResponse } });\n const { cacheKey, scope } = request;\n const storageKey = scopeKey(cacheKey, scope);\n const cachedData = this.storage.get<\n ExtractResponseType<Request>,\n ExtractErrorType<Request>,\n ExtractAdapterType<Request>\n >(storageKey);\n\n const processedResponse =\n typeof partialResponse === \"function\" ? partialResponse(cachedData || null) : partialResponse;\n if (cachedData) {\n this.set(request, { ...cachedData, ...processedResponse });\n }\n };\n\n /**\n * Get particular record from storage by cacheKey. It will trigger lazyStorage to emit lazy load event for reading it's data.\n * @param cacheKey\n * @returns\n */\n get = <Response, Error>(cacheKey: string): CacheValueType<Response, Error, Adapter> | undefined => {\n this.getLazyResource<Response, Error>(cacheKey);\n const cachedData = this.storage.get<Response, Error, Adapter>(cacheKey);\n return cachedData;\n };\n\n /**\n * Get sync storage keys, lazyStorage keys will not be included\n * @returns\n */\n keys = (): string[] => {\n const values = this.storage.keys();\n\n return [...values];\n };\n\n /**\n * Delete record from storages and trigger invalidation event\n * @param cacheKey\n */\n delete = (cacheKey: string): void => {\n this.logger.debug({ title: \"Deleting cache element\", type: \"system\", extra: { cacheKey } });\n this.storage.delete(cacheKey);\n this.lazyStorage?.delete(cacheKey);\n\n this.client.triggerPlugins(\"onCacheItemDelete\", {\n cache: this,\n cacheKey,\n });\n\n this.events.emitDelete(cacheKey);\n };\n\n /**\n * Invalidate cache by cacheKey or partial matching with RegExp\n * It emits invalidation event for each matching cacheKey and sets staleTime to 0 to indicate out of time cache\n * Called without arguments it invalidates every cached element.\n * @param cacheKeys - cacheKey or Request instance or RegExp for partial matching (defaults to all elements)\n */\n invalidate = (cacheKeys: string | RegExp | RequestInstance | (string | RegExp | RequestInstance)[] = /.*/) => {\n this.logger.debug({ title: \"Revalidating cache element\", type: \"system\", extra: { cacheKeys } });\n\n const onInvalidate = (key: string | RegExp | RequestInstance) => {\n const keys = [...this.storage.keys()];\n const handleInvalidation = (invalidateStorageKey: string, notifyCacheKey: string = invalidateStorageKey) => {\n const value = this.storage.get(invalidateStorageKey);\n if (value) {\n this.storage.set(invalidateStorageKey, { ...value, staleTime: 0 });\n }\n\n this.client.triggerPlugins(\"onCacheItemInvalidate\", {\n cache: this,\n cacheKey: notifyCacheKey,\n });\n\n this.events.emitInvalidation(notifyCacheKey);\n };\n\n if (key instanceof Request) {\n handleInvalidation(scopeKey(key.cacheKey, key.scope), key.cacheKey);\n } else if (typeof key === \"string\") {\n handleInvalidation(key);\n } else if (keys.length > 0) {\n keys.forEach((entityKey) => {\n if (key.test(entityKey)) {\n handleInvalidation(entityKey);\n }\n });\n }\n };\n\n if (Array.isArray(cacheKeys)) {\n cacheKeys.forEach(onInvalidate.bind(this));\n } else {\n onInvalidate.bind(this)(cacheKeys);\n }\n };\n\n /**\n * Used to receive data from lazy storage\n * @param cacheKey\n */\n getLazyResource = async <Response, Error>(\n cacheKey: string,\n ): Promise<CacheValueType<Response, Error, Adapter> | undefined> => {\n const data = await this.lazyStorage?.get<Response, Error, Adapter>(cacheKey);\n const syncData = this.storage.get<Response, Error, Adapter>(cacheKey);\n\n // No data in lazy storage\n const hasLazyData = this.lazyStorage && data;\n if (hasLazyData) {\n const now = Date.now();\n const isNewestData = syncData ? syncData.responseTimestamp < data.responseTimestamp : true;\n const isStaleData = data.staleTime <= now - data.responseTimestamp;\n const isValidLazyData = data.version === this.version;\n\n if (!isValidLazyData) {\n this.lazyStorage?.delete(cacheKey);\n }\n if (isNewestData && !isStaleData && isValidLazyData) {\n this.storage.set<Response, Error, Adapter>(cacheKey, data);\n this.events.emitCacheData<Response, Error, Adapter>({ ...data, cacheKey, cached: true });\n return data;\n }\n }\n\n const isValidData = syncData?.version === this.version;\n if (syncData && !isValidData) {\n this.delete(cacheKey);\n }\n return syncData;\n };\n\n /**\n * Used to receive keys from lazy storage only\n */\n getLazyKeys = async () => {\n const keys = (await this.lazyStorage?.keys()) || [];\n\n return [...new Set(keys)];\n };\n\n /**\n * Used to receive deduplicated keys from both sync storage and lazy storage\n */\n getAllKeys = async () => {\n const keys = await this.lazyStorage?.keys();\n const asyncKeys = [...(keys || [])];\n const syncKeys = [...this.storage.keys()];\n\n return [...new Set([...asyncKeys, ...syncKeys])];\n };\n\n /**\n * Schedule garbage collection for given key\n * @param cacheKey\n * @returns\n */\n scheduleGarbageCollector = (cacheKey: string) => {\n // We need to make sure that all of the values will be removed, also that we have the proper data\n const cacheData = this.storage.get(cacheKey);\n\n // Clear running garbage collectors for given key\n clearTimeout(this.garbageCollectors.get(cacheKey));\n\n // Garbage collect\n if (cacheData) {\n const timeLeft = cacheData.cacheTime + cacheData.responseTimestamp - Date.now();\n // null\n if (cacheData.cacheTime === null) {\n this.logger.debug({ title: \"Cache time is null\", type: \"system\", extra: { cacheKey } });\n }\n // Infinity\n else if (\n (cacheData.cacheTime !== null && JSON.stringify(cacheData.cacheTime) === \"null\") ||\n cacheData.cacheTime === Infinity\n ) {\n this.logger.debug({ title: \"Cache time is Infinite\", type: \"system\", extra: { cacheKey } });\n }\n // Run garbage collector\n else if (timeLeft >= 0) {\n this.garbageCollectors.set(\n cacheKey,\n setTimeout(() => {\n if (this.client.appManager.isOnline) {\n this.logger.info({ title: \"Garbage collecting cache data\", type: \"system\", extra: { cacheKey } });\n this.delete(cacheKey);\n }\n }, timeLeft),\n );\n }\n // Delete if value is stale and we are online\n else if (this.client.appManager.isOnline) {\n this.logger.info({ title: \"Garbage collecting cache data\", type: \"system\", extra: { cacheKey } });\n this.delete(cacheKey);\n }\n }\n };\n\n /**\n * Clear cache storages\n */\n clear = async (): Promise<void> => {\n this.garbageCollectors.forEach((timeout) => clearTimeout(timeout));\n this.storage.clear();\n };\n}\n","import type { ResponseDetailsType } from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtractAdapterResolvedType } from \"types\";\n\nexport const getCacheData = <T extends RequestInstance>(\n previousResponse: ExtractAdapterResolvedType<T> | undefined,\n response: ExtractAdapterResolvedType<T> & ResponseDetailsType,\n): ExtractAdapterResolvedType<T> & ResponseDetailsType => {\n const { data, success } = response;\n\n const previousData = !success && previousResponse ? previousResponse.data : null;\n const computedData = data || previousData;\n\n return { ...response, data: computedData };\n};\n\nexport const getInvalidateKey = (): string => {\n return `invalidate`;\n};\nexport const getInvalidateByKey = (key: string): string => {\n return `${key}_invalidate`;\n};\nexport const getDeleteKey = (): string => {\n return `delete`;\n};\nexport const getDeleteByKey = (key: string): string => {\n return `${key}_delete`;\n};\nexport const getCacheByKey = (key: string): string => {\n return `${key}_cache`;\n};\nexport const getCacheKey = (): string => {\n return `cache`;\n};\n\n/**\n * Check if value is a plain object (object literal or `Object.create(null)`).\n * Class instances, Dates, Maps, Blobs etc. are not plain objects.\n */\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (Object.prototype.toString.call(value) !== \"[object Object]\") {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === null || prototype === Object.prototype;\n};\n\nconst isPlainArray = (value: unknown): value is unknown[] => {\n return Array.isArray(value) && Object.keys(value).length === value.length;\n};\n\n/**\n * Structural sharing - returns `next` with every part that is deeply equal to `prev` replaced by the `prev` reference.\n * When both values are deeply equal the `prev` reference is returned, so consumers can rely on `===` checks.\n * Only plain objects and arrays are traversed, other values are compared with `Object.is`.\n * @param prev previous value\n * @param next incoming value\n * @returns `next` sharing unchanged references with `prev`\n */\nexport const replaceEqualDeep = <T>(prev: unknown, next: T): T => {\n if (Object.is(prev, next)) {\n return prev as T;\n }\n\n const isArray = isPlainArray(prev) && isPlainArray(next);\n if (!isArray && !(isPlainObject(prev) && isPlainObject(next))) {\n return next;\n }\n\n const prevItems = prev as Record<string, unknown>;\n const nextItems = next as Record<string, unknown>;\n const prevKeys = Object.keys(prevItems);\n const nextKeys = Object.keys(nextItems);\n const copy: Record<string, unknown> = isArray ? ([] as unknown as Record<string, unknown>) : {};\n\n let equalItems = 0;\n nextKeys.forEach((key) => {\n const prevValue = prevItems[key];\n const nextValue = nextItems[key];\n const value = replaceEqualDeep(prevValue, nextValue);\n copy[key] = value;\n // undefined values are equal only when the key existed before\n // eslint-disable-next-line prefer-object-has-own -- Object.hasOwn is not available in older runtimes\n if (value === prevValue && (value !== undefined || Object.prototype.hasOwnProperty.call(prevItems, key))) {\n equalItems += 1;\n }\n });\n\n return (prevKeys.length === nextKeys.length && equalItems === prevKeys.length ? prev : copy) as T;\n};\n","import type { AdapterInstance } from \"adapter\";\nimport type { CacheValueType } from \"cache\";\nimport { getInvalidateByKey, getInvalidateKey, getCacheByKey, getCacheKey, getDeleteKey, getDeleteByKey } from \"cache\";\nimport type EventEmitter from \"events\";\n\n/** Create the cache event emitters and listeners for data changes, invalidation, and deletion. */\nexport const getCacheEvents = (emitter: EventEmitter) => ({\n /**\n * Set cache data\n * @param data\n */\n emitCacheData: <Response, Error, Adapter extends AdapterInstance>(\n data: CacheValueType<Response, Error, Adapter> & { cached: boolean },\n isTriggeredExternally = false,\n ): void => {\n emitter.emit(getCacheKey(), data, isTriggeredExternally);\n emitter.emit(getCacheByKey(data.cacheKey), data, isTriggeredExternally);\n },\n /**\n * Invalidate cache values event\n */\n emitInvalidation: (cacheKey: string, isTriggeredExternally = false): void => {\n emitter.emit(getInvalidateKey(), cacheKey, isTriggeredExternally);\n emitter.emit(getInvalidateByKey(cacheKey), isTriggeredExternally);\n },\n /**\n * Delete of cache values\n */\n emitDelete: (cacheKey: string, isTriggeredExternally = false): void => {\n emitter.emit(getDeleteKey(), cacheKey, isTriggeredExternally);\n emitter.emit(getDeleteByKey(cacheKey), isTriggeredExternally);\n },\n /**\n * Cache data listener for all keys\n * @param callback\n * @returns\n */\n onData: <Response, Error, Adapter extends AdapterInstance>(\n callback: (data: CacheValueType<Response, Error, Adapter> & { cached: boolean }) => void,\n ): VoidFunction => {\n emitter.on(getCacheKey(), callback);\n return () => emitter.removeListener(getCacheKey(), callback);\n },\n /**\n * Cache data listener filtered by a specific cache key\n * @param cacheKey\n * @param callback\n * @returns\n */\n onDataByKey: <Response, Error, Adapter extends AdapterInstance>(\n cacheKey: string,\n callback: (data: CacheValueType<Response, Error, Adapter>) => void,\n ): VoidFunction => {\n emitter.on(getCacheByKey(cacheKey), callback);\n return () => emitter.removeListener(getCacheByKey(cacheKey), callback);\n },\n /**\n * Cache invalidation listener\n * @param callback\n * @returns\n */\n onInvalidate: (callback: (cacheKey: string) => void): VoidFunction => {\n emitter.on(getInvalidateKey(), callback);\n return () => emitter.removeListener(getInvalidateKey(), callback);\n },\n /**\n * Cache invalidation listener\n * @param cacheKey\n * @param callback\n * @returns\n */\n onInvalidateByKey: (cacheKey: string, callback: () => void): VoidFunction => {\n emitter.on(getInvalidateByKey(cacheKey), callback);\n return () => emitter.removeListener(getInvalidateByKey(cacheKey), callback);\n },\n /** Cache deletion listener for all keys */\n onDelete: (callback: (cacheKey: string) => void): VoidFunction => {\n emitter.on(getDeleteKey(), callback);\n return () => emitter.removeListener(getDeleteKey(), callback);\n },\n /** Cache deletion listener filtered by a specific cache key */\n onDeleteByKey: (cacheKey: string, callback: () => void): VoidFunction => {\n emitter.on(getDeleteByKey(cacheKey), callback);\n return () => emitter.removeListener(getDeleteByKey(cacheKey), callback);\n },\n});\n","export enum DispatcherMode {\n ONE_BY_ONE = \"one-by-one\",\n ALL_AT_ONCE = \"all-at-once\",\n PREVIOUS_CANCELED = \"previous-canceled\",\n DEDUPLICATED = \"deduplicated\",\n}\n","import type { QueueDataType, RunningRequestsChangeType } from \"dispatcher\";\nimport {\n getDispatcherChangeKey,\n getDispatcherChangeByKey,\n getDispatcherStatusKey,\n getDispatcherStatusByKey,\n getDispatcherDrainedKey,\n getDispatcherDrainedByKey,\n getDispatcherRunningKey,\n getDispatcherRunningByKey,\n} from \"dispatcher\";\nimport type EventEmitter from \"events\";\nimport type { RequestInstance } from \"request\";\n\nexport const getDispatcherEvents = (emitter: EventEmitter) => ({\n emitDrained: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherDrainedKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherDrainedByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitQueueStatusChanged: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherStatusKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherStatusByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitQueueChanged: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherChangeKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherChangeByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitRunningRequestsChanged: (values: RunningRequestsChangeType, isTriggeredExternally?: boolean): void => {\n emitter.emit(getDispatcherRunningKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherRunningByKey(values.queryKey), values, isTriggeredExternally);\n },\n /**\n * When queue becomes empty\n * @param callback\n * @returns\n */\n onDrained: <Request extends RequestInstance>(callback: (values: QueueDataType<Request>) => void): VoidFunction => {\n emitter.on(getDispatcherDrainedKey(), callback);\n return () => emitter.removeListener(getDispatcherDrainedKey(), callback);\n },\n /**\n * When queue becomes empty\n * @param queryKey\n * @param callback\n * @returns\n */\n onDrainedByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherDrainedByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherDrainedByKey(queryKey), callback);\n },\n /**\n * When queue status change from enabled to paused or vice versa\n * @param callback\n * @returns\n */\n onQueueStatusChange: <Request extends RequestInstance>(\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherStatusKey(), callback);\n return () => emitter.removeListener(getDispatcherStatusKey(), callback);\n },\n /**\n * When queue status change from enabled to paused or vice versa\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueStatusChangeByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherStatusByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherStatusByKey(queryKey), callback);\n },\n /**\n * When new elements are added or removed from the queue\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueChange: <Request extends RequestInstance>(\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherChangeKey(), callback);\n return () => emitter.removeListener(getDispatcherChangeKey(), callback);\n },\n /**\n * When new elements are added or removed from the queue\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueChangeByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherChangeByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherChangeByKey(queryKey), callback);\n },\n /**\n * When requests start or stop running (sent, finished, canceled or cleared)\n * @param callback\n * @returns\n */\n onRunningRequestsChange: (callback: (values: RunningRequestsChangeType) => void): VoidFunction => {\n emitter.on(getDispatcherRunningKey(), callback);\n return () => emitter.removeListener(getDispatcherRunningKey(), callback);\n },\n /**\n * When requests start or stop running (sent, finished, canceled or cleared) for given queryKey\n * @param queryKey\n * @param callback\n * @returns\n */\n onRunningRequestsChangeByKey: (\n queryKey: string,\n callback: (values: RunningRequestsChangeType) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherRunningByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherRunningByKey(queryKey), callback);\n },\n});\n","import type { AdapterInstance, RequestResponseType } from \"adapter\";\nimport { getErrorMessage } from \"adapter\";\nimport type { ClientInstance } from \"client\";\nimport type {\n QueueDataType,\n DispatcherOptionsType,\n DispatcherStorageType,\n ResolvedQueueDataType,\n ResolvedQueueItemType,\n RunningRequestValueType,\n} from \"dispatcher\";\nimport { getRequestType, canRetryRequest, getDispatcherEvents, DispatcherMode } from \"dispatcher\";\nimport type { ResponseDetailsType, LoggerMethods } from \"managers\";\nimport type { RequestInstance, RequestJSON } from \"request\";\nimport { Request, scopeKey } from \"request\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * Dispatcher controls and manages the requests that are going to be executed with adapter. It manages them based on the options provided with request.\n * This class can also run them with different modes like deduplication, cancelation, queueing or run-all-at-once mode. With it's help we can pause,\n * stop, start and cancel requests.\n */\nexport class Dispatcher<Adapter extends AdapterInstance> {\n public emitter = new EventEmitter();\n public events = getDispatcherEvents(this.emitter);\n public storage: DispatcherStorageType = new Map<string, QueueDataType<any>>();\n\n private requestCount = new Map<string, number>();\n private runningRequests = new Map<string, RunningRequestValueType[]>();\n\n private logger: LoggerMethods;\n private client: ClientInstance<{ adapter: Adapter }>;\n\n constructor(public options?: DispatcherOptionsType) {\n this.emitter?.setMaxListeners(1000);\n\n if (this.options?.storage) {\n this.storage = this.options.storage;\n }\n }\n\n // eslint-disable-next-line class-methods-use-this\n private isRequestJSON = (\n request: RequestInstance | RequestJSON<RequestInstance>,\n ): request is RequestJSON<RequestInstance> => {\n return !(request instanceof Request);\n };\n\n initialize = (client: ClientInstance<{ adapter: Adapter }>) => {\n this.client = client;\n this.logger = client.loggerManager.initialize(client, \"Dispatcher\");\n\n // Going back from offline should re-trigger all requests\n this.client.appManager.events.onOnline(() => {\n this.flush();\n });\n\n return this;\n };\n\n // *********************************************************************\n // *********************************************************************\n // Queue\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Start request handling by queryKey\n */\n start = (queryKey: string) => {\n // Change status to running\n const queue = this.getQueue(queryKey);\n\n // Start the queue when its stopped\n queue.stopped = false;\n this.setQueue(queryKey, queue);\n this.flushQueue(queryKey);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"running\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Pause request queue, but do not cancel already started requests\n */\n pause = (queryKey: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n\n queue.stopped = true;\n this.setQueue(queryKey, queue);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"paused\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Stop request queue and cancel all started requests - those will be treated like not started\n */\n stop = (queryKey: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n\n queue.stopped = true;\n this.setQueue(queryKey, queue);\n\n // Cancel running requests\n this.cancelRunningRequests(queryKey);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"stopped\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Return all queue keys currently tracked by the dispatcher storage\n */\n getQueuesKeys = () => {\n return [...this.storage.keys()];\n };\n\n /**\n * Return queue state object.\n * Automatically reconstructs any serialized (JSON) requests back into\n * proper Request class instances so the rest of the pipeline can rely on\n * having a real `RequestInstance`.\n */\n getQueue = <R extends RequestInstance = RequestInstance>(queryKey: string): ResolvedQueueDataType<R> => {\n const initialQueueState: ResolvedQueueDataType<R> = { queryKey, requests: [], stopped: false };\n const storedEntity = this.storage.get<R>(queryKey);\n\n if (!storedEntity) {\n return initialQueueState;\n }\n\n const resolvedRequests: ResolvedQueueItemType<R>[] = storedEntity.requests.map((item) => {\n if (this.isRequestJSON(item.request)) {\n return { ...item, request: this.client.fromJSON(item.request as RequestJSON<RequestInstance>) as unknown as R };\n }\n return item as ResolvedQueueItemType<R>;\n });\n\n return { ...storedEntity, requests: resolvedRequests };\n };\n\n /**\n * Return request from queue state\n */\n getRequest = <Request extends RequestInstance = RequestInstance>(queryKey: string, requestId: string) => {\n const initialQueueState: QueueDataType<Request> = { queryKey, requests: [], stopped: false };\n const storedEntity = this.storage.get<Request>(queryKey) || initialQueueState;\n\n return storedEntity.requests.find((req) => req.requestId === requestId);\n };\n\n /**\n * Get value of the active queue status based on the stopped status\n */\n getIsActiveQueue = (queryKey: string) => {\n const queue = this.getQueue(queryKey);\n const hasAvailableRequests = queue.requests.some((req) => !req.stopped);\n const isRunningQueue = !queue.stopped;\n return hasAvailableRequests && isRunningQueue;\n };\n\n /**\n * Add new element to storage\n */\n addQueueItem = <Request extends RequestInstance = RequestInstance>(\n queryKey: string,\n element: ResolvedQueueItemType<Request>,\n ) => {\n const queue = this.getQueue<Request>(queryKey);\n queue.requests.push(element);\n\n this.client.triggerPlugins(\"onDispatcherItemAdded\", { dispatcher: this, queue, queueItem: element });\n\n this.setQueue<Request>(queryKey, queue);\n };\n\n /**\n * Set new queue storage value\n */\n setQueue = <Request extends RequestInstance = RequestInstance>(\n queryKey: string,\n queue: ResolvedQueueDataType<Request>,\n ) => {\n this.storage.set<Request>(queryKey, queue as QueueDataType<Request>);\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherQueueCreated\", { dispatcher: this, queue });\n this.events.emitQueueChanged(queue);\n\n return queue;\n };\n\n /**\n * Clear requests from queue cache\n */\n clearQueue = (queryKey: string) => {\n const queue = this.getQueue(queryKey);\n const newQueue = { queryKey, requests: [], stopped: queue.stopped };\n this.storage.set(queryKey, newQueue);\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherQueueCleared\", { dispatcher: this, queue: newQueue });\n this.events.emitQueueChanged(newQueue);\n this.events.emitDrained(newQueue);\n\n return newQueue;\n };\n\n /**\n * Method used to flush the queue requests\n */\n flushQueue = async (queryKey: string) => {\n const queue = this.getQueue(queryKey);\n const runningRequests = this.getRunningRequests(queryKey);\n const queueItem = queue.requests.find((request) => !request.stopped);\n\n const isStopped = queue && queue.stopped;\n const isOffline = !this.client.appManager.isOnline;\n const isConcurrent = !queueItem?.request.queued;\n const isInactive = runningRequests.length === 0;\n const isEmpty = !queueItem;\n\n // When there are no requests to flush, when its stopped, there is running request\n // or there is no request to trigger - we don't want to perform actions\n if (isStopped || isOffline || isEmpty) {\n this.logger.debug({ title: \"Skipping queue trigger\", type: \"system\", extra: { isStopped, isOffline, isEmpty } });\n } else if (isConcurrent) {\n queue.requests.forEach((element) => {\n if (!this.hasRunningRequest(queryKey, element.requestId)) {\n this.performRequest(element);\n }\n });\n } else if (isInactive) {\n await this.performRequest(queueItem);\n this.flushQueue(queryKey);\n }\n };\n\n /**\n * Flush all available requests from all queues\n */\n flush = async () => {\n const keys = this.getQueuesKeys();\n\n // eslint-disable-next-line no-restricted-syntax\n for (const key of keys) {\n const storageItem = this.getQueue(key);\n\n if (storageItem) {\n this.flushQueue(key);\n }\n }\n };\n\n /**\n * Clear all running requests and storage\n */\n clear = () => {\n const keys = this.getQueuesKeys();\n keys.forEach((queryKey) => this.cancelRunningRequests(queryKey));\n\n [...this.runningRequests.keys()].forEach((queryKey) => this.setRunningRequests(queryKey, []));\n this.runningRequests.clear();\n this.storage.clear();\n this.client.triggerPlugins(\"onDispatcherCleared\", { dispatcher: this });\n };\n\n // *********************************************************************\n // *********************************************************************\n // Requests\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Start particular request\n */\n startRequest = (queryKey: string, requestId: string) => {\n // Change status to running\n const queue = this.getQueue(queryKey);\n const request = queue.requests.find((element) => element.requestId === requestId);\n\n // Start the queue when its stopped\n if (request) {\n request.stopped = false;\n this.setQueue(queryKey, queue);\n this.flushQueue(queryKey);\n this.events.emitQueueStatusChanged(queue);\n }\n };\n\n /**\n * Stop particular request\n */\n stopRequest = (queryKey: string, requestId: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n const request = queue.requests.find((element) => element.requestId === requestId);\n\n if (request) {\n request.stopped = true;\n this.setQueue(queryKey, queue);\n\n // Cancel running requests\n this.cancelRunningRequest(queryKey, requestId);\n this.events.emitQueueStatusChanged(queue);\n }\n };\n\n /**\n * Get currently running requests from all queryKeys\n */\n getAllRunningRequests = () => {\n return [...this.runningRequests.values()].flat();\n };\n\n /**\n * Get currently running requests\n */\n getRunningRequests = (queryKey: string) => {\n return this.runningRequests.get(queryKey) || [];\n };\n\n /**\n * Get running request by id\n */\n getRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n return runningRequests.find((req) => req.requestId === requestId);\n };\n\n /**\n * Single place for changing the running requests - notifies about the change\n */\n private setRunningRequests = (queryKey: string, runningRequests: RunningRequestValueType[]) => {\n const previousRequests = this.getRunningRequests(queryKey);\n this.runningRequests.set(queryKey, runningRequests);\n if (\n previousRequests.length !== runningRequests.length ||\n previousRequests.some((req, i) => req !== runningRequests[i])\n ) {\n this.events.emitRunningRequestsChanged({ queryKey, runningRequests });\n }\n };\n\n /**\n * Add request to the running requests list\n */\n addRunningRequest = (queryKey: string, requestId: string, request: RequestInstance): RunningRequestValueType => {\n const newRunningRequest = { requestId, request, timestamp: Date.now() };\n this.setRunningRequests(queryKey, [...this.getRunningRequests(queryKey), newRunningRequest]);\n return newRunningRequest;\n };\n\n /**\n * Get the value based on the currently running requests\n */\n hasRunningRequests = (queryKey: string) => {\n return this.getRunningRequests(queryKey).length > 0;\n };\n\n /**\n * Check if request is currently processing\n */\n hasRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n return !!runningRequests.some((req) => req.requestId === requestId);\n };\n\n /**\n * Cancel all started requests, but do NOT remove it from main storage\n */\n cancelRunningRequests = (queryKey: string) => {\n this.runningRequests.get(queryKey)?.forEach((req) => {\n const ak = scopeKey(req.request.abortKey, req.request.scope);\n this.client.requestManager.abortByRequestId(ak, req.requestId);\n });\n this.deleteRunningRequests(queryKey);\n };\n /**\n * Cancel started request, but do NOT remove it from main storage\n */\n cancelRunningRequest = (queryKey: string, requestId: string) => {\n const requests = this.getRunningRequests(queryKey).filter((request) => {\n if (request.requestId === requestId) {\n const ak = scopeKey(request.request.abortKey, request.request.scope);\n this.client.requestManager.abortByRequestId(ak, request.requestId);\n return false;\n }\n return true;\n });\n\n this.setRunningRequests(queryKey, requests);\n };\n\n /**\n * Delete all started requests, but do NOT clear it from queue and do NOT cancel them\n */\n deleteRunningRequests = (queryKey: string) => {\n this.setRunningRequests(queryKey, []);\n };\n\n /**\n * Delete request by id, but do NOT clear it from queue and do NOT cancel them\n */\n deleteRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n this.setRunningRequests(\n queryKey,\n runningRequests.filter((req) => req.requestId !== requestId),\n );\n };\n\n /**\n * Get count of requests from the same queryKey\n */\n getQueueRequestCount = (queryKey: string) => {\n return this.requestCount.get(queryKey) || 0;\n };\n\n /**\n * Add request count to the queryKey\n */\n incrementQueueRequestCount = (queryKey: string) => {\n const count = this.requestCount.get(queryKey) || 0;\n this.requestCount.set(queryKey, count + 1);\n };\n\n /**\n * Create storage element from request\n */\n // eslint-disable-next-line class-methods-use-this\n createStorageItem = <R extends RequestInstance>(request: R): ResolvedQueueItemType<R> => {\n const requestId = this.client.unstable_requestIdMapper(request);\n return {\n requestId,\n timestamp: Date.now(),\n request,\n retries: 0,\n stopped: false,\n resolved: false,\n };\n };\n\n // *********************************************************************\n // *********************************************************************\n // Dispatching\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Add request to the dispatcher handler\n */\n add = (request: RequestInstance) => {\n const queryKey = scopeKey(request.queryKey, request.scope);\n\n // Create dump of the request to allow storing it in localStorage, AsyncStorage or any other\n // This way we don't save the Class but the instruction of the request to be done\n const storageItem = this.createStorageItem(request);\n const { requestId } = storageItem;\n\n const queue = this.getQueue(queryKey);\n const [latestRequest] = queue.requests.slice(-1);\n const requestType = getRequestType(request, latestRequest);\n\n this.logger.debug({ title: \"Adding request to queue\", type: \"system\", extra: { requestType, request, requestId } });\n\n switch (requestType) {\n case DispatcherMode.ONE_BY_ONE: {\n // Requests will go one by one\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n case DispatcherMode.PREVIOUS_CANCELED: {\n // Cancel all previous on-going requests\n this.cancelRunningRequests(queryKey);\n this.clearQueue(queryKey);\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n case DispatcherMode.DEDUPLICATED: {\n this.client.requestManager.events.emitDeduplicated({\n request: latestRequest.request,\n requestId,\n deduplicatedRequest: request,\n });\n // Return the running requestId to fulfill the events\n return latestRequest.requestId;\n }\n default: {\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n }\n };\n\n /**\n * Delete from the storage and cancel request\n */\n delete = (queryKey: string, requestId: string, abortKey: string) => {\n this.logger.debug({ title: \"Deleting request\", type: \"system\", extra: { queryKey, requestId, abortKey } });\n const queue = this.getQueue(queryKey);\n const queueItem = queue.requests.find((req) => req.requestId === requestId);\n\n if (!queueItem) {return;}\n\n queue.requests = queue.requests.filter((req) => req.requestId !== requestId);\n this.storage.set(queryKey, queue);\n\n // Clean controllers\n if (this.hasRunningRequest(queryKey, requestId)) {\n this.deleteRunningRequest(queryKey, requestId);\n this.client.requestManager.abortByRequestId(abortKey, requestId);\n }\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherItemDeleted\", { queue, dispatcher: this, queueItem });\n\n this.events.emitQueueChanged(queue);\n this.client.requestManager.events.emitRemove({\n requestId,\n request: queueItem.request,\n resolved: queueItem.resolved,\n });\n\n if (queue.requests.length === 0) {\n this.client.triggerPlugins(\"onDispatcherQueueDrained\", { queue, dispatcher: this });\n this.events.emitDrained(queue);\n }\n\n return queue;\n };\n\n /**\n * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted\n * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved\n */\n performRequest = async (storageItem: ResolvedQueueItemType) => {\n const { request, requestId } = storageItem;\n this.logger.debug({ title: \"Performing request\", type: \"system\", extra: { request, requestId } });\n\n const { retry, retryTime, queryKey: rawQueryKey, abortKey: rawAbortKey, offline, scope } = request;\n const queryKey = scopeKey(rawQueryKey, scope);\n const abortKey = scopeKey(rawAbortKey, scope);\n const { adapter, requestManager, cache, appManager } = this.client;\n\n const canRetry = canRetryRequest(storageItem.retries, retry);\n // When offline not perform any request\n const isOffline = !appManager.isOnline && offline;\n // When request with this id was triggered again\n const isAlreadyRunning = this.hasRunningRequest(queryKey, requestId);\n const isStopped = storageItem.stopped;\n\n if (isOffline || isAlreadyRunning || isStopped) {\n return this.logger.warning({\n title: \"Unable to perform request\",\n type: \"system\",\n extra: { isOffline, isAlreadyRunning, isStopped },\n });\n }\n\n // Additionally keep the running request to possibly abort it later\n const runningRequest = this.addRunningRequest(queryKey, requestId, request);\n\n // Propagate the loading to all connected hooks\n requestManager.events.emitLoading({\n request,\n requestId,\n loading: true,\n isRetry: !!storageItem.retries,\n isOffline,\n });\n\n // Trigger Request\n this.incrementQueueRequestCount(queryKey);\n // Listen for aborting\n requestManager.addAbortController(abortKey, requestId);\n\n const response: RequestResponseType<any> = await adapter.fetch(request, requestId);\n\n // TODO: improve this\n // eslint-disable-next-line no-param-reassign\n storageItem.resolved = true;\n // Stop listening for aborting\n requestManager.removeAbortController(abortKey, requestId);\n // Do not continue the request handling when it got stopped and request was unsuccessful\n // Or when the request was aborted/canceled\n const isOfflineResponseStatus = !appManager.isOnline;\n // If there is no running request with this id, it means it was cancelled and removed during send\n const isCancelMessage = getErrorMessage(\"abort\").message === response.error?.message;\n const isCanceled = !this.hasRunningRequest(queryKey, requestId) || isCancelMessage;\n\n // Remove running request, must be called after isCancelled\n this.deleteRunningRequest(queryKey, requestId);\n\n const shouldRetryOnError = response.success || !canRetry || !request.retryOnError || request.retryOnError(response);\n const willRetry = !response.success && canRetry && shouldRetryOnError && !isCanceled && !isOfflineResponseStatus;\n\n const requestDetails: ResponseDetailsType = {\n isCanceled,\n isOffline: isOfflineResponseStatus,\n retries: storageItem.retries,\n willRetry,\n addedTimestamp: storageItem.timestamp,\n triggerTimestamp: runningRequest.timestamp,\n requestTimestamp: response.requestTimestamp,\n responseTimestamp: response.responseTimestamp,\n };\n\n // Global response emitter to handle request execution\n requestManager.events.emitResponse({ request, requestId, response, details: requestDetails });\n\n // Turn off loading\n requestManager.events.emitLoading({\n request,\n requestId,\n loading: false,\n isRetry: !!storageItem.retries,\n isOffline,\n });\n\n // Cache event to emit the data inside and store it\n cache.set(request, { ...response, ...requestDetails });\n this.logger.debug({\n title: \"Dispatcher processing response\",\n type: \"system\",\n extra: { requestId, request, response, details: requestDetails },\n });\n\n // On cancelled\n if (isCanceled) {\n const queue = this.getQueue(queryKey);\n const queueItem = queue.requests.find((req) => req.requestId === requestId);\n\n // do not remove cancelled request as it may be result of manual queue pause\n // if abort was done without stop action we can remove request\n if (!queue.stopped && !queueItem?.stopped) {\n this.logger.debug({ title: \"Request paused\", type: \"system\", extra: { response, requestDetails, request } });\n return this.delete(queryKey, requestId, abortKey);\n }\n return this.logger.debug({\n title: \"Request canceled\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n }\n // On offline\n if (!response.success && isOfflineResponseStatus) {\n // if we don't want to keep offline request - just delete them\n if (!offline) {\n this.logger.warning({\n title: \"Removing non-offline request\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n return this.delete(queryKey, requestId, abortKey);\n }\n // do not remove request from store as we want to re-send it later\n return this.logger.debug({\n title: \"Awaiting for network restoration\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n }\n // On success\n if (response.success) {\n this.delete(queryKey, requestId, abortKey);\n return this.logger.debug({\n title: \"Successful response, removing request from queue.\",\n type: \"system\",\n extra: {\n response,\n requestDetails,\n request,\n },\n });\n }\n // On retry\n if (willRetry) {\n this.logger.debug({ title: \"Waiting for retry\", type: \"system\", extra: { response, requestDetails, request } });\n // Perform retry once request is failed\n setTimeout(() => {\n this.logger.warning({\n title: \"Error response, performing retry\",\n type: \"request\",\n extra: { response, requestDetails, request, requestId },\n });\n this.performRequest({\n ...storageItem,\n retries: storageItem.retries + 1,\n });\n }, retryTime || 0);\n } else {\n if (request.retry) {\n this.logger.error({\n title: \"All retries have been used. Removing request from queue.\",\n type: \"request\",\n extra: { response, requestDetails, request, requestId },\n });\n }\n this.delete(queryKey, requestId, abortKey);\n }\n };\n}\n","import type { ResolvedQueueItemType } from \"dispatcher\";\nimport { DispatcherMode } from \"dispatcher\";\nimport type { RequestInstance } from \"request\";\n\n// Events\n\nexport const getDispatcherDrainedKey = (): string => {\n return `drained-event`;\n};\nexport const getDispatcherDrainedByKey = (key: string): string => {\n return `${key}-drained-event`;\n};\nexport const getDispatcherStatusKey = (): string => {\n return `status-event`;\n};\nexport const getDispatcherStatusByKey = (key: string): string => {\n return `${key}-status-event`;\n};\nexport const getDispatcherChangeKey = (): string => {\n return `change-event`;\n};\nexport const getDispatcherChangeByKey = (key: string): string => {\n return `${key}-change-event`;\n};\nexport const getDispatcherRunningKey = (): string => {\n return `running-event`;\n};\nexport const getDispatcherRunningByKey = (key: string): string => {\n return `${key}-running-event`;\n};\n\n// Requesting\n\nexport const getIsEqualTimestamp = (currentTimestamp: number, threshold: number, queueTimestamp?: number): boolean => {\n if (!queueTimestamp) {\n return false;\n }\n return queueTimestamp - currentTimestamp <= threshold;\n};\n\nexport const canRetryRequest = (currentRetries: number, retry: number | undefined) => {\n if (retry && currentRetries < retry) {\n return true;\n }\n return false;\n};\n\nconst isInDeduplicateRange = (request: RequestInstance, latestRequest: ResolvedQueueItemType) => {\n if (request.deduplicateTime) {\n return Date.now() - latestRequest.timestamp <= request.deduplicateTime;\n }\n return true;\n};\n\nexport const getRequestType = (request: RequestInstance, latestRequest: ResolvedQueueItemType | undefined) => {\n const { queued, cancelable, deduplicate, used } = request;\n const canDeduplicate = latestRequest ? isInDeduplicateRange(request, latestRequest) : false;\n // Only join requests that are genuinely still ongoing. A resolved item already emitted its\n // response (a late joiner would wait forever), and a stopped item may never fire at all.\n const isOngoing = latestRequest ? !latestRequest.resolved && !latestRequest.stopped : false;\n\n if (queued) {\n return DispatcherMode.ONE_BY_ONE;\n }\n if (cancelable) {\n return DispatcherMode.PREVIOUS_CANCELED;\n }\n // A request marked with setUsed(true) is an intentional resend, like the auth interceptor\n // retrying after a token refresh. Deduplicating it against the original in-flight request\n // would deadlock: the retry would wait for a response that is blocked on the interceptor.\n if (canDeduplicate && isOngoing && deduplicate && !used) {\n return DispatcherMode.DEDUPLICATED;\n }\n return DispatcherMode.ALL_AT_ONCE;\n};\n","import { Time } from \"constants/time.constants\";\n\nimport type { HttpAdapterExtraType } from \"./http-adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\nexport const xhrExtra: HttpAdapterExtraType = {\n headers: {},\n};\n","import type { QueryParamsType, QueryParamType, QueryParamValuesType } from \"adapter\";\nimport { getErrorMessage } from \"adapter\";\nimport { stringifyDefaultOptions } from \"client\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtractErrorType, EmptyTypes } from \"types\";\n\nimport type { BufferEncoding, QueryStringifyOptionsType } from \"./http-adapter.types\";\n\n// Utils\n\nexport const getResponseHeaders = (headersString: string): Record<string, string> => {\n const arr = headersString.trim().split(/[\\r\\n]+/);\n\n const headers: Record<string, string> = {};\n arr.forEach((line) => {\n const parts = line.split(\": \");\n const header = parts.shift();\n const value = parts.join(\": \");\n if (header) {\n headers[header] = value;\n }\n });\n\n return headers;\n};\n\n// Responses\n\nexport const parseResponse = (response: string | unknown) => {\n try {\n return JSON.parse(response as string);\n } catch {\n return response;\n }\n};\n\nexport const handleResponse = (responseChunks: any[], responseType: string, responseEncoding: BufferEncoding) => {\n const bufferedResponse = Buffer.concat(responseChunks);\n switch (responseType) {\n case \"arraybuffer\": {\n return bufferedResponse;\n }\n case \"json\": {\n return parseResponse(bufferedResponse.toString(responseEncoding));\n }\n default: {\n return bufferedResponse.toString(responseEncoding);\n }\n }\n};\n\nexport const parseErrorResponse = <T extends RequestInstance>(response: unknown): ExtractErrorType<T> => {\n return response ? parseResponse(response) : (getErrorMessage() as ExtractErrorType<T>);\n};\n\n// Stringify\n\nconst isValidValue = (options: QueryStringifyOptionsType) => {\n return (value: QueryParamType) => {\n const { skipNull, skipEmptyString } = options;\n\n if (skipEmptyString && value === undefined) {\n return false;\n }\n if (skipEmptyString && value === \"\") {\n return false;\n }\n if (skipNull && value === null) {\n return false;\n }\n return true;\n };\n};\n\nconst encodeValue = (\n value: string,\n { encode, strict }: Pick<QueryStringifyOptionsType, \"encode\" | \"strict\">,\n): string => {\n if (encode && strict) {\n return encodeURIComponent(value).replaceAll(/[!'()*]/g, (s) => `%${s.codePointAt(0)!.toString(16).toUpperCase()}`);\n }\n if (encode) {\n return encodeURIComponent(value);\n }\n return value;\n};\n\nconst parseValue = (value: QueryParamValuesType, options: QueryStringifyOptionsType): string => {\n if (value instanceof Date) {\n return options.dateParser?.(value) || value.toISOString();\n }\n\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n return options.objectParser?.(value) || JSON.stringify(value);\n }\n\n return String(value);\n};\n\nconst encodeParams = (key: string, value: QueryParamType, options: QueryStringifyOptionsType) => {\n const shouldSkip = !isValidValue(options)(value);\n\n if (!key || shouldSkip) {\n return \"\";\n }\n\n return `${encodeValue(key, options)}=${encodeValue(parseValue(value as QueryParamValuesType, options), options)}`;\n};\n\nconst encodeArray = (key: string, array: QueryParamValuesType[], options: QueryStringifyOptionsType): string => {\n const { arrayFormat, arraySeparator } = options;\n const separator = arraySeparator || \"|\";\n const encodedKey = encodeValue(key, options);\n\n return array\n .filter(isValidValue(options))\n .reduce<string[]>((acc, value, index) => {\n const encodedValue = encodeValue(parseValue(value, options), options);\n\n switch (arrayFormat) {\n case \"index\": {\n acc.push(`${encodedKey}[${encodeValue(String(index), options)}]=${encodedValue}`);\n break;\n }\n case \"bracket\": {\n acc.push(`${encodedKey}[]=${encodedValue}`);\n break;\n }\n case \"comma\": {\n const keyValue = (acc.length === 0 && `${encodedKey}=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(\",\")];\n }\n case \"separator\": {\n const keyValue = (acc.length === 0 && `${encodedKey}=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(separator)];\n }\n case \"bracket-separator\": {\n const keyValue = (acc.length === 0 && `${encodedKey}[]=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(separator)];\n }\n default: {\n acc.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return acc;\n }, [])\n .join(\"&\");\n};\n\nexport const stringifyQueryParams = (\n queryParams: QueryParamsType | string | EmptyTypes,\n options?: QueryStringifyOptionsType,\n): string => {\n // Merge with defaults so a partial config (e.g. `{ arrayFormat: \"comma\" }`) keeps encoding and skipping enabled\n const config: QueryStringifyOptionsType = { ...stringifyDefaultOptions, ...options };\n\n if (!queryParams || Object.keys(queryParams).length === 0) {\n return \"\";\n }\n\n if (typeof queryParams === \"string\") {\n const hasQuestionMark = queryParams[0] === \"?\";\n return hasQuestionMark ? queryParams : `?${queryParams}`;\n }\n\n const stringified = Object.entries(queryParams)\n .map(([key, value]): string => {\n if (Array.isArray(value)) {\n return encodeArray(key, value, config);\n }\n\n return encodeParams(key, value, config);\n })\n .filter(Boolean)\n .join(\"&\");\n\n if (stringified) {\n return `?${stringified}`;\n }\n return \"\";\n};\n","import type { QueryParamsType } from \"adapter\";\nimport { HttpMethods, SAFE_HTTP_METHODS } from \"constants/http.constants\";\nimport type { HttpMethodsType, HttpStatusType } from \"types\";\n\nimport { Adapter } from \"../adapter/adapter\";\nimport { defaultTimeout, xhrExtra } from \"./http-adapter.constants\";\nimport type { HttpAdapterExtraType, FetchAdapterOptionsType } from \"./http-adapter.types\";\nimport { parseErrorResponse, parseResponse, stringifyQueryParams } from \"./http-adapter.utils\";\n\nconst defaultExtra = xhrExtra;\n\nexport const getAdapter = () =>\n new Adapter<\n FetchAdapterOptionsType,\n HttpMethodsType,\n HttpStatusType,\n HttpAdapterExtraType,\n QueryParamsType | string | null,\n undefined,\n string\n >({\n name: \"http\",\n defaultMethod: HttpMethods.GET,\n defaultExtra,\n systemErrorStatus: 0 as number,\n systemErrorExtra: defaultExtra,\n })\n .setQueryParamsMapper(stringifyQueryParams)\n // Safe reads (GET, QUERY) deduplicate by default: concurrent identical requests collapse\n // into one network call. Explicit `deduplicate` in request options still wins.\n .setRequestDefaults((options) => {\n const method = options.method ?? HttpMethods.GET;\n if (SAFE_HTTP_METHODS.includes(method)) {\n return { deduplicate: true };\n }\n return {};\n })\n .setFetcher(\n async ({\n request,\n url,\n endpoint,\n queryParams,\n adapterOptions,\n headers,\n payload,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n getAbortController,\n onResponseProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onSuccess,\n }) => {\n const { method } = request;\n const fullUrl = `${url}${endpoint}${queryParams}`;\n\n const controller = getAbortController();\n const { timeout: timeoutMs = defaultTimeout, streaming = false, ...restOptions } = adapterOptions || {};\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n // Abort listener handles user-initiated aborts (e.g. request.abort())\n // For fetch, onAbort is a no-op since the signal is already passed to fetch()\n const unmountListener = createAbortListener({\n status: 0,\n extra: defaultExtra,\n });\n\n if (timeoutMs > 0 && controller) {\n timeoutId = setTimeout(() => {\n timedOut = true;\n unmountListener();\n controller.abort();\n }, timeoutMs);\n }\n\n onBeforeRequest();\n onRequestStart();\n\n try {\n const init: RequestInit = {\n method,\n headers: headers as Record<string, string>,\n signal: controller?.signal,\n ...restOptions,\n };\n\n if (payload && method !== \"GET\" && method !== \"HEAD\") {\n init.body = payload as BodyInit;\n\n if (typeof payload === \"string\") {\n const total = new Blob([payload]).size;\n onRequestProgress({ total, loaded: total } as ProgressEvent);\n }\n }\n\n onRequestEnd();\n\n const response = await fetch(fullUrl, init);\n\n if (timeoutId) {clearTimeout(timeoutId);}\n\n onResponseStart();\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n const extra: HttpAdapterExtraType = { headers: responseHeaders };\n const { status } = response;\n\n if (streaming && response.body) {\n onResponseEnd();\n unmountListener();\n\n if (response.ok) {\n onSuccess({ data: response.body as any, status, extra });\n } else {\n const errorBody = await response.text();\n const error = parseErrorResponse(errorBody);\n onError({ error, status, extra });\n }\n } else {\n let body: string;\n\n if (response.body && typeof response.body.getReader === \"function\") {\n const reader = response.body.getReader();\n const contentLength = parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n let receivedLength = 0;\n const chunks: Uint8Array[] = [];\n\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 chunks.push(value);\n receivedLength += value.length;\n onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);\n }\n\n const allChunks = new Uint8Array(receivedLength);\n let position = 0;\n // eslint-disable-next-line no-restricted-syntax\n for (const chunk of chunks) {\n allChunks.set(chunk, position);\n position += chunk.length;\n }\n body = new TextDecoder().decode(allChunks);\n } else {\n body = await response.text();\n }\n\n onResponseEnd();\n unmountListener();\n\n if (response.ok) {\n const data = parseResponse(body);\n onSuccess({ data, status, extra });\n } else {\n const error = parseErrorResponse(body);\n onError({ error, status, extra });\n }\n }\n } catch (error: any) {\n if (timeoutId) {clearTimeout(timeoutId);}\n unmountListener();\n\n if (controller?.signal?.aborted) {\n if (timedOut) {\n onTimeoutError({ status: 0, extra: defaultExtra });\n }\n return;\n }\n\n onError({ error, status: 0, extra: defaultExtra });\n }\n },\n );\n","import type { HttpAdapterType } from \"http-adapter/http-adapter.types\";\n\nimport { getAdapter } from \"./http-adapter.fetch\";\n\nexport const HttpAdapter = (): HttpAdapterType => {\n return getAdapter();\n};\n","import type { ResponseType } from \"adapter\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtendRequest, ExtractClientAdapterType } from \"types\";\n\nimport type {\n ClientInstance,\n ClientMode,\n ClientModeOption,\n RequestInterceptorType,\n ResponseInterceptorType,\n} from \"./client.types\";\n\n/** Picks effective {@link ClientMode}: explicit override, else environment detection. */\nexport function resolveClientMode(modeOption: ClientModeOption | undefined): ClientMode {\n if (modeOption === \"client\" || modeOption === \"server\") {\n return modeOption;\n }\n\n const inBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\n if (inBrowser) {\n return \"client\";\n }\n\n return \"server\";\n}\n\nexport const interceptRequest = async (interceptors: RequestInterceptorType[], request: RequestInstance) => {\n let newRequest = request;\n if (!request.requestOptions.disableRequestInterceptors) {\n // eslint-disable-next-line no-restricted-syntax\n for (const interceptor of interceptors) {\n // eslint-disable-next-line no-await-in-loop\n newRequest = (await interceptor(request)) as RequestInstance;\n if (!newRequest) {throw new Error(\"Request modifier must return request\");}\n }\n }\n return newRequest;\n};\n\nexport const interceptResponse = async <GlobalErrorType, Client extends ClientInstance>(\n interceptors: ResponseInterceptorType<Client>[],\n response: ResponseType<any, GlobalErrorType, ExtractClientAdapterType<Client>>,\n request: ExtendRequest<RequestInstance, { client: Client }>,\n) => {\n let newResponse = response;\n if (!request.requestOptions.disableResponseInterceptors) {\n // eslint-disable-next-line no-restricted-syntax\n for (const interceptor of interceptors) {\n // eslint-disable-next-line no-await-in-loop\n newResponse = await interceptor(response, request);\n if (!newResponse) {throw new Error(\"Response modifier must return data\");}\n }\n }\n return newResponse;\n};\n","import type { AdapterInstance, ResponseType } from \"adapter\";\nimport { Cache } from \"cache\";\nimport type {\n ClientErrorType,\n ClientInstance,\n ClientMode,\n ClientOptionsType,\n RequestGenericType,\n RequestInterceptorType,\n ResponseInterceptorType,\n} from \"client\";\nimport { Dispatcher } from \"dispatcher\";\nimport type { HttpAdapterType } from \"http-adapter\";\nimport { parseResponse, HttpAdapter } from \"http-adapter\";\nimport type { LogLevel } from \"managers\";\nimport { AppManager, LoggerManager, RequestManager } from \"managers\";\nimport type { PluginInstance, PluginMethodParameters, PluginMethods } from \"plugin\";\nimport type { RequestInstance, RequestJSON, RequestOptionsType } from \"request\";\nimport { getRequestKey, getSimpleKey, Request, scopeKey } from \"request\";\nimport type {\n EmptyTypes,\n TypeWithDefaults,\n ExtractAdapterMethodType,\n ExtractAdapterOptionsType,\n ExtractAdapterQueryParamsType,\n ExtractAdapterEndpointType,\n ExtractUnionAdapter,\n HydrateDataType,\n HydrationOptions,\n ExtractAdapterDefaultQueryParamsType,\n ExtractAdapterRequestOptionsType,\n} from \"types\";\nimport { getUniqueRequestId } from \"utils\";\n\nimport { interceptRequest, interceptResponse, resolveClientMode } from \"./client.utils\";\n\n/**\n * **Client** is a class that allows you to configure the connection with the server and then use it to create\n * requests. It allows you to set global defaults for the requests configuration, query params configuration.\n * It is also orchestrator for all of the HyperFetch modules like Cache, Dispatcher, AppManager, LoggerManager,\n * RequestManager and more.\n */\nexport class Client<\n GlobalErrorType extends ClientErrorType = Error,\n Adapter extends AdapterInstance = HttpAdapterType,\n> {\n url: string;\n readonly mode: ClientMode;\n public debug: boolean;\n\n // Private\n unstable_onErrorCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onSuccessCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onResponseCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onAuthCallbacks: RequestInterceptorType[] = [];\n unstable_onRequestCallbacks: RequestInterceptorType[] = [];\n\n // Managers\n loggerManager: LoggerManager = new LoggerManager();\n requestManager: RequestManager = new RequestManager();\n appManager: AppManager;\n\n // Config\n adapter: Adapter;\n cache: Cache<Adapter>;\n fetchDispatcher: Dispatcher<Adapter>;\n submitDispatcher: Dispatcher<Adapter>;\n isMockerEnabled = true;\n\n // Registered requests effect\n plugins: PluginInstance[] = [];\n\n /** @internal */\n unstable_abortKeyMapper: (request: RequestInstance) => string = getSimpleKey;\n\n /** @internal */\n unstable_cacheKeyMapper: (request: RequestInstance) => string = getRequestKey;\n\n /** @internal */\n unstable_queryKeyMapper: (request: RequestInstance) => string = getRequestKey;\n\n /** @internal */\n unstable_requestIdMapper: (request: RequestInstance) => string = getUniqueRequestId;\n\n // Logger\n logger = this.loggerManager.initialize(this, \"Client\");\n\n constructor(public options: ClientOptionsType<Client<GlobalErrorType, Adapter>>) {\n const { url, appManager, cache, fetchDispatcher, submitDispatcher, mode: modeOption } = this.options;\n this.url = url;\n this.mode = resolveClientMode(modeOption);\n this.adapter = HttpAdapter() as Adapter;\n\n this.appManager = appManager?.() || new AppManager();\n this.cache = cache?.() || new Cache();\n this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();\n this.submitDispatcher = submitDispatcher?.() || new Dispatcher();\n\n // IMPORTANT: Do not change initialization order as it's crucial for dependencies injection\n this.adapter.initialize(this);\n this.appManager.initialize();\n this.cache.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.fetchDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.submitDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n }\n\n /**\n * Set the base url used by the next requests - e.g. when switching tenants, regions or environments at runtime.\n * Cache keys don't include the base url, so data cached for the previous url stays in place unless you pass\n * `invalidate: true`. Pass `abort: true` to cancel the requests that are still in progress for the previous url.\n * @param url new base url\n * @param options.abort abort all ongoing requests\n * @param options.invalidate invalidate the cache (and requests aborted by `abort`), so active consumers refetch\n */\n setUrl = (url: string, options: { abort?: boolean; invalidate?: boolean } = {}): Client<GlobalErrorType, Adapter> => {\n if (url === this.url) {\n return this;\n }\n\n const { abort = false, invalidate = false } = options;\n const runningRequests = this.fetchDispatcher.getAllRunningRequests().map(({ request }) => request);\n\n this.url = url;\n\n if (abort) {\n this.requestManager.abortAll();\n }\n if (invalidate) {\n this.cache.invalidate();\n // Aborted requests never land in the cache, so the full invalidation above would not notify their consumers\n if (abort && runningRequests.length > 0) {\n this.cache.invalidate(runningRequests);\n }\n }\n\n return this;\n };\n\n /**\n * This method enables the logger usage and display the logs in console\n */\n setDebug = (enabled: boolean): Client<GlobalErrorType, Adapter> => {\n this.debug = enabled;\n return this;\n };\n\n /**\n * Set the logger severity of the messages displayed to the console\n */\n setLogLevel = (severity: LogLevel): Client<GlobalErrorType, Adapter> => {\n this.loggerManager.setSeverity(severity);\n return this;\n };\n\n /**\n * Set the new logger instance to the Client\n */\n setLogger = (callback: (Client: ClientInstance) => LoggerManager): Client<GlobalErrorType, Adapter> => {\n this.loggerManager = callback(this);\n this.loggerManager.initialize(this, \"Client\");\n return this;\n };\n\n /**\n * Set globally if mocking should be enabled or disabled for all client requests.\n * @param isMockerEnabled\n */\n setEnableGlobalMocking = (isMockerEnabled: boolean) => {\n this.isMockerEnabled = isMockerEnabled;\n return this;\n };\n\n /**\n * Set custom http adapter to handle graphql, rest, firebase or others\n */\n setAdapter = <NewAdapter extends AdapterInstance>(adapter: NewAdapter): Client<GlobalErrorType, NewAdapter> => {\n this.adapter = adapter as unknown as Adapter;\n this.adapter.initialize(this);\n return this as unknown as Client<GlobalErrorType, NewAdapter>;\n };\n\n /**\n * Method of manipulating requests before sending the request. We can for example add custom header with token to the request which request had the auth set to true.\n */\n onAuth = (callback: RequestInterceptorType): Client<GlobalErrorType, Adapter> => {\n this.unstable_onAuthCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on auth.\n * */\n removeOnAuthInterceptors = (callbacks: RequestInterceptorType[]): Client<GlobalErrorType, Adapter> => {\n this.unstable_onAuthCallbacks = this.unstable_onAuthCallbacks.filter((callback) => !callbacks.includes(callback));\n return this;\n };\n\n /**\n * Method for intercepting error responses. It can be used for example to refresh tokens.\n */\n onError = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onErrorCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on error.\n * */\n removeOnErrorInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onErrorCallbacks = this.unstable_onErrorCallbacks.filter((callback) => !callbacks.includes(callback));\n return this;\n };\n\n /**\n * Method for intercepting success responses.\n */\n onSuccess = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onSuccessCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on success.\n * */\n removeOnSuccessInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onSuccessCallbacks = this.unstable_onSuccessCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Method of manipulating requests before sending the request.\n */\n onRequest = (callback: RequestInterceptorType): Client<GlobalErrorType, Adapter> => {\n this.unstable_onRequestCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on request.\n * */\n removeOnRequestInterceptors = (callbacks: RequestInterceptorType[]): Client<GlobalErrorType, Adapter> => {\n this.unstable_onRequestCallbacks = this.unstable_onRequestCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Method for intercepting any responses.\n */\n onResponse = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onResponseCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing response interceptors.\n * */\n removeOnResponseInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onResponseCallbacks = this.unstable_onResponseCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Add persistent plugins which trigger on the request lifecycle\n */\n addPlugin = (plugin: PluginInstance) => {\n this.plugins.push(plugin);\n\n plugin.initialize(this);\n plugin.trigger(\"onMount\", { client: this });\n\n return this;\n };\n\n /**\n * Remove plugins from Client\n */\n removePlugin = (plugin: PluginInstance) => {\n const pluginCount = this.plugins.length;\n this.plugins = this.plugins.filter((p) => p !== plugin);\n\n if (this.plugins.length !== pluginCount) {\n plugin.trigger(\"onUnmount\", { client: this });\n }\n\n return this;\n };\n\n triggerPlugins = <Key extends keyof PluginMethods<Client>>(key: Key, data: PluginMethodParameters<Key, Client>) => {\n if (this.plugins.length === 0) {\n return this;\n }\n\n this.plugins.forEach((plugin) => {\n plugin.trigger(key, data);\n });\n\n return this;\n };\n\n /**\n * Key setters\n */\n\n /** Set a custom mapper that generates the abort key used to cancel in-flight requests. */\n setAbortKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_abortKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the cache key used to store and retrieve cached responses. */\n setCacheKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_cacheKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the query key used to identify requests in the dispatcher queue. */\n setQueryKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_queryKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the unique request ID for deduplication and tracking. */\n setRequestIdMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_requestIdMapper = callback;\n return this;\n };\n\n /**\n * Helper used by http adapter to apply the modifications on response error\n * @private\n */\n unstable_modifyAuth = async (request: RequestInstance) => interceptRequest(this.unstable_onAuthCallbacks, request);\n\n /**\n * Private helper to run async pre-request processing\n * @private\n */\n unstable_modifyRequest = async (request: RequestInstance) =>\n interceptRequest(this.unstable_onRequestCallbacks, request);\n\n /**\n * Private helper to run async on-error response processing\n * @private\n */\n unstable_modifyErrorResponse = async (\n response: ResponseType<any, GlobalErrorType, Adapter>,\n request: RequestInstance,\n ) => interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onErrorCallbacks, response, request);\n\n /**\n * Private helper to run async on-success response processing\n * @private\n */\n unstable_modifySuccessResponse = async (\n response: ResponseType<any, GlobalErrorType, Adapter>,\n request: RequestInstance,\n ) => interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onSuccessCallbacks, response, request);\n\n /**\n * Private helper to run async response processing\n * @private\n */\n unstable_modifyResponse = async (response: ResponseType<any, GlobalErrorType, Adapter>, request: RequestInstance) =>\n interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onResponseCallbacks, response, request);\n\n /**\n * Reconstruct a Request class instance from its serialized JSON form.\n * Useful when dispatcher storage serializes queue data (e.g. MMKV, AsyncStorage)\n * and the deserialized request loses its class identity.\n */\n fromJSON = <RequestProperties extends RequestGenericType<ExtractAdapterQueryParamsType<Adapter>> = {}>(\n json: RequestJSON<RequestInstance>,\n ) => {\n type DefaultQueryParams = ExtractAdapterDefaultQueryParamsType<Adapter>;\n\n type Response = TypeWithDefaults<RequestProperties, \"response\", undefined>;\n type Payload = TypeWithDefaults<RequestProperties, \"payload\", undefined>;\n type LocalError = TypeWithDefaults<RequestProperties, \"error\", GlobalErrorType>;\n type QueryParams = TypeWithDefaults<RequestProperties, \"queryParams\", DefaultQueryParams, never>;\n type Endpoint = TypeWithDefaults<RequestProperties, \"endpoint\", string>;\n\n return Request.fromJSON(this as unknown as ClientInstance, json) as unknown as Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string ? Endpoint : string,\n Client<GlobalErrorType, Adapter>\n >;\n };\n\n /**\n * Clears the Client instance and remove all listeners on it's dependencies\n */\n clear = () => {\n const { appManager, cache, fetchDispatcher, submitDispatcher } = this.options;\n\n this.requestManager.abortControllers.clear();\n this.fetchDispatcher.clear();\n this.submitDispatcher.clear();\n this.cache.clear();\n\n this.requestManager.emitter.removeAllListeners();\n this.fetchDispatcher.emitter.removeAllListeners();\n this.submitDispatcher.emitter.removeAllListeners();\n this.cache.emitter.removeAllListeners();\n this.appManager.unmount();\n\n this.cache = cache?.() || new Cache();\n this.appManager = appManager?.() || new AppManager();\n this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();\n this.submitDispatcher = submitDispatcher?.() || new Dispatcher();\n\n // DO NOT CHANGE INITIALIZATION ORDER\n this.appManager.initialize();\n this.cache.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.fetchDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.submitDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n };\n\n /**\n * Hydrate your SSR cache data\n * @param hydrationData\n * @param options\n */\n hydrate = (\n hydrationData: (HydrateDataType | EmptyTypes)[],\n options?: Partial<HydrationOptions> | ((item: HydrateDataType) => Partial<HydrationOptions>),\n ) => {\n hydrationData?.forEach((item) => {\n if (!item) {\n return;\n }\n\n const { cacheKey, scope, response, ...fallbackOptions } = item;\n const defaults = {\n cache: true,\n override: true,\n } satisfies Partial<HydrationOptions>;\n const config =\n typeof options === \"function\"\n ? { ...defaults, ...fallbackOptions, ...options(item) }\n : { ...defaults, ...fallbackOptions, ...options };\n\n if (!config.override) {\n const cachedData = this.cache.get(scopeKey(cacheKey, scope));\n if (cachedData) {\n return;\n }\n }\n\n const parsedData = parseResponse(response);\n this.cache.set({ ...config, cacheKey, scope }, parsedData);\n });\n };\n\n /**\n * Create requests based on the Client setup\n *\n * @template Response Your response\n */\n createRequest = <RequestProperties extends RequestGenericType<ExtractAdapterQueryParamsType<Adapter>> = {}>(\n /**\n * `createRequest` must be initialized twice(currying).\n *\n * ✅ Good:\n * ```ts\n * const request = createRequest<RequestProperties>()(params)\n * ```\n * ⛔ Bad:\n * ```ts\n * const request = createRequest<RequestProperties>(params)\n * ```\n *\n * We are using currying to achieve auto generated types for the endpoint string.\n *\n * This solution will be removed once https://github.com/microsoft/TypeScript/issues/10571 get resolved.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _USE_DOUBLE_INITIALIZATION?: never,\n ) => {\n type DefaultQueryParams = ExtractAdapterDefaultQueryParamsType<Adapter>;\n\n type Response = TypeWithDefaults<RequestProperties, \"response\", undefined>;\n type Payload = TypeWithDefaults<RequestProperties, \"payload\", undefined>;\n type LocalError = TypeWithDefaults<RequestProperties, \"error\", GlobalErrorType>;\n /** we pass never to prevent the type from being empty, but we allow it to be undefined (optional) */\n type QueryParams = TypeWithDefaults<RequestProperties, \"queryParams\", DefaultQueryParams, never>;\n\n return <\n EndpointType extends ExtractAdapterEndpointType<Adapter>,\n AdapterOptions extends ExtractAdapterOptionsType<Adapter>,\n MethodType extends ExtractAdapterMethodType<Adapter>,\n >(\n params: RequestOptionsType<EndpointType, AdapterOptions, MethodType> & ExtractAdapterRequestOptionsType<Adapter>,\n ) => {\n type Endpoint = TypeWithDefaults<RequestProperties, \"endpoint\", EndpointType>;\n\n const endpoint = this.adapter.unstable_endpointMapper(params.endpoint);\n\n // Splitting this type prevents \"Type instantiation is excessively deep and possibly infinite\" error\n type ExtractedAdapter = ExtractUnionAdapter<\n Adapter,\n {\n method: MethodType;\n options: AdapterOptions;\n queryParams: QueryParams;\n }\n >;\n type ExtractedAdapterType = ExtractedAdapter extends EmptyTypes ? Adapter : ExtractedAdapter;\n\n const mappedParams: RequestOptionsType<\n Endpoint extends string ? Endpoint : typeof endpoint,\n AdapterOptions,\n MethodType\n > = {\n ...params,\n endpoint: String(endpoint) as Endpoint extends string ? Endpoint : typeof endpoint,\n };\n\n const request = new Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string ? Endpoint : typeof endpoint,\n Client<GlobalErrorType, ExtractedAdapterType>\n >(this as unknown as Client<GlobalErrorType, ExtractedAdapterType>, mappedParams);\n\n this.plugins.forEach((plugin) => plugin.trigger(\"onRequestCreate\", { request }));\n\n return request;\n };\n };\n}\n","export const stringifyDefaultOptions = {\n strict: true,\n encode: true,\n arrayFormat: \"bracket\",\n arraySeparator: \"|\",\n sort: false,\n skipNull: true,\n skipEmptyString: true,\n} as const;\n","import type { ClientErrorType, ClientOptionsType } from \"client\";\nimport { Client } from \"client\";\nimport type { HttpAdapterType } from \"http-adapter\";\nimport type { TypeWithDefaults } from \"types\";\n\nexport type ClientGenericType = {\n error?: ClientErrorType;\n};\n\nexport function createClient<ClientProperties extends ClientGenericType = {}>(\n options: ClientOptionsType<Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>>>,\n): Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>, HttpAdapterType> {\n return new Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>, HttpAdapterType>(options);\n}\n","import type { ClientInstance } from \"client\";\nimport type { RequestInstance } from \"request\";\nimport { Request } from \"request\";\nimport type {\n ExtractEndpointType,\n ExtractResponseType,\n ExtractPayloadType,\n ExtractQueryParamsType,\n ExtractLocalErrorType,\n ExtractHasPayloadType,\n ExtractHasParamsType,\n ExtractHasQueryParamsType,\n ExtractMutationContextType,\n} from \"types\";\n\nexport type RecursiveSchemaType = Record<\n string, // for example users / $userId / posts / $postId\n any\n>;\n\n/**\n * Recursively walks a schema and rebuilds every `Request` leaf with the SDK's actual client\n * type injected into the `Client` generic slot. Lets users omit `client` from their\n * `RequestModel<{...}>` declarations - the SDK fills it in from the client passed to\n * `createSdk(client)`.\n *\n * Non-Request leaves (primitive values, plain types) are passed through unchanged. Nested\n * schema objects are recursed into. Depth is guarded at 10 levels to keep the type checker\n * within reasonable bounds.\n */\nexport type InjectClient<T, TClient extends ClientInstance, Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? T\n : T extends RequestInstance\n ? Request<\n ExtractResponseType<T>,\n ExtractPayloadType<T>,\n ExtractQueryParamsType<T>,\n ExtractLocalErrorType<T>,\n ExtractEndpointType<T> extends string ? ExtractEndpointType<T> : string,\n TClient,\n ExtractHasPayloadType<T> extends boolean ? ExtractHasPayloadType<T> : false,\n ExtractHasParamsType<T> extends boolean ? ExtractHasParamsType<T> : false,\n ExtractHasQueryParamsType<T> extends boolean ? ExtractHasQueryParamsType<T> : false,\n ExtractMutationContextType<T>\n >\n : T extends Record<string, any>\n ? { [K in keyof T]: InjectClient<T[K], TClient, [...Depth, unknown]> }\n : T;\n\n/**\n * Per-request defaults that can be applied via SDK configuration.\n * These mirror the chainable setters on Request (headers, cache, retry, etc.).\n */\nexport type SdkRequestDefaults = {\n headers?: HeadersInit;\n auth?: boolean;\n cache?: boolean;\n cacheTime?: number;\n staleTime?: number;\n retry?: number;\n retryTime?: number;\n cancelable?: boolean;\n queued?: boolean;\n offline?: boolean;\n deduplicate?: boolean;\n deduplicateTime?: number | null;\n structuralSharing?: boolean;\n};\n\n/**\n * Configuration value: either a static property bag or a function that receives\n * the request and returns a modified request (full access to every Request setter).\n */\nexport type SdkConfigurationValue = SdkRequestDefaults | ((request: RequestInstance) => RequestInstance);\n\n/**\n * Recursively extracts all endpoint strings from an SDK schema type.\n * Leaf nodes (keys starting with $) are RequestInstance — extract endpoint from those.\n * Other keys are nested schema segments to recurse into.\n */\ntype ExtractSdkEndpoints<T, Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? never\n : {\n [K in keyof T]: K extends `$${string}`\n ? T[K] extends RequestInstance\n ? ExtractEndpointType<T[K]>\n : never\n : T[K] extends Record<string, any>\n ? ExtractSdkEndpoints<T[K], [...Depth, unknown]>\n : never;\n }[keyof T];\n\n/**\n * Recursively extracts dot-path accessor keys from an SDK schema.\n * These mirror the SDK property chain: \"users.$get\", \"users.$userId.$get\", etc.\n */\ntype ExtractSdkPaths<T, Prefix extends string = \"\", Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? never\n : {\n [K in keyof T & string]: T[K] extends RequestInstance\n ? `${Prefix}${K}`\n : T[K] extends Record<string, any>\n ? ExtractSdkPaths<T[K], `${Prefix}${K}.`, [...Depth, unknown]>\n : never;\n }[keyof T & string];\n\n/**\n * Builds the set of valid configuration keys from an SDK schema:\n * - \"*\" (global wildcard)\n * - exact endpoint paths extracted from RequestInstance nodes (group keys)\n * - wildcard patterns like \"/users/*\" (group keys)\n * - dot-path accessor keys like \"users.$get\" (method-specific keys)\n */\ntype SdkConfigurationKeys<Schema extends RecursiveSchemaType> =\n | \"*\"\n | ExtractSdkEndpoints<Schema>\n | `${ExtractSdkEndpoints<Schema> & string}/*`\n | ExtractSdkPaths<Schema>;\n\n/**\n * Maps endpoint paths, wildcard patterns, or dot-path accessor keys to request defaults.\n * Keys are validated against the SDK schema.\n *\n * Values can be:\n * - A plain `SdkRequestDefaults` object (shorthand for common settings)\n * - A function `(request) => request` for full access to every Request setter\n */\nexport type SdkConfigurationMap<Schema extends RecursiveSchemaType = RecursiveSchemaType> = Partial<\n Record<SdkConfigurationKeys<Schema>, SdkConfigurationValue>\n>;\n\nexport type CreateSdkOptions<Schema extends RecursiveSchemaType = RecursiveSchemaType> = {\n /** @default true */\n camelCaseToKebabCase?: boolean;\n /** @default (method) => method.toUpperCase() */\n methodTransform?: (method: string) => string;\n /** Per-endpoint request defaults */\n defaults?: SdkConfigurationMap<Schema>;\n};\n\nconst OPTIONAL_REQUEST_FIELDS = Request.OPTIONAL_FIELDS;\n\nconst getMethod = (key: string, options?: CreateSdkOptions<any>) => {\n const { methodTransform = (method: string) => method.toUpperCase() } = options ?? {};\n return methodTransform(key);\n};\n\nconst endpointMatchesPattern = (endpoint: string, pattern: string): boolean => {\n if (pattern === \"*\") {return true;}\n if (pattern === endpoint) {return true;}\n // Simple wildcard: \"/users/*\" matches \"/users/:userId\", \"/users/:userId/posts\", etc.\n if (pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -1);\n return endpoint.startsWith(prefix) || endpoint === prefix.slice(0, -1);\n }\n return false;\n};\n\nconst isDotPath = (key: string): boolean => {\n return key.includes(\".\") && !key.startsWith(\"/\");\n};\n\nconst applyObjectDefaults = (request: RequestInstance, config: SdkRequestDefaults): RequestInstance => {\n let result = request;\n if (config.headers) {result = result.setHeaders(config.headers);}\n if (config.auth !== undefined) {result = result.setAuth(config.auth);}\n if (config.cache !== undefined) {result = result.setCache(config.cache);}\n if (config.cacheTime !== undefined) {result = result.setCacheTime(config.cacheTime);}\n if (config.staleTime !== undefined) {result = result.setStaleTime(config.staleTime);}\n if (config.retry !== undefined) {result = result.setRetry(config.retry);}\n if (config.retryTime !== undefined) {result = result.setRetryTime(config.retryTime);}\n if (config.cancelable !== undefined) {result = result.setCancelable(config.cancelable);}\n if (config.queued !== undefined) {result = result.setQueued(config.queued);}\n if (config.offline !== undefined) {result = result.setOffline(config.offline);}\n if (config.deduplicate !== undefined) {result = result.setDeduplicate(config.deduplicate);}\n if (config.deduplicateTime !== undefined && config.deduplicateTime !== null) {\n result = result.setDeduplicateTime(config.deduplicateTime);\n }\n if (config.structuralSharing !== undefined) {\n result = result.setStructuralSharing(config.structuralSharing);\n }\n return result;\n};\n\nconst applyDefaults = (\n request: RequestInstance,\n context: { endpoint: string; sdkPath: string; defaults?: Partial<Record<string, SdkConfigurationValue>> },\n): RequestInstance => {\n const { endpoint, sdkPath, defaults } = context;\n if (!defaults) {return request;}\n\n let result = request;\n const entries = Object.entries(defaults);\n\n // Sort: \"*\" first, then endpoint groups (start with \"/\"), then dot-path (method-specific) last\n const globalEntries: [string, SdkConfigurationValue][] = [];\n const groupEntries: [string, SdkConfigurationValue][] = [];\n const pathEntries: [string, SdkConfigurationValue][] = [];\n\n for (let i = 0; i < entries.length; i += 1) {\n const [key, value] = entries[i];\n if (!value) {continue;}\n const entry: [string, SdkConfigurationValue] = [key, value];\n if (entry[0] === \"*\") {\n globalEntries.push(entry);\n } else if (isDotPath(entry[0])) {\n pathEntries.push(entry);\n } else {\n groupEntries.push(entry);\n }\n }\n\n const sorted = [...globalEntries, ...groupEntries, ...pathEntries];\n\n for (let i = 0; i < sorted.length; i += 1) {\n const [pattern, config] = sorted[i];\n\n let matches = false;\n if (isDotPath(pattern)) {\n matches = pattern === sdkPath;\n } else {\n matches = endpointMatchesPattern(endpoint, pattern);\n }\n\n if (matches) {\n if (typeof config === \"function\") {\n result = config(result);\n } else {\n result = applyObjectDefaults(result, config);\n }\n }\n }\n\n return result;\n};\n\nconst createRecursiveProxy = (\n client: ClientInstance,\n context: { path: string[]; sdkKeys: string[]; options?: CreateSdkOptions<any> },\n): any => {\n const { path, sdkKeys, options } = context;\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n return new Proxy(() => {}, {\n get: (_target, key: string) => {\n if (typeof key === \"symbol\" || key === \"inspect\") {\n return;\n }\n\n // Check if this is a method (starts with $) or a path segment\n let isMethod = false;\n let methodName = key;\n let pathSegment = key;\n\n if (key.startsWith(\"$\")) {\n isMethod = true;\n methodName = key.slice(1);\n pathSegment = `:${key.slice(1)}`;\n } else if (options?.camelCaseToKebabCase) {\n pathSegment = key.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n }\n\n // Build the sdk dot-path for method-specific configuration matching\n const currentSdkKeys = [...sdkKeys, key];\n const sdkPath = currentSdkKeys.join(\".\");\n\n // Always create a request assuming this is a method call\n const endpoint = `/${path.join(\"/\")}`;\n const method = getMethod(isMethod ? methodName : key, options);\n let request: RequestInstance = client.createRequest()({ endpoint, method });\n request = applyDefaults(request, { endpoint, sdkPath, defaults: options?.defaults });\n\n // But also, assume the key is a new path segment for a deeper call\n const newPath = [...path, pathSegment];\n const deeperProxy = createRecursiveProxy(client, { path: newPath, sdkKeys: currentSdkKeys, options });\n\n // Return a new proxy that wraps both the request and the deeper proxy\n return new Proxy(request, {\n get: (reqTarget, reqKey: string) => {\n // If the property exists on the request instance (like .send(), .setParams()), return it.\n // Optional fields are checked by name as well: transpilers that compile class\n // properties in loose mode (Metro on React Native) drop uninitialized field\n // declarations, and falling through to the deeper proxy would hand callers a\n // truthy path proxy where they expect undefined.\n if (reqKey in reqTarget || (OPTIONAL_REQUEST_FIELDS as readonly string[]).includes(reqKey)) {\n return reqTarget[reqKey as keyof typeof reqTarget];\n }\n // Otherwise, it's a deeper path, so delegate to the deeper proxy.\n return deeperProxy[reqKey];\n },\n });\n },\n });\n};\n\n/**\n * The fully-resolved SDK instance type returned by `createSdk`.\n *\n * The schema is rewritten via {@link InjectClient} so every `Request` leaf carries the\n * actual client type passed to `createSdk(client)` - users do not need to repeat\n * `client: AppClient` in every `RequestModel<{...}>` declaration.\n */\nexport type SdkInstance<\n Schema extends RecursiveSchemaType,\n TClient extends ClientInstance = ClientInstance,\n> = InjectClient<Schema, TClient> & {\n /**\n * Apply request defaults to the SDK. Returns a new SDK instance with the configuration applied.\n * Use \"*\" to match all endpoints, or specific endpoint strings / wildcard patterns.\n */\n $configure: (defaults: SdkConfigurationMap<Schema>) => SdkInstance<Schema, TClient>;\n};\n\nexport const createSdk = <Client extends ClientInstance, RecursiveSchema extends RecursiveSchemaType>(\n client: Client,\n options?: CreateSdkOptions<RecursiveSchema>,\n): SdkInstance<RecursiveSchema, Client> => {\n const {\n camelCaseToKebabCase = true,\n methodTransform = (method: string) => method.toUpperCase(),\n ...rest\n } = options ?? {};\n\n const mergedOptions: CreateSdkOptions<RecursiveSchema> = { camelCaseToKebabCase, methodTransform, ...rest };\n // Break inference for TypeDoc / tsserver (TS2589) — runtime value is unchanged.\n const proxy = createRecursiveProxy(client, { path: [], sdkKeys: [], options: mergedOptions as never });\n\n return new Proxy(proxy, {\n get: (target, key: string) => {\n if (key === \"$configure\") {\n return (defaults: SdkConfigurationMap<RecursiveSchema>) => {\n const existingDefaults = mergedOptions.defaults || {};\n return createSdk<Client, RecursiveSchema>(client, {\n ...mergedOptions,\n defaults: { ...existingDefaults, ...defaults } as SdkConfigurationMap<RecursiveSchema>,\n });\n };\n }\n return target[key];\n },\n }) as SdkInstance<RecursiveSchema, Client>;\n};\n\n/**\n * Type-safe factory for creating SDK configuration maps.\n *\n * @example\n * const config = createConfiguration<MySdkSchema>()({ \"*\": { retry: 3 } })\n */\nexport const createConfiguration = <Schema extends RecursiveSchemaType>() => {\n return (defaults: SdkConfigurationMap<Schema>): SdkConfigurationMap<Schema> => defaults;\n};\n"],"x_google_ignoreList":[6],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,IAAa,SAAb,MAAuF;CACrF;CACA;CAEA,SAAoC,KAAA;CAEpC,gBAAwD,EAAE;CAE1D,YAAY,QAA8C;AAAvC,OAAA,SAAA;AACjB,OAAK,OAAO,OAAO;AACnB,MAAI,OAAO,KACT,MAAK,OAAO,OAAO;;;CAKvB,cAAc,WAAmB;AAC/B,OAAK,SAAS;AACd,SAAO;;;CAIT,WAAoD,QAAa,SAA8C;EAC7G,MAAM,WAAW,KAAK,cAAc;AACpC,MAAI,SACF,UAAS,KAAY;;;;;CAWzB,WAAW,aAA+C;AACxD,OAAK,cAAc,UAAU;AAC7B,SAAO;;;;;CAMT,aAAa,aAAiD;AAC5D,OAAK,cAAc,YAAY;AAC/B,SAAO;;;;;C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B,MAAM,QAAQ,QAAgB;AAC5B,MAAI,QAAQ,aACV,SAAQ,aAAmD;GACzD,MAAM,mBAAmB,cAAc,YAAY,EAAE;AACrD,UAAO,UAAmC,QAAQ;IAChD,GAAG;IACH,UAAU;KAAE,GAAG;KAAkB,GAAG;KAAU;IAC/C,CAAC;;AAGN,SAAO,OAAO;IAEjB,CAAC;;;;;;;;AASJ,IAAa,4BAAgE;AAC3E,SAAQ,aAAuE"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/plugin/plugin.ts","../src/constants/time.constants.ts","../src/request/request.hooks.ts","../src/mocker/mocker.ts","../src/adapter/adapter.bindings.ts","../src/utils/uuid.utils.ts","../../../node_modules/.pnpm/events@3.3.0/node_modules/events/events.js","../src/utils/emitter.utils.ts","../src/managers/app/app.manager.ts","../src/managers/app/app.manager.utils.ts","../src/managers/app/app.manager.events.ts","../src/managers/app/app.manager.constants.ts","../src/managers/request/request.manager.ts","../src/managers/request/request.manager.utils.ts","../src/managers/request/request.manager.events.ts","../src/managers/logger/logger.manager.ts","../src/managers/logger/logger.manager.utils.ts","../src/managers/logger/logger.manager.constants.ts","../src/adapter/adapter.utils.ts","../src/adapter/adapter.ts","../src/constants/http.constants.ts","../src/request/request.utils.ts","../src/request/request.ts","../src/cache/cache.ts","../src/cache/cache.utils.ts","../src/cache/cache.events.ts","../src/dispatcher/dispatcher.constants.ts","../src/dispatcher/dispatcher.events.ts","../src/dispatcher/dispatcher.ts","../src/dispatcher/dispatcher.utils.ts","../src/http-adapter/http-adapter.constants.ts","../src/http-adapter/http-adapter.utils.ts","../src/http-adapter/http-adapter.fetch.ts","../src/http-adapter/http-adapter.ts","../src/client/client.utils.ts","../src/client/client.ts","../src/client/client.constants.ts","../src/client/client.create.ts","../src/sdk/sdk.ts"],"sourcesContent":["import type { ClientInstance } from \"client\";\nimport type { PluginMethodParameters, PluginMethods, PluginOptionsType } from \"plugin\";\n\n/**\n * Base class for plugins that hook into the request, cache, dispatcher, and adapter lifecycle.\n * Extend this to build devtools, logging, analytics, or custom side-effect plugins.\n */\nexport class Plugin<Client extends ClientInstance = ClientInstance, PluginData = void> {\n public name: string;\n public data: PluginData;\n\n public client: Client | undefined = undefined;\n\n private pluginMethods: Partial<PluginMethods<Client>> = {};\n\n constructor(public config: PluginOptionsType<PluginData>) {\n this.name = config.name;\n if (config.data) {\n this.data = config.data;\n }\n }\n\n /** Bind the plugin to a client instance. Called automatically when the plugin is added via `client.addPlugin()`. */\n initialize = (client: Client) => {\n this.client = client;\n return this;\n };\n\n /** Invoke a registered plugin method by name. Used internally by the client to dispatch lifecycle events. */\n trigger = <Key extends keyof PluginMethods<Client>>(method: Key, data: PluginMethodParameters<Key, Client>) => {\n const callback = this.pluginMethods[method];\n if (callback) {\n callback(data as any);\n }\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Plugin lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /**\n * Callback that will be executed when plugin is mounted\n */\n onMount = (callback: PluginMethods<Client>[\"onMount\"]) => {\n this.pluginMethods.onMount = callback;\n return this;\n };\n\n /**\n * Callback that will be executed when plugin is unmounted\n */\n onUnmount = (callback: PluginMethods<Client>[\"onUnmount\"]) => {\n this.pluginMethods.onUnmount = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Request lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /**\n * Callback that will be executed when request is created\n */\n onRequestCreate = (callback: PluginMethods<Client>[\"onRequestCreate\"]) => {\n this.pluginMethods.onRequestCreate = callback;\n return this;\n };\n /**\n * Callback that will be executed when request gets triggered\n */\n onRequestTrigger = (callback: PluginMethods<Client>[\"onRequestTrigger\"]) => {\n this.pluginMethods.onRequestTrigger = callback;\n return this;\n };\n /**\n * Callback that will be executed when request starts\n */\n onRequestStart = (callback: PluginMethods<Client>[\"onRequestStart\"]) => {\n this.pluginMethods.onRequestStart = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is successful\n */\n onRequestSuccess = (callback: PluginMethods<Client>[\"onRequestSuccess\"]) => {\n this.pluginMethods.onRequestSuccess = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is failed\n */\n onRequestError = (callback: PluginMethods<Client>[\"onRequestError\"]) => {\n this.pluginMethods.onRequestError = callback;\n return this;\n };\n /**\n * Callback that will be executed when response is finished\n */\n onRequestFinished = (callback: PluginMethods<Client>[\"onRequestFinished\"]) => {\n this.pluginMethods.onRequestFinished = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Dispatcher lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when the dispatcher storage is fully cleared */\n onDispatcherCleared = (callback: PluginMethods<Client>[\"onDispatcherCleared\"]) => {\n this.pluginMethods.onDispatcherCleared = callback;\n return this;\n };\n\n /** Called when a dispatcher queue has no more pending requests */\n onDispatcherQueueDrained = (callback: PluginMethods<Client>[\"onDispatcherQueueDrained\"]) => {\n this.pluginMethods.onDispatcherQueueDrained = callback;\n return this;\n };\n\n /** Called when a dispatcher queue transitions to running, paused, or stopped */\n onDispatcherQueueRunning = (callback: PluginMethods<Client>[\"onDispatcherQueueRunning\"]) => {\n this.pluginMethods.onDispatcherQueueRunning = callback;\n return this;\n };\n\n /** Called when a new item is added to a dispatcher queue */\n onDispatcherItemAdded = (callback: PluginMethods<Client>[\"onDispatcherItemAdded\"]) => {\n this.pluginMethods.onDispatcherItemAdded = callback;\n return this;\n };\n\n /** Called when an item is removed from a dispatcher queue */\n onDispatcherItemDeleted = (callback: PluginMethods<Client>[\"onDispatcherItemDeleted\"]) => {\n this.pluginMethods.onDispatcherItemDeleted = callback;\n return this;\n };\n\n /** Called when a new dispatcher queue is created */\n onDispatcherQueueCreated = (callback: PluginMethods<Client>[\"onDispatcherQueueCreated\"]) => {\n this.pluginMethods.onDispatcherQueueCreated = callback;\n return this;\n };\n\n /** Called when an entire dispatcher queue is cleared */\n onDispatcherQueueCleared = (callback: PluginMethods<Client>[\"onDispatcherQueueCleared\"]) => {\n this.pluginMethods.onDispatcherQueueCleared = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Cache lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when a cache entry is created or updated */\n onCacheItemChange = (callback: PluginMethods<Client>[\"onCacheItemChange\"]) => {\n this.pluginMethods.onCacheItemChange = callback;\n return this;\n };\n\n /** Called when a cache entry is deleted */\n onCacheItemDelete = (callback: PluginMethods<Client>[\"onCacheItemDelete\"]) => {\n this.pluginMethods.onCacheItemDelete = callback;\n return this;\n };\n\n /* -------------------------------------------------------------------------------------------------\n * Adapter lifecycle\n * -----------------------------------------------------------------------------------------------*/\n\n /** Called when the adapter fetcher is about to execute a request */\n onAdapterFetch = (callback: PluginMethods<Client>[\"onAdapterFetch\"]) => {\n this.pluginMethods.onAdapterFetch = callback;\n return this;\n };\n}\n","export enum Time {\n SEC = 1e3,\n MIN = 6e4,\n HOUR = 3.6e6,\n DAY = 8.64e7,\n WEEK = 6.048e8,\n MONTH_30 = 2.592e9,\n MONTH_31 = 2.6784e9,\n YEAR = 3.1536e10,\n YEAR_LEAP = 3.162_24e10,\n}\n","import type { RequestEventType, RequestProgressEventType, RequestResponseEventType } from \"managers\";\n\nimport type { RequestInstance } from \"./request.types\";\n\ntype HookName =\n | \"onBeforeSent\"\n | \"onRequestStart\"\n | \"onResponseStart\"\n | \"onUploadProgress\"\n | \"onDownloadProgress\"\n | \"onResponse\"\n | \"onRemove\";\n\nexport interface RequestHooks<R extends RequestInstance> {\n onBeforeSent: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onRequestStart: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onResponseStart: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n onUploadProgress: (cb: (eventData: RequestProgressEventType<R>) => void) => () => void;\n onDownloadProgress: (cb: (eventData: RequestProgressEventType<R>) => void) => () => void;\n onResponse: (cb: (eventData: RequestResponseEventType<R>) => void) => () => void;\n onRemove: (cb: (eventData: RequestEventType<R>) => void) => () => void;\n /** @internal Invoke all registered listeners for a given hook */\n __emit: (name: HookName, data: any) => void;\n /** @internal Get a snapshot of all registered listeners (used by clone) */\n __snapshot: () => Record<HookName, ((...args: any[]) => void)[]>;\n}\n\nconst HOOK_NAMES: HookName[] = [\n \"onBeforeSent\",\n \"onRequestStart\",\n \"onResponseStart\",\n \"onUploadProgress\",\n \"onDownloadProgress\",\n \"onResponse\",\n \"onRemove\",\n];\n\nexport function createRequestHooks<R extends RequestInstance>(\n initial?: Record<HookName, ((...args: any[]) => void)[]>,\n): RequestHooks<R> {\n const listeners: Record<HookName, ((...args: any[]) => void)[]> = {\n onBeforeSent: [],\n onRequestStart: [],\n onResponseStart: [],\n onUploadProgress: [],\n onDownloadProgress: [],\n onResponse: [],\n onRemove: [],\n };\n\n if (initial) {\n HOOK_NAMES.forEach((name) => {\n listeners[name] = [...initial[name]];\n });\n }\n\n const subscribe = (name: HookName) => {\n return (cb: (...args: any[]) => void) => {\n listeners[name].push(cb);\n return () => {\n const idx = listeners[name].indexOf(cb);\n if (idx !== -1) {listeners[name].splice(idx, 1);}\n };\n };\n };\n\n return {\n onBeforeSent: subscribe(\"onBeforeSent\"),\n onRequestStart: subscribe(\"onRequestStart\"),\n onResponseStart: subscribe(\"onResponseStart\"),\n onUploadProgress: subscribe(\"onUploadProgress\"),\n onDownloadProgress: subscribe(\"onDownloadProgress\"),\n onResponse: subscribe(\"onResponse\"),\n onRemove: subscribe(\"onRemove\"),\n __emit(name: HookName, data: any) {\n listeners[name].forEach((cb) => {\n cb(data);\n });\n },\n __snapshot() {\n const snap = {} as Record<HookName, ((...args: any[]) => void)[]>;\n HOOK_NAMES.forEach((name) => {\n snap[name] = [...listeners[name]];\n });\n return snap;\n },\n };\n}\n","import type { getAdapterBindings, AdapterInstance } from \"adapter\";\nimport { RequestProcessingError } from \"adapter\";\nimport type { ExtractAdapterExtraType, ExtractAdapterStatusType } from \"types\";\n\nexport const mocker = async <T extends AdapterInstance>({\n request,\n requestId,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n onResponseProgress,\n onRequestProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onSuccess,\n onAbortError,\n adapter,\n}: Awaited<ReturnType<typeof getAdapterBindings<T>>>) => {\n if (!request.unstable_mock) {\n throw new RequestProcessingError(\"Mock should be defined when calling mocker\");\n }\n\n let thrown = false;\n\n const {\n requestTime = 20,\n responseTime = 20,\n totalUploaded = 1000,\n totalDownloaded = 1000,\n timeout,\n } = request.unstable_mock.config;\n const result = await request.unstable_mock.fn({ request, requestId });\n\n const { data, error, status, success = true, extra = request.client.adapter.defaultExtra } = result;\n\n createAbortListener({\n status: adapter.systemErrorStatus,\n extra: adapter.systemErrorExtra,\n onAbort: () => {\n thrown = true;\n },\n });\n\n onBeforeRequest();\n onRequestStart();\n\n const progress = (\n totalTime: number,\n totalSize: number,\n progressFunction: typeof onResponseProgress | typeof onRequestProgress,\n ) =>\n new Promise((resolveProgress) => {\n if (thrown) {\n resolveProgress(true);\n return;\n }\n\n const interval = 20;\n const dataStart = Date.now();\n const intervals = Math.ceil(totalTime / interval);\n const chunkSize = Math.ceil(totalSize / intervals);\n let currentlyLoaded = 0;\n const timer = setInterval(function handleProgressInterval() {\n if (thrown) {\n resolveProgress(true);\n clearInterval(timer);\n }\n\n const currentTime = Math.min(totalTime, Date.now() - dataStart);\n currentlyLoaded += currentlyLoaded + chunkSize >= totalSize ? totalSize - currentlyLoaded : chunkSize;\n progressFunction({\n total: totalSize,\n loaded: currentTime >= totalTime ? totalSize : currentlyLoaded,\n });\n\n if (currentTime >= totalTime) {\n resolveProgress(true);\n clearInterval(timer);\n }\n }, interval);\n });\n\n if (typeof timeout === \"number\") {\n setTimeout(() => {\n thrown = true;\n onTimeoutError({\n status: 0 as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n }, timeout);\n }\n if (!thrown) {\n await progress(requestTime, totalUploaded, onRequestProgress);\n }\n if (!thrown) {\n onRequestEnd();\n onResponseStart();\n }\n if (!thrown) {\n await progress(responseTime, totalDownloaded, onResponseProgress);\n }\n if (thrown) {\n onAbortError({\n status: adapter.systemErrorStatus,\n extra: adapter.systemErrorExtra,\n });\n } else if (success || (error && data)) {\n onSuccess({\n data,\n error,\n status: status as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n } else {\n onError({\n error,\n status: status as ExtractAdapterStatusType<T>,\n extra: extra as ExtractAdapterExtraType<T>,\n });\n }\n if (!thrown) {\n onResponseEnd();\n }\n};\n","import type { ResponseSuccessType, ResponseErrorType, ProgressDataType, AdapterInstance } from \"adapter\";\nimport { getErrorMessage, RequestProcessingError } from \"adapter\";\nimport type { LoggerMethods } from \"managers\";\nimport type { RequestInstance, ProgressEventType } from \"request\";\nimport { getProgressData, scopeKey } from \"request\";\nimport type {\n ExtractResponseType,\n ExtractErrorType,\n ExtractPayloadType,\n ExtractAdapterOptionsType,\n ExtractAdapterStatusType,\n ExtractAdapterExtraType,\n} from \"types\";\n\nexport const getAdapterBindings = async <T extends AdapterInstance>({\n request: baseRequest,\n requestId,\n resolve,\n onStartTime,\n internalErrorMapping,\n}: {\n request: RequestInstance;\n requestId: string;\n resolve: (value: ResponseSuccessType<any, T> | ResponseErrorType<any, T>) => void;\n onStartTime: (timestamp: number) => void;\n internalErrorMapping: (error: ReturnType<typeof getErrorMessage>) => any;\n}) => {\n const { requestManager, loggerManager } = baseRequest.client;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { unstable_payloadMapper } = baseRequest.client.adapter;\n\n const logger = loggerManager.initialize(baseRequest.client, \"Adapter\");\n\n let requestStartTimestamp: null | number = null;\n let responseStartTimestamp: null | number = null;\n let request = baseRequest;\n\n // Progress\n let requestTotal = 1;\n let responseTotal = 1;\n let previousRequestTotal = 0;\n let previousResponseTotal = 0;\n\n // Pre request modifications\n logger.debug({\n title: `Running middleware callbacks`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n\n request = await request.client.unstable_modifyRequest(request);\n\n if (request.auth) {\n request = await request.client.unstable_modifyAuth(request);\n }\n\n if (request.unstable_requestMapper) {\n request = await request.unstable_requestMapper(request, requestId);\n }\n\n // Request Setup\n const { client, abortKey } = request;\n const scopedAbortKey = scopeKey(abortKey, request.scope);\n\n // eslint-disable-next-line prefer-destructuring\n let payload = request.payload;\n\n if (request.unstable_payloadMapper) {\n payload = await request.unstable_payloadMapper<ExtractPayloadType<RequestInstance>>(request.payload);\n } else if (unstable_payloadMapper) {\n payload = await unstable_payloadMapper(payload);\n }\n\n const adapterOptions = request.options as ExtractAdapterOptionsType<T> | undefined;\n const startTime = Date.now();\n onStartTime(startTime);\n\n const getRequestStartTimestamp = () => {\n return requestStartTimestamp;\n };\n\n const getResponseStartTimestamp = () => {\n return responseStartTimestamp;\n };\n\n // Progress\n\n const getTotal = (previousTotal: number, progress?: ProgressDataType) => {\n if (!progress) {return previousTotal;}\n const total = Number(progress.total || 0);\n const loaded = Number(progress.loaded || 0);\n return Math.max(total, loaded, previousTotal);\n };\n\n const handleRequestProgress = (\n startTimestamp: number,\n progressTimestamp: number,\n progressEvent: ProgressEventType,\n ) => {\n const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);\n\n if (previousRequestTotal !== 100) {\n previousRequestTotal = progress.total;\n requestManager.events.emitUploadProgress({ ...progress, requestId, request });\n }\n };\n\n const handleResponseProgress = (\n startTimestamp: number,\n progressTimestamp: number,\n progressEvent: ProgressEventType,\n ) => {\n const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);\n\n if (previousResponseTotal !== 100) {\n previousResponseTotal = progress.total;\n requestManager.events.emitDownloadProgress({ ...progress, requestId, request });\n }\n };\n\n // Pre-request\n\n const onBeforeRequest = () => {\n logger.debug({\n title: `Request about to be sent`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n client.triggerPlugins(\"onRequestTrigger\", { request });\n };\n\n // Request\n\n const onRequestStart = (progress?: ProgressDataType) => {\n logger.info({\n title: `Request start`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n client.triggerPlugins(\"onRequestStart\", { request });\n\n if (progress?.total) {\n requestTotal = getTotal(requestTotal, progress);\n }\n\n const initialPayload = {\n total: requestTotal,\n loaded: progress?.loaded || 0,\n };\n requestStartTimestamp = Date.now();\n handleRequestProgress(requestStartTimestamp, requestStartTimestamp, initialPayload);\n requestManager.events.emitRequestStart({ requestId, request });\n return requestStartTimestamp;\n };\n\n const onRequestProgress = (progress: ProgressDataType) => {\n if (!requestStartTimestamp) {\n requestStartTimestamp = Date.now();\n }\n requestTotal = getTotal(requestTotal, progress);\n\n const progressTimestamp = Date.now();\n\n handleRequestProgress(requestStartTimestamp, progressTimestamp, {\n total: requestTotal,\n loaded: progress.loaded || 0,\n });\n return progressTimestamp;\n };\n\n const onRequestEnd = () => {\n if (!requestStartTimestamp) {\n requestStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n handleRequestProgress(requestStartTimestamp, progressTimestamp, {\n total: requestTotal,\n loaded: requestTotal,\n });\n return progressTimestamp;\n };\n\n // Response\n\n const onResponseStart = (progress?: ProgressDataType) => {\n responseStartTimestamp = Date.now();\n\n responseTotal = getTotal(responseTotal, progress);\n\n const initialPayload = {\n total: responseTotal,\n loaded: progress?.loaded || 0,\n };\n\n handleResponseProgress(responseStartTimestamp, responseStartTimestamp, initialPayload);\n requestManager.events.emitResponseStart({ requestId, request });\n return responseStartTimestamp;\n };\n\n const onResponseProgress = (progress: ProgressDataType) => {\n if (!responseStartTimestamp) {\n responseStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n responseTotal = getTotal(responseTotal, progress);\n\n handleResponseProgress(responseStartTimestamp, progressTimestamp, {\n total: progress.total || responseTotal,\n loaded: progress.loaded || 0,\n });\n return progressTimestamp;\n };\n\n const onResponseEnd = () => {\n if (!responseStartTimestamp) {\n responseStartTimestamp = Date.now();\n }\n\n const progressTimestamp = Date.now();\n handleResponseProgress(responseStartTimestamp, progressTimestamp, {\n total: responseTotal,\n loaded: responseTotal,\n });\n return progressTimestamp;\n };\n\n // Success\n\n const onSuccess = async ({\n data,\n error,\n status,\n extra,\n }: {\n data: any;\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n error?: ExtractErrorType<T>;\n }): Promise<ResponseSuccessType<ExtractResponseType<T>, T>> => {\n let response: ResponseSuccessType<ExtractResponseType<T>, T> = {\n data,\n error: error ?? null,\n success: true,\n status,\n extra,\n requestTimestamp: startTime,\n responseTimestamp: Date.now(),\n };\n response = (await request.client.unstable_modifyResponse?.(response, request)) as typeof data;\n response = (await request.client.unstable_modifySuccessResponse?.(response, request)) as typeof data;\n\n client.triggerPlugins(\"onRequestSuccess\", { response, request });\n client.triggerPlugins(\"onRequestFinished\", { response, request });\n\n resolve(response);\n\n logger.info({\n title: `Response success`,\n type: \"response\",\n extra: {\n request,\n requestId,\n response,\n },\n });\n return response;\n };\n\n // Errors\n\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n const onError = getAdapterOnError({\n request,\n requestId,\n startTime,\n logger,\n resolve,\n });\n\n const onAbortError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Abort error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = internalErrorMapping(getErrorMessage(\"abort\"));\n return onError({ error, status, extra });\n };\n\n const onTimeoutError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Timeout error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = getErrorMessage(\"timeout\");\n return onError({ error, status, extra });\n };\n\n const onUnexpectedError = ({\n status,\n extra,\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }) => {\n logger.error({\n title: `Unexpected error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n },\n });\n const error = getErrorMessage();\n return onError({ error, status, extra });\n };\n\n // Abort\n\n const getAbortController = () => {\n return requestManager.getAbortController(scopedAbortKey, requestId);\n };\n\n const createAbortListener = ({\n status,\n extra,\n onAbort = () => {},\n }: {\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n onAbort?: () => void;\n }) => {\n const controller = getAbortController();\n if (!controller) {\n throw new RequestProcessingError(\"Controller is not found\");\n }\n\n const abort = () => {\n onAbortError({ status, extra });\n onAbort();\n requestManager.events.emitAbort({ requestId, request });\n };\n\n // Instant abort when we stack many requests triggered at once, and we receive aborted controller\n if (controller.signal.aborted) {\n abort();\n }\n\n // Abort during the request\n controller.signal.addEventListener(\"abort\", abort);\n\n return () => controller.signal.removeEventListener(\"abort\", abort);\n };\n\n logger.debug({\n title: `Mounted adapter bindings`,\n type: \"request\",\n extra: {\n request,\n requestId,\n payload,\n adapterOptions,\n },\n });\n\n const queryParams = baseRequest.client.adapter.unstable_queryParamsMapper(request.queryParams);\n const endpoint = baseRequest.client.adapter.unstable_endpointMapper(request.endpoint);\n const headers = baseRequest.client.adapter.unstable_headerMapper(request);\n const { url } = baseRequest.client;\n\n return {\n request,\n requestId,\n url,\n endpoint,\n queryParams,\n payload,\n headers,\n adapter: baseRequest.client.adapter,\n adapterOptions,\n getAbortController,\n getRequestStartTimestamp,\n getResponseStartTimestamp,\n createAbortListener,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onRequestEnd,\n onResponseStart,\n onResponseProgress,\n onResponseEnd,\n onSuccess,\n onAbortError,\n onTimeoutError,\n onUnexpectedError,\n onError,\n };\n};\n\nexport function getAdapterOnError<T extends AdapterInstance>({\n request,\n requestId,\n startTime,\n resolve,\n logger,\n}: {\n request: RequestInstance;\n requestId: string;\n startTime: number;\n logger: LoggerMethods;\n resolve: (value: ResponseSuccessType<any, T> | ResponseErrorType<any, T>) => void;\n}) {\n const { client } = request;\n\n return async ({\n error,\n status,\n extra,\n }: {\n error: any;\n status: ExtractAdapterStatusType<T>;\n extra: ExtractAdapterExtraType<T>;\n }): Promise<ResponseErrorType<any, T>> => {\n let response: ResponseErrorType<any, T> = {\n data: null,\n status,\n error,\n success: false,\n extra,\n requestTimestamp: startTime,\n responseTimestamp: Date.now(),\n };\n\n response = (await client.unstable_modifyResponse(response, request)) as typeof response;\n response = (await client.unstable_modifyErrorResponse(response, request)) as typeof response;\n\n client.triggerPlugins(\"onRequestError\", { response, request });\n client.triggerPlugins(\"onRequestFinished\", { response, request });\n\n resolve(response);\n\n logger.error({\n title: `Request error`,\n type: \"request\",\n extra: {\n request,\n requestId,\n response,\n },\n });\n\n return response;\n };\n}\n","import type { RequestInstance } from \"request\";\n\nexport const getUniqueRequestId = (request: Pick<RequestInstance, \"queryKey\">) => {\n return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","import Emitter from \"events\";\n\nconst getListenName = (event: string | symbol) => `listen_${String(event)}`;\n\nexport class EventEmitter extends Emitter {\n emitCallbacks: ((event: string, data: any, isTriggeredExternally?: true) => void)[] = [];\n\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(options?: ConstructorParameters<typeof Emitter>[0]) {\n super(options);\n }\n\n emit(type: string, data: any, isTriggeredExternally: boolean) {\n const params: [string, any, true?] = [type, data];\n\n if (isTriggeredExternally) {\n params.push(isTriggeredExternally);\n }\n\n this.emitCallbacks?.forEach((callback) => callback(...params));\n return super.emit(...params);\n }\n\n onEmit = (callback: (event: string, data: any, isTriggeredExternally?: true) => void) => {\n this.emitCallbacks?.push(callback);\n return () => {\n this.emitCallbacks = this.emitCallbacks?.filter((cb) => cb !== callback);\n };\n };\n\n onListener = (event: string, listener: (count: number) => void) => {\n super.on(getListenName(event), listener);\n return () => {\n super.off(getListenName(event), listener);\n };\n };\n\n on = (event: string | symbol, listener: (...args: any[]) => void) => {\n super.on(event, listener);\n super.emit(getListenName(event), super.listeners(event).length);\n return this;\n };\n\n off = (event: string | symbol, listener: (...args: any[]) => void) => {\n super.off(event, listener);\n super.emit(getListenName(event), super.listeners(event).length);\n return this;\n };\n\n addListener = this.on;\n removeListener = this.off;\n}\n","import type { AppManagerOptionsType } from \"managers\";\nimport { appManagerInitialOptions, getAppManagerEvents, hasDocument } from \"managers\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * App manager handles main application states - focus and online. Those two values can answer questions:\n * - Is the tab or current view instance focused and visible for user?\n * - Is our application online or offline?\n * With the app manager it is not a problem to get the valid answer for this question.\n *\n * @caution\n * Make sure to apply valid focus/online handlers for different environments like for example for native mobile applications.\n */\nexport class AppManager {\n emitter = new EventEmitter();\n events = getAppManagerEvents(this.emitter);\n\n isBrowser: boolean;\n isOnline: boolean;\n isFocused: boolean;\n\n private unmountCallbacks: VoidFunction[] = [];\n\n constructor(public options?: AppManagerOptionsType) {\n this.emitter?.setMaxListeners(1000);\n const {\n initiallyFocused = appManagerInitialOptions.initiallyFocused,\n initiallyOnline = appManagerInitialOptions.initiallyOnline,\n } = this.options || appManagerInitialOptions;\n\n this.setInitialFocus(initiallyFocused);\n this.setInitialOnline(initiallyOnline);\n\n this.isBrowser = hasDocument();\n }\n\n /**\n * Subscribes to the environment focus and network changes. Calling it again replaces the previous subscriptions,\n * so the listeners are never registered twice.\n */\n initialize = () => {\n const { focusEvent = appManagerInitialOptions.focusEvent, onlineEvent = appManagerInitialOptions.onlineEvent } =\n this.options || appManagerInitialOptions;\n\n this.unmount();\n\n [focusEvent(this.setFocused), onlineEvent(this.setOnline)].forEach((unmount) => {\n if (typeof unmount === \"function\") {\n this.unmountCallbacks.push(unmount);\n }\n });\n };\n\n /**\n * Removes the environment listeners registered by `initialize()`. Listeners added with `events` are kept.\n */\n unmount = () => {\n const callbacks = this.unmountCallbacks;\n this.unmountCallbacks = [];\n callbacks.forEach((unmount) => unmount());\n };\n\n private setInitialFocus = async (initValue: Exclude<AppManagerOptionsType[\"initiallyFocused\"], undefined>) => {\n if (typeof initValue !== \"function\") {\n this.isFocused = initValue;\n return;\n }\n\n // Synchronous getters apply right away, so there is no moment with a wrong value\n const value = initValue();\n if (typeof value === \"boolean\") {\n this.isFocused = value;\n } else {\n this.isFocused = false;\n this.isFocused = await value;\n }\n };\n\n private setInitialOnline = async (initValue: Exclude<AppManagerOptionsType[\"initiallyOnline\"], undefined>) => {\n if (typeof initValue !== \"function\") {\n this.isOnline = initValue;\n return;\n }\n\n // Synchronous getters apply right away, so there is no moment with a wrong value\n const value = initValue();\n if (typeof value === \"boolean\") {\n this.isOnline = value;\n } else {\n this.isOnline = false;\n this.isOnline = await value;\n }\n };\n\n setFocused = (isFocused: boolean) => {\n this.isFocused = isFocused;\n\n if (isFocused) {\n this.events.emitFocus();\n } else {\n this.events.emitBlur();\n }\n };\n\n setOnline = (isOnline: boolean) => {\n this.isOnline = isOnline;\n\n if (isOnline) {\n this.events.emitOnline();\n } else {\n this.events.emitOffline();\n }\n };\n}\n","export const hasWindow = () => {\n try {\n return Boolean(window && window.addEventListener);\n } catch {\n /* istanbul ignore next */\n return false;\n }\n};\n\nexport const hasDocument = () => {\n try {\n return Boolean(hasWindow() && window.document && window.document.addEventListener);\n } catch {\n /* istanbul ignore next */\n return false;\n }\n};\n\n/**\n * Reads the current network state from the browser. Falls back to `true` when it is unknown - e.g. in Node.js or\n * React Native, where `navigator.onLine` is not available.\n */\nexport const isNavigatorOnline = () => {\n try {\n return typeof navigator.onLine === \"boolean\" ? navigator.onLine : true;\n } catch {\n /* istanbul ignore next */\n return true;\n }\n};\n\nexport const onWindowEvent = <K extends keyof WindowEventMap>(\n key: K,\n listener: (this: Window, ev: WindowEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions | undefined,\n): VoidFunction => {\n /* istanbul ignore next */\n if (hasWindow()) {\n window.addEventListener(key, listener, options);\n return () => window.removeEventListener(key, listener, options);\n }\n /* istanbul ignore next */\n return () => null;\n};\n\nexport const onDocumentEvent = <K extends keyof DocumentEventMap>(\n key: K,\n listener: (this: Document, ev: DocumentEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions | undefined,\n): VoidFunction => {\n /* istanbul ignore next */\n if (hasDocument()) {\n window.document.addEventListener(key, listener, options);\n return () => window.document.removeEventListener(key, listener, options);\n }\n /* istanbul ignore next */\n return () => null;\n};\n","import type EventEmitter from \"events\";\nimport { AppEvents } from \"managers\";\n\n/** Create event emitters and listeners for application-level focus, blur, online, and offline state changes. */\nexport const getAppManagerEvents = (emitter: EventEmitter) => ({\n /** Emit when the application window gains focus */\n emitFocus: (): void => {\n emitter.emit(AppEvents.FOCUS);\n },\n /** Emit when the application window loses focus */\n emitBlur: (): void => {\n emitter.emit(AppEvents.BLUR);\n },\n /** Emit when the application transitions to online state */\n emitOnline: (): void => {\n emitter.emit(AppEvents.ONLINE);\n },\n /** Emit when the application transitions to offline state */\n emitOffline: (): void => {\n emitter.emit(AppEvents.OFFLINE);\n },\n /** Listen for focus events */\n onFocus: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.FOCUS, callback);\n return () => emitter.removeListener(AppEvents.FOCUS, callback);\n },\n /** Listen for blur events */\n onBlur: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.BLUR, callback);\n return () => emitter.removeListener(AppEvents.BLUR, callback);\n },\n /** Listen for online state transitions */\n onOnline: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.ONLINE, callback);\n return () => emitter.removeListener(AppEvents.ONLINE, callback);\n },\n /** Listen for offline state transitions */\n onOffline: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.OFFLINE, callback);\n return () => emitter.removeListener(AppEvents.OFFLINE, callback);\n },\n});\n","import type { AppManagerOptionsType } from \"managers\";\nimport type { RequiredKeys } from \"types\";\n\nimport { onWindowEvent, onDocumentEvent, isNavigatorOnline } from \"./app.manager.utils\";\n\nexport enum AppEvents {\n FOCUS = \"focus\",\n BLUR = \"blur\",\n ONLINE = \"online\",\n OFFLINE = \"offline\",\n}\n\nexport const appManagerInitialOptions: RequiredKeys<AppManagerOptionsType> = {\n initiallyFocused: true,\n initiallyOnline: isNavigatorOnline,\n focusEvent: (setFocused) => {\n const unmountVisibility = onDocumentEvent(\"visibilitychange\", () => setFocused(true));\n const unmountFocus = onWindowEvent(\"focus\", () => setFocused(true));\n const unmountBlur = onWindowEvent(\"blur\", () => setFocused(false));\n\n return () => {\n unmountVisibility();\n unmountFocus();\n unmountBlur();\n };\n },\n onlineEvent: (setOnline) => {\n const unmountOnline = onWindowEvent(\"online\", () => setOnline(true));\n const unmountOffline = onWindowEvent(\"offline\", () => setOnline(false));\n\n return () => {\n unmountOnline();\n unmountOffline();\n };\n },\n};\n","import { getRequestManagerEvents } from \"managers\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * **Request Manager** is used to emit `request lifecycle events` like - request start, request end, upload and download progress.\n * It is also the place of `request aborting` system, here we store all the keys and controllers that are isolated for each client instance.\n */\nexport class RequestManager {\n emitter = new EventEmitter();\n events = getRequestManagerEvents(this.emitter);\n\n constructor() {\n this.emitter?.setMaxListeners(1000);\n }\n\n abortControllers = new Map<string, Map<string, AbortController>>();\n\n addAbortController = (abortKey: string, requestId: string) => {\n let abortGroup = this.abortControllers.get(abortKey);\n if (!abortGroup) {\n const newAbortGroup = new Map();\n abortGroup = newAbortGroup;\n this.abortControllers.set(abortKey, newAbortGroup);\n }\n\n const abortController = abortGroup.get(requestId);\n if (!abortController || abortController.signal.aborted) {\n abortGroup.set(requestId, new AbortController());\n }\n };\n\n getAbortController = (abortKey: string, requestId: string) => {\n return this.abortControllers.get(abortKey)?.get(requestId);\n };\n\n removeAbortController = (abortKey: string, requestId: string) => {\n this.abortControllers.get(abortKey)?.delete(requestId);\n };\n\n // Aborting\n\n useAbortController = (abortKey: string, requestId: string) => {\n const controller = this.abortControllers.get(abortKey)?.get(requestId);\n controller?.abort();\n };\n\n abortByKey = (abortKey: string) => {\n const controllers = this.abortControllers.get(abortKey);\n\n if (controllers) {\n const entries = [...controllers.entries()];\n entries.forEach(([key]) => {\n this.useAbortController(abortKey, key);\n });\n }\n };\n\n abortByRequestId = (abortKey: string, requestId: string) => {\n this.useAbortController(abortKey, requestId);\n };\n\n abortAll = () => {\n const entries = [...this.abortControllers.entries()];\n entries.forEach(([abortKey, value]) => {\n const controllers = [...value.entries()];\n controllers.forEach(([requestId]) => {\n this.useAbortController(abortKey, requestId);\n });\n });\n };\n}\n","// Events\n\nexport const getLoadingKey = (): string => `loading-event-any`;\nexport const getLoadingByQueryKey = (queryKey: string): string => `${queryKey}-loading-event`;\nexport const getLoadingByCacheKey = (cacheKey: string): string => `${cacheKey}-loading-cache-event`;\nexport const getLoadingByIdKey = (id: string): string => `${id}-loading-event-by-id`;\nexport const getRemoveKey = (): string => `remove-event-any`;\nexport const getRemoveByQueryKey = (queryKey: string): string => `${queryKey}-remove-event`;\nexport const getRemoveByIdKey = (id: string): string => `${id}-remove-event-by-id`;\nexport const getAbortKey = () => `request-abort-any`;\nexport const getAbortByAbortKey = (abortKey: string) => `${abortKey}-request-abort`;\nexport const getAbortByIdKey = (id: string) => `${id}-request-abort-by-id`;\nexport const getResponseKey = () => `response-any`;\nexport const getResponseByCacheKey = (cacheKey: string) => `${cacheKey}-response`;\nexport const getResponseByIdKey = (id: string) => `${id}-response-by-id`;\nexport const getRequestStartKey = () => `request-start-any`;\nexport const getRequestStarByQueryKey = (queryKey: string) => `${queryKey}-request-start`;\nexport const getRequestStartByIdKey = (id: string) => `${id}-request-start-by-id`;\nexport const getResponseStartKey = () => `response-start-any`;\nexport const getResponseStartByQueryKey = (queryKey: string) => `${queryKey}-response-start`;\nexport const getResponseStartByIdKey = (id: string) => `${id}-response-start-by-id`;\nexport const getUploadProgressKey = () => `request-progress-any`;\nexport const getUploadProgressByQueryKey = (queryKey: string) => `${queryKey}-request-progress`;\nexport const getUploadProgressByIdKey = (id: string) => `${id}-request-progress-by-id`;\nexport const getDownloadProgressKey = () => `response-progress-any`;\nexport const getDownloadProgressByQueryKey = (queryKey: string) => `${queryKey}-response-progress`;\nexport const getDownloadProgressByIdKey = (id: string) => `${id}-response-progress-by-id`;\nexport const getRequestDeduplicatedKey = () => `request-deduplicated-any`;\nexport const getRequestDeduplicatedByQueryKey = (queryKey: string) => `${queryKey}-query-request-deduplicated`;\nexport const getRequestDeduplicatedByCacheKey = (cacheKey: string) => `${cacheKey}-cache-request-deduplicated`;\nexport const getRequestDeduplicatedByIdKey = (id: string) => `${id}-request-deduplicated-by-id`;\n","import type { AdapterInstance } from \"adapter\";\nimport type { Client } from \"client\";\n/* eslint-disable max-params */\nimport type EventEmitter from \"events\";\nimport type {\n RequestEventType,\n RequestLoadingEventType,\n RequestProgressEventType,\n RequestResponseEventType,\n RequestRemovedEventType,\n RequestDeduplicatedEventType,\n} from \"managers\";\nimport {\n getRequestStarByQueryKey,\n getResponseStartByQueryKey,\n getDownloadProgressByQueryKey,\n getUploadProgressByQueryKey,\n getResponseByIdKey,\n getAbortByAbortKey,\n getAbortByIdKey,\n getResponseByCacheKey,\n getUploadProgressByIdKey,\n getDownloadProgressByIdKey,\n getResponseStartByIdKey,\n getRequestStartByIdKey,\n getLoadingByQueryKey,\n getLoadingByIdKey,\n getRemoveByQueryKey,\n getRemoveByIdKey,\n getLoadingKey,\n getRequestStartKey,\n getUploadProgressKey,\n getDownloadProgressKey,\n getResponseKey,\n getAbortKey,\n getRemoveKey,\n getResponseStartKey,\n getLoadingByCacheKey,\n getRequestDeduplicatedKey,\n getRequestDeduplicatedByIdKey,\n getRequestDeduplicatedByCacheKey,\n getRequestDeduplicatedByQueryKey,\n} from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtendRequest } from \"types\";\n\n/** Create event emitters and listeners for the request lifecycle: loading, progress, response, abort, deduplication, and removal. */\nexport const getRequestManagerEvents = (emitter: EventEmitter) => ({\n /**\n * Emitters\n */\n\n /** Emit when a request is deduplicated (skipped because an identical one is in-flight) */\n emitDeduplicated: (data: RequestDeduplicatedEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRequestDeduplicatedKey(), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n emitter.emit(getRequestDeduplicatedByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit loading state changes for a request */\n emitLoading: (data: RequestLoadingEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getLoadingKey(), data, isTriggeredExternally);\n emitter.emit(getLoadingByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getLoadingByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n emitter.emit(getLoadingByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request starts being sent */\n emitRequestStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRequestStartKey(), data, isTriggeredExternally);\n emitter.emit(getRequestStartByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRequestStarByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n /** Emit when the response starts being received */\n emitResponseStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getResponseStartKey(), data, isTriggeredExternally);\n emitter.emit(getResponseStartByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getResponseStartByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit upload progress updates */\n emitUploadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getUploadProgressKey(), data, isTriggeredExternally);\n emitter.emit(getUploadProgressByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getUploadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n /** Emit download progress updates */\n emitDownloadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getDownloadProgressKey(), data, isTriggeredExternally);\n emitter.emit(getDownloadProgressByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getDownloadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /** Emit when a response is received */\n emitResponse: <Adapter extends AdapterInstance>(\n data: RequestResponseEventType<ExtendRequest<RequestInstance, { client: Client<any, Adapter> }>>,\n isTriggeredExternally = false,\n ): void => {\n emitter.emit(getResponseKey(), data, isTriggeredExternally);\n emitter.emit(getResponseByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getResponseByCacheKey(data.request.cacheKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request is aborted */\n emitAbort: (data: RequestEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getAbortKey(), data, isTriggeredExternally);\n emitter.emit(getAbortByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getAbortByAbortKey(data.request.abortKey), data, isTriggeredExternally);\n },\n\n /** Emit when a request is removed from the dispatcher queue */\n emitRemove: (data: RequestRemovedEventType<RequestInstance>, isTriggeredExternally = false): void => {\n emitter.emit(getRemoveKey(), data, isTriggeredExternally);\n emitter.emit(getRemoveByIdKey(data.requestId), data, isTriggeredExternally);\n emitter.emit(getRemoveByQueryKey(data.request.queryKey), data, isTriggeredExternally);\n },\n\n /**\n * Listeners\n */\n\n /** Listen for deduplicated request events */\n onDeduplicated: <T extends RequestInstance>(\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedKey(), callback);\n return () => emitter.removeListener(getRequestDeduplicatedKey(), callback);\n },\n onDeduplicatedByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByQueryKey(queryKey), callback);\n },\n onDeduplicatedByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByCacheKey(cacheKey), callback);\n },\n onDeduplicatedById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestDeduplicatedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestDeduplicatedByIdKey(requestId), callback);\n return () => emitter.removeListener(getRequestDeduplicatedByIdKey(requestId), callback);\n },\n\n // Loading\n onLoading: <T extends RequestInstance>(callback: (data: RequestLoadingEventType<T>) => void): VoidFunction => {\n emitter.on(getLoadingKey(), callback);\n return () => emitter.removeListener(getLoadingKey(), callback);\n },\n onLoadingByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getLoadingByQueryKey(queryKey), callback);\n },\n onLoadingByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getLoadingByCacheKey(cacheKey), callback);\n },\n onLoadingById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestLoadingEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getLoadingByIdKey(requestId), callback);\n return () => emitter.removeListener(getLoadingByIdKey(requestId), callback);\n },\n\n // Request Start\n onRequestStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void): VoidFunction => {\n emitter.on(getRequestStartKey(), callback);\n return () => emitter.removeListener(getRequestStartKey(), callback);\n },\n onRequestStartByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestStarByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRequestStarByQueryKey(queryKey), callback);\n },\n onRequestStartById: <T extends RequestInstance>(\n requestId: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestStartByIdKey(requestId), callback);\n return () => emitter.removeListener(getRequestStartByIdKey(requestId), callback);\n },\n\n // Response Start\n onResponseStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void): VoidFunction => {\n emitter.on(getResponseStartKey(), callback);\n return () => emitter.removeListener(getResponseStartKey(), callback);\n },\n onResponseStartByQueue: <T extends RequestInstance>(\n queryKey: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseStartByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getResponseStartByQueryKey(queryKey), callback);\n },\n onResponseStartById: <T extends RequestInstance>(\n requestId: string,\n callback: (details: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseStartByIdKey(requestId), callback);\n return () => emitter.removeListener(getResponseStartByIdKey(requestId), callback);\n },\n\n // Progress\n onUploadProgress: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressKey(), callback);\n return () => emitter.removeListener(getUploadProgressKey(), callback);\n },\n onUploadProgressByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getUploadProgressByQueryKey(queryKey), callback);\n },\n onUploadProgressById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressByIdKey(requestId), callback);\n return () => emitter.removeListener(getUploadProgressByIdKey(requestId), callback);\n },\n\n onDownloadProgress: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressKey(), callback);\n return () => emitter.removeListener(getDownloadProgressKey(), callback);\n },\n onDownloadProgressByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getDownloadProgressByQueryKey(queryKey), callback);\n },\n onDownloadProgressById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestProgressEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressByIdKey(requestId), callback);\n return () => emitter.removeListener(getDownloadProgressByIdKey(requestId), callback);\n },\n\n // Response\n onResponse: <T extends RequestInstance>(callback: (data: RequestResponseEventType<T>) => void): VoidFunction => {\n emitter.on(getResponseKey(), callback);\n return () => emitter.removeListener(getResponseKey(), callback);\n },\n onResponseByCache: <T extends RequestInstance>(\n cacheKey: string,\n callback: (data: RequestResponseEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseByCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getResponseByCacheKey(cacheKey), callback);\n },\n onResponseById: <T extends RequestInstance>(\n requestId: string,\n callback: (data: RequestResponseEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseByIdKey(requestId), callback);\n return () => emitter.removeListener(getResponseByIdKey(requestId), callback);\n },\n\n // Abort\n onAbort: <T extends RequestInstance = RequestInstance>(\n callback: (request: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortKey(), callback);\n return () => emitter.removeListener(getAbortKey(), callback);\n },\n onAbortByKey: <T extends RequestInstance = RequestInstance>(\n abortKey: string,\n callback: (request: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortByAbortKey(abortKey), callback);\n return () => emitter.removeListener(getAbortByAbortKey(abortKey), callback);\n },\n onAbortById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getAbortByIdKey(requestId), callback);\n return () => emitter.removeListener(getAbortByIdKey(requestId), callback);\n },\n\n // Remove\n onRemove: <T extends RequestInstance = RequestInstance>(\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveKey(), callback);\n return () => emitter.removeListener(getRemoveKey(), callback);\n },\n onRemoveByQueue: <T extends RequestInstance = RequestInstance>(\n queryKey: string,\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveByQueryKey(queryKey), callback);\n return () => emitter.removeListener(getRemoveByQueryKey(queryKey), callback);\n },\n onRemoveById: <T extends RequestInstance = RequestInstance>(\n requestId: string,\n callback: (data: RequestRemovedEventType<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveByIdKey(requestId), callback);\n return () => emitter.removeListener(getRemoveByIdKey(requestId), callback);\n },\n});\n","import type { ClientInstance } from \"client\";\nimport EventEmitter from \"events\";\nimport type { LogLevel, LoggerOptionsType, LoggerType, LoggerMethods } from \"managers\";\nimport { logger, logLevelOrder } from \"managers\";\n\n/**\n * This class is used across the Hyper Fetch library to provide unified logging system with necessary setup per each client.\n * We can set up the logging level based on available values. This manager enable to initialize the logging instance per individual module\n * like Client, Request etc. Which can give you better feedback on the logging itself.\n */\nexport class LoggerManager {\n logger: LoggerType;\n level: LogLevel;\n modules: string[] | undefined;\n\n public emitter = new EventEmitter();\n\n private client: Pick<ClientInstance, \"debug\">;\n\n constructor(private options?: LoggerOptionsType) {\n this.emitter?.setMaxListeners(1000);\n this.logger = this.options?.logger || logger;\n this.level = this.options?.level || \"warning\";\n this.modules = this.options?.modules;\n }\n\n setSeverity = (level: LogLevel) => {\n this.level = level;\n };\n\n setModules = (modules: string[] | undefined) => {\n this.modules = modules;\n };\n\n initialize = (client: Pick<ClientInstance, \"debug\">, module: string): LoggerMethods => {\n this.client = client;\n\n return {\n error: (data) => this.log({ ...data, level: \"error\", module }),\n warning: (data) => this.log({ ...data, level: \"warning\", module }),\n info: (data) => this.log({ ...data, level: \"info\", module }),\n debug: (data) => this.log({ ...data, level: \"debug\", module }),\n };\n };\n\n private log: LoggerType = (data) => {\n if (!this.client.debug) {\n return;\n }\n if (logLevelOrder.indexOf(this.level) <= logLevelOrder.indexOf(data.level)) {\n return;\n }\n if (this.modules && !this.modules.includes(data.module)) {\n return;\n }\n this.logger(data);\n };\n}\n","/* eslint-disable no-console */\nimport type { LoggerType } from \"managers\";\nimport { loggerColors, loggerStyles } from \"managers\";\n\nexport const getTime = () => {\n const d = new Date();\n return `${d.toLocaleTimeString()}`;\n};\n\nconst getModuleName = (data: Parameters<LoggerType>[0]) => {\n if (data.type === \"request\" || data.type === \"response\") {\n return `${data.extra.request.endpoint}`;\n }\n return `[${data.module}]`;\n};\n\n// Logger\nexport const logger: LoggerType = (log) => {\n const styles = loggerStyles[log.level];\n const color = loggerColors[log.level];\n const message = `%c[${getTime()}]%c${log.title}%c${getModuleName(log)}`;\n\n const style1 = `${styles}${color}font-weight:600;border-radius: 4px 0 0 4px;`;\n const style2 = `${styles}${color}font-weight:600;`;\n const style3 = `${styles}font-weight:normal;border-radius: 0 4px 4px 0;`;\n\n if (log.extra ? Object.keys(log.extra)?.length : false) {\n console.groupCollapsed(message, style1, style2, style3);\n console.log(log.extra);\n console.groupEnd();\n } else {\n console.log(message, styles);\n }\n};\n","import type { LogLevel } from \"./logger.manager.types\";\n\nexport const logLevelOrder: LogLevel[] = [\"error\", \"warning\", \"info\", \"debug\"];\n\nconst defaultStyles = \"padding:2px 5px;\";\n\nexport const loggerStyles: Record<LogLevel, string> = {\n error: `${defaultStyles};background:#db252520;`,\n warning: `${defaultStyles};background:#e1941e20;`,\n info: `${defaultStyles};background:#1e74e120;`,\n debug: `${defaultStyles};background:#00000020;`,\n};\n\nexport const loggerColors: Record<LogLevel, string> = {\n error: \"color:#ff3737;\",\n warning: \"color:#ffc107;\",\n info: \"color:#34a8ff;\",\n debug: \"color:#cccccc;\",\n};\n","/* eslint-disable max-classes-per-file */\n// Utils\nimport { hasWindow } from \"managers\";\nimport type { RequestInstance } from \"request\";\n\nexport class TimeoutError extends Error {\n constructor() {\n super(\"Request timeout\");\n this.name = \"TimeoutError\";\n }\n}\n\nexport class AbortError extends Error {\n constructor() {\n super(\"Request aborted\");\n this.name = \"AbortError\";\n }\n}\n\nexport class DeletedError extends Error {\n constructor() {\n super(\"Request deleted\");\n this.name = \"DeletedError\";\n }\n}\n\nexport class RequestProcessingError extends Error {\n description?: string = undefined;\n\n constructor(description?: string) {\n super(\"Request processing error\");\n this.description = description;\n this.name = \"RequestProcessingError\";\n }\n}\n\nexport class UnexpectedError extends Error {\n description?: string = undefined;\n\n constructor(description?: string) {\n super(\"Unexpected error\");\n this.description = description;\n this.name = \"UnexpectedError\";\n }\n}\n\nexport const getErrorMessage = (errorCase?: \"timeout\" | \"abort\" | \"deleted\" | \"processing\" | \"unexpected\") => {\n if (errorCase === \"timeout\") {\n return new TimeoutError();\n }\n if (errorCase === \"abort\") {\n return new AbortError();\n }\n if (errorCase === \"deleted\") {\n return new DeletedError();\n }\n if (errorCase === \"processing\") {\n return new RequestProcessingError();\n }\n return new UnexpectedError();\n};\n\n// Mappers\n\nexport const stringifyValue = (response: string | unknown): string => {\n try {\n return JSON.stringify(response as string);\n } catch {\n return \"\";\n }\n};\n\nexport const getAdapterHeaders = (request: RequestInstance) => {\n const isFormData = hasWindow() && request.payload instanceof FormData;\n const isObject = typeof request.payload === \"object\" && request.payload !== null;\n const headers: HeadersInit = {};\n\n if (!isFormData && isObject) {headers[\"Content-Type\"] = \"application/json\";}\n\n Object.assign(headers, request.headers);\n return headers as HeadersInit;\n};\n\nexport const getAdapterPayload = (data: unknown): string | FormData => {\n const isFormData = hasWindow() && data instanceof FormData;\n if (isFormData) {return data;}\n\n return stringifyValue(data);\n};\n","import type { Client, ClientInstance } from \"client\";\nimport type { LoggerMethods } from \"managers\";\nimport { mocker } from \"mocker\";\nimport type { RequestInstance, RequestOptionsType } from \"request\";\n/* eslint-disable class-methods-use-this */\nimport type { EmptyTypes, ExtendRequest } from \"types\";\n\nimport { getAdapterOnError, getAdapterBindings } from \"./adapter.bindings\";\nimport type {\n EndpointMapper,\n AdapterFetcherType,\n AdapterPayloadMappingType,\n HeaderMappingType,\n QueryParamsMapper,\n QueryParamsType,\n RequestResponseType,\n ResponseType,\n} from \"./adapter.types\";\nimport type { getErrorMessage } from \"./adapter.utils\";\nimport { getAdapterHeaders, getAdapterPayload, RequestProcessingError } from \"./adapter.utils\";\n\nexport type DefaultMapperType = <V, C = undefined>(value: V, config?: C) => V;\nexport const defaultMapper: DefaultMapperType = (value) => value;\n\n/**\n * Base adapter class responsible for executing HTTP requests. Adapters handle endpoint resolution,\n * header/payload/query-params mapping, and the actual fetch call. Extend or configure this class\n * to integrate custom transport layers (e.g., axios, graphql, firebase).\n */\nexport class Adapter<\n AdapterOptions,\n MethodType extends string,\n StatusType extends number | string,\n Extra extends Record<string, any>,\n QueryParams = QueryParamsType | string | EmptyTypes,\n DefaultQueryParams = undefined,\n EndpointType = string,\n EndpointMapperType extends EndpointMapper<EndpointType> | DefaultMapperType = DefaultMapperType,\n QueryParamsMapperType extends QueryParamsMapper<QueryParams> | DefaultMapperType = DefaultMapperType,\n HeaderMapperType extends HeaderMappingType | DefaultMapperType = DefaultMapperType,\n PayloadMapperType extends AdapterPayloadMappingType | DefaultMapperType = DefaultMapperType,\n RequestOptions extends Record<string, any> = {},\n> {\n /** Fetching function */\n public unstable_fetcher: AdapterFetcherType<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n\n /**\n * ********************\n * Defaults\n * ********************\n */\n\n public name: string;\n public defaultMethod: MethodType;\n public defaultExtra: Extra;\n public systemErrorStatus: StatusType;\n public systemErrorExtra: Extra;\n public defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType> = undefined;\n public logger: LoggerMethods;\n public initialized = false;\n public client: ClientInstance;\n\n public unstable_onInitializeCallback?: (options: { client: ClientInstance }) => void = undefined;\n\n public unstable_queryParamsMapperConfig: Parameters<QueryParamsMapperType>[1];\n public unstable_headerMapperConfig: Parameters<HeaderMapperType>[1];\n public unstable_payloadMapperConfig: Parameters<PayloadMapperType>[1];\n public unstable_endpointMapperConfig: Parameters<EndpointMapperType>[1];\n\n /**\n * Type-only carrier of the additional `createRequest` fields declared by this adapter.\n * It has no runtime value - adapters read those fields from `request.requestOptions`.\n */\n public unstable_requestOptionsType?: RequestOptions = undefined;\n\n constructor(\n public options: {\n name: string;\n defaultMethod: MethodType;\n defaultExtra: Extra;\n systemErrorStatus: StatusType;\n systemErrorExtra: Extra;\n defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType>;\n },\n ) {\n this.name = options.name;\n this.defaultMethod = options.defaultMethod;\n this.defaultExtra = options.defaultExtra;\n this.systemErrorStatus = options.systemErrorStatus;\n this.systemErrorExtra = options.systemErrorExtra;\n this.defaultRequestOptions = options.defaultRequestOptions;\n }\n\n /** Initialize the adapter with a client reference and set up logging. Called automatically when the client is created. */\n initialize = (client: ClientInstance) => {\n this.logger = client.loggerManager.initialize(client, \"Adapter\");\n this.initialized = true;\n this.client = client;\n\n this.unstable_onInitializeCallback?.({ client });\n return this;\n };\n\n /** Register a callback invoked once the adapter is initialized with a client. */\n onInitialize = (callback: (options: { client: ClientInstance }) => void) => {\n this.unstable_onInitializeCallback = callback;\n return this;\n };\n\n /**\n * ********************\n * Options Setters\n * ********************\n */\n\n public unstable_internalErrorMapping: (error: ReturnType<typeof getErrorMessage>) => any = (error) => error;\n /** Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats. */\n public unstable_headerMapper: HeaderMapperType = getAdapterHeaders as HeaderMapperType;\n /** Method to get request data and transform them to the required format. It handles FormData and JSON by default. */\n public unstable_payloadMapper: PayloadMapperType = getAdapterPayload as PayloadMapperType;\n /** Method to get the endpoint for the adapter request. */\n public unstable_endpointMapper: EndpointMapperType = defaultMapper as EndpointMapperType;\n /** Method to get request data and transform them to the required format. */\n public unstable_queryParamsMapper: QueryParamsMapperType = defaultMapper as QueryParamsMapperType;\n /** Get default adapter options for the request. */\n public unstable_getAdapterDefaults?: (\n request: ExtendRequest<\n RequestInstance,\n {\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n ) => AdapterOptions = undefined;\n /** Get default request options for the request. */\n public unstable_getRequestDefaults?: (\n options: RequestOptionsType<EndpointType, AdapterOptions, MethodType>,\n ) => Partial<RequestOptionsType<EndpointType, AdapterOptions, MethodType>> = undefined;\n /**\n * Get formatted endpoint name of the request.\n * Helpful in displaying long endpoints like in case of graphql schemas etc.\n */\n public unstable_devtoolsEndpointGetter: (endpoint: string, requestOptions?: Record<string, any>) => string = (\n endpoint,\n ) => endpoint;\n\n /**\n * ********************\n * Methods\n * ********************\n */\n\n /** Set the default HTTP method used when a request does not specify one. */\n setDefaultMethod = (method: MethodType) => {\n this.defaultMethod = method;\n return this;\n };\n\n /** Set the default extra metadata attached to every request response (e.g., headers, status). */\n setDefaultExtra = (extra: Extra) => {\n this.defaultExtra = extra;\n return this;\n };\n\n /** Set a function that formats the endpoint string for display in devtools. */\n setDevtoolsEndpointGetter = (callback: (endpoint: string, requestOptions?: Record<string, any>) => string) => {\n this.unstable_devtoolsEndpointGetter = callback;\n return this;\n };\n\n /**\n * This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.\n */\n setRequestDefaults = (callback: typeof this.unstable_getRequestDefaults): this => {\n this.unstable_getRequestDefaults = callback;\n return this;\n };\n\n /**\n * Set the adapter default options added to every sent request\n */\n setAdapterDefaults = (\n callback: (\n request: ExtendRequest<\n RequestInstance,\n {\n // No need for global error type, because we haven't sent the request yet\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n ) => AdapterOptions,\n ): this => {\n this.unstable_getAdapterDefaults = callback;\n return this;\n };\n\n /** Set a custom mapping for internal adapter errors before they are returned in the response. */\n setInternalErrorMapping = (callback: (error: ReturnType<typeof getErrorMessage>) => any) => {\n this.unstable_internalErrorMapping = callback;\n return this;\n };\n\n /**\n * Set the custom header mapping function\n */\n setHeaderMapper = <NewMapper extends HeaderMappingType>(headerMapper: NewMapper) => {\n this.unstable_headerMapper = ((req: Parameters<NewMapper>[0]) =>\n headerMapper(req, this.unstable_headerMapperConfig as Parameters<NewMapper>[1])) as unknown as HeaderMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n NewMapper,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /**\n * Set the request payload mapping function which gets triggered before request is send\n */\n setPayloadMapper = <NewMapper extends AdapterPayloadMappingType>(payloadMapper: NewMapper) => {\n this.unstable_payloadMapper = ((req: Parameters<NewMapper>[0]) =>\n payloadMapper(\n req,\n this.unstable_payloadMapperConfig as Parameters<NewMapper>[1],\n )) as unknown as PayloadMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n NewMapper,\n RequestOptions\n >;\n };\n\n /**\n * Set the endpoint mapping function which transforms the endpoint string before the request is sent\n */\n setEndpointMapper = <NewEndpointMapper extends EndpointMapper<EndpointType>>(endpointMapper: NewEndpointMapper) => {\n this.unstable_endpointMapper = ((endpoint: Parameters<NewEndpointMapper>[0]) =>\n endpointMapper(\n endpoint,\n this.unstable_endpointMapperConfig as Parameters<NewEndpointMapper>[1],\n )) as unknown as EndpointMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n NewEndpointMapper,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /**\n * Set the query params mapping function which get triggered before request get sent\n */\n setQueryParamsMapper = <NewQueryParamsMapper extends QueryParamsMapper<QueryParams>>(\n queryParamsMapper: NewQueryParamsMapper,\n ) => {\n this.unstable_queryParamsMapper = ((queryParams: Parameters<NewQueryParamsMapper>[0]) =>\n queryParamsMapper(\n queryParams,\n this.unstable_queryParamsMapperConfig as Parameters<NewQueryParamsMapper>[1],\n )) as unknown as QueryParamsMapperType;\n return this as unknown as Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n NewQueryParamsMapper,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >;\n };\n\n /** Set the configuration object passed as the second argument to the query params mapper. */\n setQueryParamsMapperConfig = <NewQueryParamsMapperConfig extends Parameters<QueryParamsMapperType>[1]>(\n config: NewQueryParamsMapperConfig,\n ) => {\n this.unstable_queryParamsMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the header mapper. */\n setHeaderMapperConfig = <NewHeaderMapperConfig extends Parameters<HeaderMapperType>[1]>(\n config: NewHeaderMapperConfig,\n ) => {\n this.unstable_headerMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the endpoint mapper. */\n setEndpointMapperConfig = <NewEndpointMapperConfig extends Parameters<EndpointMapperType>[1]>(\n config: NewEndpointMapperConfig,\n ) => {\n this.unstable_endpointMapperConfig = config;\n return this;\n };\n\n /** Set the configuration object passed as the second argument to the payload mapper. */\n setPayloadMapperConfig = <NewPayloadMapperConfig extends Parameters<PayloadMapperType>[1]>(\n config: NewPayloadMapperConfig,\n ) => {\n this.unstable_payloadMapperConfig = config;\n return this;\n };\n\n /**\n * ********************\n * Fetching\n * ********************\n */\n\n /** Set the fetcher function that performs the actual network request. Must be called before any request can be executed. */\n public setFetcher(\n fetcher: AdapterFetcherType<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >,\n ) {\n this.unstable_fetcher = fetcher.bind(this);\n return this;\n }\n\n /** Execute a request through the adapter pipeline: maps endpoint/headers/payload, runs plugins, then calls the fetcher. */\n public async fetch(\n request: ExtendRequest<\n RequestInstance,\n {\n // No need for global error type, it doesn't matter to the fetcher itself\n client: Client<\n any,\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >;\n }\n >,\n requestId: string,\n ): Promise<RequestResponseType<RequestInstance>> {\n let startTime: number | undefined;\n\n const execute = async (resolve: (value: ResponseType<any, any, any>) => void) => {\n try {\n if (!this.initialized) {\n throw new RequestProcessingError(`Adapter ${this.options.name} is not initialized`);\n }\n\n if (!this.unstable_fetcher) {\n throw new RequestProcessingError(`Fetcher for ${this.options.name} adapter is not set`);\n }\n\n this.client.triggerPlugins(\"onAdapterFetch\", {\n adapter: this,\n request,\n requestId,\n });\n\n const bindings = await getAdapterBindings<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >({\n request,\n requestId,\n resolve,\n internalErrorMapping: this.unstable_internalErrorMapping,\n onStartTime: (time) => {\n startTime = time;\n },\n });\n\n if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) {\n return await mocker<\n Adapter<\n AdapterOptions,\n MethodType,\n StatusType,\n Extra,\n QueryParams,\n DefaultQueryParams,\n EndpointType,\n EndpointMapperType,\n QueryParamsMapperType,\n HeaderMapperType,\n PayloadMapperType,\n RequestOptions\n >\n >(bindings);\n }\n\n return this.unstable_fetcher(bindings);\n } catch (error) {\n const onError = getAdapterOnError({\n request,\n requestId,\n startTime: startTime || Date.now(),\n logger: this.logger,\n resolve,\n });\n\n return onError({\n error: this.unstable_internalErrorMapping(error as ReturnType<typeof getErrorMessage>),\n status: this.options.systemErrorStatus,\n extra: this.options.systemErrorExtra,\n });\n }\n };\n\n const promise = new Promise((resolve) => {\n execute(resolve);\n });\n\n return promise as Promise<RequestResponseType<RequestInstance>>;\n }\n}\n","export enum HttpMethods {\n GET = \"GET\",\n POST = \"POST\",\n PUT = \"PUT\",\n PATCH = \"PATCH\",\n DELETE = \"DELETE\",\n /** Safe, idempotent read with a request body (IETF draft-ietf-httpbis-safe-method-w-body). */\n QUERY = \"QUERY\",\n}\n\n/** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */\nexport const SAFE_HTTP_METHODS: string[] = [HttpMethods.GET, HttpMethods.QUERY];\n","import { getErrorMessage } from \"adapter\";\nimport type { AdapterInstance, ProgressType, RequestResponseType, ResponseType } from \"adapter\";\nimport { SAFE_HTTP_METHODS } from \"constants/http.constants\";\nimport type { Dispatcher } from \"dispatcher\";\nimport type { RequestResponseEventType } from \"managers\";\nimport type { ExtractAdapterType, ExtractErrorType } from \"types\";\n\nimport type {\n OptimisticCallbackResult,\n OptimisticRollbackArgs,\n ProgressEventType,\n RequestInstance,\n RequestJSON,\n RequestSendOptionsType,\n} from \"./request.types\";\n\ntype MappedResponse =\n | ResponseType<any, any, AdapterInstance>\n | Promise<ResponseType<any, any, AdapterInstance>>\n | undefined;\n\nexport const scopeKey = (key: string, scope: string | null): string => {\n return scope ? `${scope}__${key}` : key;\n};\n\nexport const stringifyKey = (value: unknown): string => {\n try {\n if (typeof value === \"string\") {\n return value;\n }\n if (value === undefined || value === null) {\n return \"\";\n }\n const data = JSON.stringify(value);\n if (typeof data !== \"string\") {\n throw new TypeError();\n }\n return data;\n } catch {\n return \"\";\n }\n};\n\nexport const getProgressValue = ({ loaded, total }: ProgressEventType): number => {\n if (!loaded || !total) {\n return 0;\n }\n return Number(((loaded * 100) / total).toFixed(0));\n};\n\nexport const getRequestEta = (\n startDate: Date,\n progressDate: Date,\n { total, loaded }: ProgressEventType,\n): { sizeLeft: number; timeLeft: number | null } => {\n const timeElapsed = +progressDate - +startDate || 1;\n const uploadSpeed = loaded / timeElapsed;\n const totalValue = Math.max(total, loaded);\n const sizeLeft = totalValue - loaded;\n const estimatedTimeValue = uploadSpeed ? sizeLeft / uploadSpeed : null;\n const timeLeft = totalValue === loaded ? 0 : estimatedTimeValue;\n\n return { timeLeft, sizeLeft };\n};\n\nexport const getProgressData = (\n requestStartTime: Date,\n progressDate: Date,\n progressEvent: ProgressEventType,\n): ProgressType => {\n const { total, loaded } = progressEvent;\n if (Number.isNaN(total) || Number.isNaN(loaded)) {\n return {\n progress: 0,\n timeLeft: 0,\n sizeLeft: 0,\n total: 0,\n loaded: 0,\n startTimestamp: +requestStartTime,\n };\n }\n\n const { timeLeft, sizeLeft } = getRequestEta(requestStartTime, progressDate, progressEvent);\n\n return {\n progress: getProgressValue(progressEvent),\n timeLeft,\n sizeLeft,\n total,\n loaded,\n startTimestamp: +requestStartTime,\n };\n};\n\n// Keys\nexport const getSimpleKey = (request: RequestInstance | RequestJSON<RequestInstance>): string => {\n return `${request.method}_${request.requestOptions.endpoint}_${request.cancelable}`;\n};\n\n/**\n * Cache instance for individual request that collects individual requests responses from\n * the same endpoint (they may differ base on the custom key, endpoint params etc)\n * @param request\n * @param useInitialValues\n * @returns\n */\nexport const getRequestKey = (\n request: RequestInstance | RequestJSON<RequestInstance>,\n useInitialValues?: boolean,\n): string => {\n /**\n * Below stringified values allow to match the response by method, endpoint and query params.\n * That's because we have shared endpoint, but data with queryParams '?user=1' will not match regular request without queries.\n * We want both results to be cached in separate places to not override each other.\n *\n * Values to be stringified:\n *\n * endpoint: string;\n * queryParams: string;\n * params: string;\n */\n const methodKey = stringifyKey(request.method);\n const endpointKey = useInitialValues ? request.requestOptions.endpoint : stringifyKey(request.endpoint);\n const queryParamsKey = useInitialValues ? \"\" : stringifyKey(request.queryParams);\n\n return `${methodKey}_${endpointKey}_${queryParamsKey}`;\n};\n\nexport const getRequestDispatcher = <Request extends RequestInstance>(\n request: Request,\n dispatcherType: \"auto\" | \"fetch\" | \"submit\" = \"auto\",\n): [Dispatcher<ExtractAdapterType<Request>>, isFetchDispatcher: boolean] => {\n const { fetchDispatcher, submitDispatcher } = request.client;\n const isSafeRead = SAFE_HTTP_METHODS.includes(request.method as string);\n const isFetchDispatcher = (dispatcherType === \"auto\" && isSafeRead) || dispatcherType === \"fetch\";\n const dispatcher = isFetchDispatcher ? fetchDispatcher : submitDispatcher;\n\n return [dispatcher, isFetchDispatcher];\n};\n\nexport const mapResponseForSend = async <Request extends RequestInstance>(\n request: Request,\n response: ResponseType<any, any, AdapterInstance>,\n): Promise<RequestResponseType<Request>> => {\n const mapping = request.unstable_responseMapper?.(response as ResponseType<any, any, ExtractAdapterType<Request>>);\n\n if (mapping instanceof Promise) {\n return (await mapping) as RequestResponseType<Request>;\n }\n\n return (mapping || response) as RequestResponseType<Request>;\n};\n\n/**\n * Rollback is user code running in the middle of the response handling, its failure can't affect the request\n */\nconst rollbackOptimistic = (\n optimistic: OptimisticCallbackResult<any>,\n args: OptimisticRollbackArgs<RequestInstance>,\n): void => {\n const logFailure = (error: unknown) => {\n args.request.client.logger.error({\n title: \"Optimistic rollback failed\",\n type: \"system\",\n extra: { error, reason: args.reason, request: args.request },\n });\n };\n\n try {\n // Async rollback is not awaited, but its rejection can't stay unhandled\n Promise.resolve(optimistic.rollback?.(args)).catch(logFailure);\n } catch (error) {\n logFailure(error);\n }\n};\n\nconst invalidateOptimistic = (optimistic: OptimisticCallbackResult<any>, request: RequestInstance): void => {\n optimistic.invalidate?.forEach((target) => {\n try {\n request.client.cache.invalidate(target);\n } catch (error) {\n request.client.logger.error({\n title: \"Optimistic invalidation failed\",\n type: \"system\",\n extra: { error, target, request },\n });\n }\n });\n};\n\nexport const sendRequest = async <Request extends RequestInstance>(\n request: Request,\n options?: RequestSendOptionsType<Request>,\n): Promise<RequestResponseType<Request>> => {\n const { client } = request;\n const { requestManager } = client;\n const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);\n\n let mutationContext: OptimisticCallbackResult<any> | undefined;\n\n if (request.optimistic) {\n try {\n mutationContext = await request.optimistic({\n request,\n client: request.client,\n payload: request.payload,\n });\n } catch (error) {\n return {\n data: null,\n error: new Error(\n `Optimistic callback failed: ${error instanceof Error ? error.message : error}`,\n ) as unknown as ExtractErrorType<Request>,\n status: null,\n success: false,\n extra: client.adapter.defaultExtra,\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n };\n }\n }\n\n return new Promise<RequestResponseType<Request>>((resolve) => {\n // The dispatcher is done with the request - removal from the queue that follows is not a separate outcome\n let isResolved = false;\n let isDelivered = false;\n let isSettled = false;\n const requestId = dispatcher.add(request);\n const { $hooks } = request;\n\n // Failed attempts stay in the dispatcher queue when they are going to be sent again\n const getWillBeResent = ({ response, details }: RequestResponseEventType<Request>) => {\n if (response.success || details.isCanceled) {\n return false;\n }\n return details.willRetry || (request.offline && details.isOffline);\n };\n\n // Settlement and delivery read the same event - the mapper has to run only once per response\n const mappings = new WeakMap<RequestResponseEventType<Request>, MappedResponse>();\n const getMapping = (values: RequestResponseEventType<Request>) => {\n if (!mappings.has(values)) {\n mappings.set(\n values,\n request.unstable_responseMapper?.(values.response as ResponseType<any, any, ExtractAdapterType<Request>>),\n );\n }\n return mappings.get(values);\n };\n\n // Attached ahead of `onBeforeSent`, so listeners added there already observe the settled cache\n const unmountSettlement = mutationContext\n ? requestManager.events.onResponseById<Request>(requestId, (values) => {\n const optimistic = mutationContext as OptimisticCallbackResult<any>;\n const willBeResent = getWillBeResent(values);\n\n const settle = (response: ResponseType<any, any, AdapterInstance>) => {\n if (isSettled || (!response.success && willBeResent)) {\n return;\n }\n isSettled = true;\n\n if (values.details.isCanceled) {\n rollbackOptimistic(optimistic, { reason: \"abort\", response, request });\n } else if (response.success) {\n invalidateOptimistic(optimistic, request);\n } else {\n rollbackOptimistic(optimistic, { reason: \"error\", response, request });\n }\n };\n\n const mapping = getMapping(values);\n if (mapping instanceof Promise) {\n mapping.then(settle);\n } else {\n settle(mapping || values.response);\n }\n })\n : undefined;\n\n const beforeSentData = { requestId, request, mutationContext };\n options?.onBeforeSent?.(beforeSentData);\n $hooks.__emit(\"onBeforeSent\", beforeSentData);\n\n const unmountRequestStart = requestManager.events.onRequestStartById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n options?.onRequestStart?.(enriched);\n $hooks.__emit(\"onRequestStart\", enriched);\n });\n\n const unmountResponseStart = requestManager.events.onResponseStartById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n options?.onResponseStart?.(enriched);\n $hooks.__emit(\"onResponseStart\", enriched);\n });\n\n const unmountUpload = requestManager.events.onUploadProgressById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n options?.onUploadProgress?.(enriched);\n $hooks.__emit(\"onUploadProgress\", enriched);\n });\n\n const unmountDownload = requestManager.events.onDownloadProgressById<Request>(requestId, (data) => {\n const enriched = { ...data, mutationContext };\n options?.onDownloadProgress?.(enriched);\n $hooks.__emit(\"onDownloadProgress\", enriched);\n });\n\n // When resolved\n const unmountResponse = requestManager.events.onResponseById<Request>(requestId, (values) => {\n const { response } = values;\n const willBeResent = getWillBeResent(values);\n isResolved = !willBeResent;\n const enrichedValues = { ...values, mutationContext };\n\n const mapping = getMapping(values);\n\n const handleResponse = (success: boolean, data: ResponseType<any, any, ExtractAdapterType<Request>>) => {\n // Retries and offline postponing end with another response we need to listen for\n if (isDelivered || (!success && willBeResent)) {\n return;\n }\n isDelivered = true;\n\n options?.onResponse?.(enrichedValues);\n $hooks.__emit(\"onResponse\", enrichedValues);\n resolve(data);\n\n // Unmount Listeners\n // eslint-disable-next-line @typescript-eslint/no-use-before-define, @typescript-eslint/no-use-before-define\n umountAll();\n };\n\n // Create async await ONLY when we make a promise mapper\n if (mapping instanceof Promise) {\n (async () => {\n const responseData = await mapping;\n\n const { success } = responseData;\n handleResponse(success, responseData as ResponseType<any, any, ExtractAdapterType<Request>>);\n })();\n }\n // For sync mapping operations we should not use async actions\n else {\n const data = mapping || response;\n const { success } = data;\n handleResponse(success, data as ResponseType<any, any, ExtractAdapterType<Request>>);\n }\n });\n\n // When removed from queue storage we need to clean event listeners and return proper error\n const unmountRemoveQueueElement = requestManager.events.onRemoveById<Request>(requestId, (data) => {\n if (!isResolved) {\n isResolved = true;\n isDelivered = true;\n\n if (mutationContext && !isSettled) {\n isSettled = true;\n rollbackOptimistic(mutationContext, { reason: \"removed\", request });\n }\n\n const enriched = { ...data, mutationContext };\n options?.onRemove?.(enriched);\n $hooks.__emit(\"onRemove\", enriched);\n resolve({\n data: null,\n status: null,\n success: false,\n error: getErrorMessage(\"deleted\") as unknown as ExtractErrorType<Request>,\n extra: request.client.adapter.defaultExtra,\n requestTimestamp: Date.now(),\n responseTimestamp: Date.now(),\n });\n\n // Unmount Listeners\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n umountAll();\n }\n });\n\n function umountAll() {\n unmountSettlement?.();\n unmountRequestStart();\n unmountResponseStart();\n unmountUpload();\n unmountDownload();\n unmountResponse();\n unmountRemoveQueueElement();\n }\n });\n};\n","import type { ResponseErrorType, ResponseSuccessType, ResponseType } from \"adapter\";\nimport type { ClientInstance } from \"client\";\nimport { Time } from \"constants/time.constants\";\nimport type { MockerConfigType, MockResponseType } from \"mocker\";\nimport type {\n ExtractAdapterType,\n ExtractClientAdapterType,\n ExtractClientGlobalError,\n ExtractEndpointType,\n ExtractParamsType,\n ExtractPayloadType,\n ExtractQueryParamsType,\n EmptyTypes,\n ExtractAdapterMethodType,\n ExtractAdapterOptionsType,\n HydrateDataType,\n SyncOrAsync,\n} from \"types\";\n\nimport type { RequestHooks } from \"./request.hooks\";\nimport { createRequestHooks } from \"./request.hooks\";\n/* eslint-disable max-lines */\nimport type {\n RequestSendOptionsType,\n ParamsType,\n RequestSendType,\n PayloadType,\n RequestJSON,\n RequestOptionsType,\n RequestConfigurationType,\n PayloadMapperType,\n RequestInstance,\n RequestMapper,\n ResponseMapper,\n ExtractUrlParams,\n RetryOnErrorCallbackType,\n OptimisticCallback,\n} from \"./request.types\";\nimport { mapResponseForSend, sendRequest, scopeKey } from \"./request.utils\";\n\ntype ClientAdapterOptions<C extends ClientInstance> = ExtractAdapterOptionsType<ExtractClientAdapterType<C>>;\ntype ClientAdapterMethod<C extends ClientInstance> = ExtractAdapterMethodType<ExtractClientAdapterType<C>>;\ntype ClientRequestOptions<E, C extends ClientInstance> = RequestOptionsType<\n E,\n ClientAdapterOptions<C>,\n ClientAdapterMethod<C>\n>;\n\n/**\n * Request is a class that represents a request sent to the server. It contains all the necessary information to make a request, like endpoint, method, headers, data, and much more.\n * It is executed at any time via methods like `send` or `exec`.\n *\n * We can set it up with options like endpoint, method, headers and more.\n * We can choose some of advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.\n *\n * @info We should not use this class directly in the standard development flow.\n * We can initialize it using the `createRequest` method on the **Client** class.\n *\n * @attention The most important thing about the request is that it keeps data in the format that can be dumped.\n * This is necessary for the persistence and different dispatcher storage types.\n * This class doesn't have any callback methods by design and communicate with dispatcher and cache by events.\n *\n * It should be serializable to JSON and deserializable back to the class.\n * Serialization should not affect the result of the request, so it's methods and functional part should be only syntax sugar for given runtime.\n */\n\nexport class Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string,\n Client extends ClientInstance,\n HasPayload extends true | false = false,\n HasParams extends true | false = false,\n HasQuery extends true | false = false,\n MutationContext = undefined,\n> {\n endpoint: Endpoint;\n headers?: HeadersInit = undefined;\n auth: boolean;\n method: ClientAdapterMethod<Client>;\n params: ExtractUrlParams<Endpoint> | EmptyTypes;\n payload: PayloadType<Payload>;\n queryParams: QueryParams | EmptyTypes;\n options?: ClientAdapterOptions<Client> | undefined = undefined;\n cancelable: boolean;\n retry: number;\n retryTime: number;\n cacheTime: number;\n cache: boolean;\n staleTime: number;\n queued: boolean;\n offline: boolean;\n abortKey: string;\n cacheKey: string;\n queryKey: string;\n used: boolean;\n deduplicate: boolean;\n deduplicateTime: number | null;\n structuralSharing: boolean;\n scope: string | null;\n\n /**\n * Instance-level lifecycle hooks. These callbacks fire for every `send()` / `exec()` call\n * made on this request instance (and its clones), without needing to pass them to `send()` each time.\n * Useful for cross-cutting concerns like logging, analytics, or toast notifications.\n *\n * Each method registers a callback and returns an unsubscribe function.\n * Multiple listeners per hook are supported.\n */\n $hooks: RequestHooks<RequestInstance> = createRequestHooks();\n\n isMockerEnabled = false;\n\n static readonly OPTIONAL_FIELDS = [\n \"unstable_mock\",\n \"unstable_payloadMapper\",\n \"unstable_requestMapper\",\n \"unstable_responseMapper\",\n \"retryOnError\",\n \"optimistic\",\n ] as const;\n\n // The `= undefined` initializers below are load-bearing. Metro (React Native) compiles\n // class properties in loose mode, which drops field declarations that have no initializer,\n // and the SDK proxy relies on an `in` check to tell request properties apart from deeper\n // API path segments (see OPTIONAL_REQUEST_FIELDS in sdk/sdk.ts).\n unstable_mock?: {\n fn: (options: {\n request: RequestInstance;\n requestId: string;\n }) => MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;\n config: MockerConfigType;\n } = undefined;\n /** @internal */\n unstable_payloadMapper?: PayloadMapperType<Payload> = undefined;\n /** @internal */\n unstable_requestMapper?: RequestMapper<any, any> = undefined;\n /** @internal */\n unstable_responseMapper?: ResponseMapper<this, ResponseSuccessType<any, any> | ResponseErrorType<any, any>> =\n undefined;\n /** @internal */\n retryOnError?: RetryOnErrorCallbackType<RequestInstance> = undefined;\n /** @internal */\n optimistic?: OptimisticCallback<RequestInstance, any> = undefined;\n\n unstable_hasParams: HasParams = false as HasParams;\n unstable_hasPayload: HasPayload = false as HasPayload;\n unstable_hasQuery: HasQuery = false as HasQuery;\n unstable_hasMutationContext: MutationContext = undefined as MutationContext;\n\n private updatedAbortKey: boolean;\n private updatedCacheKey: boolean;\n private updatedQueryKey: boolean;\n\n constructor(\n readonly client: Client,\n readonly requestOptions: ClientRequestOptions<Endpoint, Client>,\n readonly initialRequestConfiguration?:\n | RequestConfigurationType<\n Payload,\n Endpoint extends string ? ExtractUrlParams<Endpoint> : never,\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n >\n | undefined,\n ) {\n const configuration: ClientRequestOptions<Endpoint, Client> = {\n ...(this.client.adapter.unstable_getRequestDefaults?.(requestOptions) as ClientRequestOptions<Endpoint, Client>),\n ...requestOptions,\n };\n const {\n endpoint,\n headers,\n auth = true,\n method = client.adapter.defaultMethod,\n options,\n cancelable = false,\n retry = 0,\n retryTime = 500,\n cacheTime = Time.MIN * 5,\n cache = true,\n staleTime = Time.MIN * 5,\n queued = false,\n offline = true,\n abortKey,\n cacheKey,\n queryKey,\n deduplicate = false,\n deduplicateTime = null,\n structuralSharing = true,\n } = configuration;\n this.endpoint = initialRequestConfiguration?.endpoint ?? endpoint;\n this.headers = initialRequestConfiguration?.headers ?? headers;\n this.auth = initialRequestConfiguration?.auth ?? auth;\n this.method = method as ExtractAdapterMethodType<ExtractClientAdapterType<Client>>;\n this.params = initialRequestConfiguration?.params;\n this.payload = initialRequestConfiguration?.payload;\n this.queryParams = initialRequestConfiguration?.queryParams;\n this.options = initialRequestConfiguration?.options ?? options;\n this.cancelable = initialRequestConfiguration?.cancelable ?? cancelable;\n this.retry = initialRequestConfiguration?.retry ?? retry;\n this.retryTime = initialRequestConfiguration?.retryTime ?? retryTime;\n this.cacheTime = initialRequestConfiguration?.cacheTime ?? cacheTime;\n this.cache = initialRequestConfiguration?.cache ?? cache;\n this.staleTime = initialRequestConfiguration?.staleTime ?? staleTime;\n this.queued = initialRequestConfiguration?.queued ?? queued;\n this.offline = initialRequestConfiguration?.offline ?? offline;\n this.abortKey = initialRequestConfiguration?.abortKey ?? abortKey ?? this.client.unstable_abortKeyMapper(this);\n this.cacheKey = initialRequestConfiguration?.cacheKey ?? cacheKey ?? this.client.unstable_cacheKeyMapper(this);\n this.queryKey = initialRequestConfiguration?.queryKey ?? queryKey ?? this.client.unstable_queryKeyMapper(this);\n this.used = initialRequestConfiguration?.used ?? false;\n this.deduplicate = initialRequestConfiguration?.deduplicate ?? deduplicate;\n this.deduplicateTime = initialRequestConfiguration?.deduplicateTime ?? deduplicateTime;\n this.structuralSharing = initialRequestConfiguration?.structuralSharing ?? structuralSharing;\n this.scope = initialRequestConfiguration?.scope ?? null;\n this.updatedAbortKey = initialRequestConfiguration?.updatedAbortKey ?? false;\n this.updatedCacheKey = initialRequestConfiguration?.updatedCacheKey ?? false;\n this.updatedQueryKey = initialRequestConfiguration?.updatedQueryKey ?? false;\n }\n\n /** Set the request headers. Returns a cloned request with the new headers applied. */\n public setHeaders = (headers: HeadersInit) => {\n return this.clone({ headers });\n };\n\n /** Set whether authentication interceptors should run for this request. */\n public setAuth = (auth: boolean) => {\n return this.clone({ auth });\n };\n\n /** Set the URL path parameters (e.g., `:userId`). */\n public setParams = <P extends ExtractParamsType<this>>(params: P) => {\n return this.clone<HasPayload, P extends null ? false : true, HasQuery>({ params });\n };\n\n /** Set the request body payload. */\n public setPayload = <P extends Payload>(payload: P) => {\n return this.clone<P extends null ? false : true, HasParams, HasQuery>({\n payload,\n });\n };\n\n /** Set the query parameters appended to the URL. */\n public setQueryParams = (queryParams: QueryParams) => {\n return this.clone<HasPayload, HasParams, true>({ queryParams });\n };\n\n /** Set adapter-specific options (e.g., axios config, fetch init). */\n public setOptions = (options: ClientAdapterOptions<Client>) => {\n return this.clone<HasPayload, HasParams, true>({ options });\n };\n\n /**\n * Set a scope identifier for this request.\n * All keys (cache, queue, abort) are prefixed with this scope, isolating\n * the request from other scopes. In \"server\" client mode, setting a scope\n * also enables caching (which is otherwise disabled to prevent cross-request leaks).\n */\n public setScope = (scopeId: string) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.scope = scopeId;\n return cloned;\n };\n\n /** Set whether in-flight requests with the same abort key are cancelled when a new one is dispatched. */\n public setCancelable = (cancelable: boolean) => {\n return this.clone({ cancelable });\n };\n\n /** Set the number of retry attempts on failure. */\n public setRetry = (retry: ClientRequestOptions<Endpoint, Client>[\"retry\"]) => {\n return this.clone({ retry });\n };\n\n /** Set the delay in milliseconds between retry attempts. */\n public setRetryTime = (retryTime: ClientRequestOptions<Endpoint, Client>[\"retryTime\"]) => {\n return this.clone({ retryTime });\n };\n\n /**\n * Set a callback that controls whether a failed request should be retried.\n * Called on each failed attempt before scheduling the next retry.\n * Return `true` to allow the retry, `false` to stop retrying immediately.\n */\n public setRetryOnError = (\n callback: RetryOnErrorCallbackType<\n Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>\n >,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.retryOnError = callback as RetryOnErrorCallbackType<RequestInstance>;\n return cloned;\n };\n\n /**\n * Configure optimistic update behavior for this request.\n * The callback runs before the request is sent and receives the request, client, and payload.\n * Return `context` (available in lifecycle callbacks), `rollback` (called automatically once on\n * failure, abort or queue removal), and `invalidate` (requests invalidated on success).\n * Both run for every way of sending the request, not only inside of framework hooks.\n */\n public setOptimistic = <Ctx>(callback: OptimisticCallback<this, Ctx>) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n cloned.optimistic = callback as OptimisticCallback<RequestInstance, any>;\n return cloned as unknown as Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint,\n Client,\n HasPayload,\n HasParams,\n HasQuery,\n Ctx\n >;\n };\n\n /** Set how long (in ms) the response remains in cache before being garbage collected. */\n public setCacheTime = (cacheTime: ClientRequestOptions<Endpoint, Client>[\"cacheTime\"]) => {\n return this.clone({ cacheTime });\n };\n\n /** Set whether this request should use the cache. */\n public setCache = (cache: ClientRequestOptions<Endpoint, Client>[\"cache\"]) => {\n return this.clone({ cache });\n };\n\n /** Set how long (in ms) cached data is considered fresh before triggering a revalidation. */\n public setStaleTime = (staleTime: ClientRequestOptions<Endpoint, Client>[\"staleTime\"]) => {\n return this.clone({ staleTime });\n };\n\n /** Set whether the request should be queued and executed sequentially rather than immediately. */\n public setQueued = (queued: boolean) => {\n return this.clone({ queued });\n };\n\n /** Override the abort key used to cancel this request. */\n public setAbortKey = (abortKey: string) => {\n this.updatedAbortKey = true;\n return this.clone({ abortKey });\n };\n\n /** Override the cache key used to store/retrieve the response. */\n public setCacheKey = (cacheKey: string) => {\n this.updatedCacheKey = true;\n return this.clone({ cacheKey });\n };\n\n /** Override the query key that identifies this request in the dispatcher queue. */\n public setQueryKey = (queryKey: string) => {\n this.updatedQueryKey = true;\n return this.clone({ queryKey });\n };\n\n /** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */\n public setDeduplicate = (deduplicate: boolean) => {\n return this.clone({ deduplicate });\n };\n\n /** Set the time window (in ms) during which identical requests are deduplicated. */\n public setDeduplicateTime = (deduplicateTime: number) => {\n return this.clone({ deduplicateTime });\n };\n\n /** Enable or disable structural sharing - keeping references of unchanged parts of the response data in cache. */\n public setStructuralSharing = (structuralSharing: boolean) => {\n return this.clone({ structuralSharing });\n };\n\n /** Mark the request as used (prevents automatic refetching in hooks). */\n public setUsed = (used: boolean) => {\n return this.clone({ used });\n };\n\n /** Set whether the request should be stored in the offline queue when there is no network connection. */\n public setOffline = (offline: boolean) => {\n return this.clone({ offline });\n };\n\n /** Attach a mock handler to this request. When mocking is enabled, the handler is called instead of the real adapter. */\n public setMock = (\n fn: (options: {\n request: Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;\n requestId: string;\n }) => SyncOrAsync<\n MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n >,\n config: MockerConfigType = {},\n ) => {\n this.unstable_mock = { fn, config } as typeof this.unstable_mock;\n this.isMockerEnabled = true;\n return this;\n };\n\n /** Remove any attached mock handler and disable mocking for this request. */\n public clearMock = () => {\n this.unstable_mock = undefined;\n this.isMockerEnabled = false;\n return this;\n };\n\n /** Enable or disable the mocker for this request without removing the mock handler. */\n public setMockingEnabled = (isMockerEnabled: boolean) => {\n this.isMockerEnabled = isMockerEnabled;\n return this;\n };\n\n /**\n * Map data before it gets send to the server\n * @param payloadMapper\n * @returns\n */\n public setPayloadMapper = <MappedPayload extends any | Promise<any>>(\n payloadMapper: (data: Payload) => MappedPayload,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_payloadMapper = payloadMapper as typeof this.unstable_payloadMapper;\n\n return cloned;\n };\n\n /**\n * Map request before it gets send to the server\n * @param requestMapper mapper of the request\n * @returns new request\n */\n public setRequestMapper = <NewRequest extends RequestInstance>(requestMapper: RequestMapper<this, NewRequest>) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_requestMapper = requestMapper;\n\n return cloned;\n };\n\n /**\n * Map the response to the new interface\n * @param responseMapper our mapping callback\n * @returns new response\n */\n public setResponseMapper = <MappedResponse extends ResponseSuccessType<any, any> | ResponseErrorType<any, any>>(\n responseMapper?: ResponseMapper<this, MappedResponse>,\n ) => {\n const cloned = this.clone<HasPayload, HasParams, HasQuery>();\n\n cloned.unstable_responseMapper = responseMapper as typeof cloned.unstable_responseMapper;\n\n return cloned as unknown as Request<\n MappedResponse extends ResponseType<infer R, any, any> ? R : Response,\n Payload,\n QueryParams,\n MappedResponse extends ResponseType<any, infer E, any> ? E : LocalError,\n Endpoint,\n Client,\n HasPayload,\n HasParams,\n HasQuery,\n MutationContext\n >;\n };\n\n private paramsMapper = (params: ParamsType | null | undefined): Endpoint => {\n const { endpoint } = this.requestOptions;\n\n let stringEndpoint = String(endpoint);\n if (params) {\n Object.entries(params).forEach(([key, value]) => {\n stringEndpoint = stringEndpoint.replaceAll(new RegExp(`:${key}`, \"g\"), String(value));\n });\n }\n\n return stringEndpoint as Endpoint;\n };\n\n /** Serialize the request configuration into a plain JSON object for persistence or transfer. */\n public toJSON(): RequestJSON<this> {\n return {\n requestOptions: this.requestOptions as unknown as RequestOptionsType<\n ExtractEndpointType<this>,\n ExtractAdapterOptionsType<ExtractAdapterType<this>>,\n ExtractAdapterMethodType<ExtractAdapterType<this>>\n >,\n endpoint: this.endpoint as ExtractEndpointType<this>,\n headers: this.headers,\n auth: this.auth,\n // TODO: fix this type\n method: this.method as any,\n params: this.params as ExtractParamsType<this>,\n payload: this.payload as ExtractPayloadType<this>,\n queryParams: this.queryParams as ExtractQueryParamsType<this>,\n options: this.options,\n cancelable: this.cancelable,\n retry: this.retry,\n retryTime: this.retryTime,\n cacheTime: this.cacheTime,\n cache: this.cache,\n staleTime: this.staleTime,\n queued: this.queued,\n offline: this.offline,\n abortKey: this.abortKey,\n cacheKey: this.cacheKey,\n queryKey: this.queryKey,\n used: this.used,\n disableResponseInterceptors: this.requestOptions.disableResponseInterceptors,\n disableRequestInterceptors: this.requestOptions.disableRequestInterceptors,\n updatedAbortKey: this.updatedAbortKey,\n updatedCacheKey: this.updatedCacheKey,\n updatedQueryKey: this.updatedQueryKey,\n deduplicate: this.deduplicate,\n deduplicateTime: this.deduplicateTime,\n structuralSharing: this.structuralSharing,\n scope: this.scope,\n isMockerEnabled: this.isMockerEnabled,\n hasMock: !!this.unstable_mock,\n };\n }\n\n /** Create a new request instance with optional configuration overrides. Used internally by all setter methods. */\n public clone<\n NewData extends true | false = HasPayload,\n NewParams extends true | false = HasParams,\n NewQueryParams extends true | false = HasQuery,\n >(\n configuration?: RequestConfigurationType<\n Payload,\n (typeof this)[\"params\"],\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n >,\n ) {\n const json = this.toJSON();\n const initialRequestConfiguration: RequestConfigurationType<\n Payload,\n Endpoint extends string ? ExtractUrlParams<Endpoint> : never,\n QueryParams,\n Endpoint,\n ClientAdapterOptions<Client>,\n ClientAdapterMethod<Client>\n > = {\n ...json,\n ...configuration,\n options: configuration?.options || this.options,\n abortKey: this.updatedAbortKey ? configuration?.abortKey || this.abortKey : undefined,\n cacheKey: this.updatedCacheKey ? configuration?.cacheKey || this.cacheKey : undefined,\n queryKey: this.updatedQueryKey ? configuration?.queryKey || this.queryKey : undefined,\n endpoint: this.paramsMapper(configuration?.params || this.params),\n queryParams: configuration?.queryParams || this.queryParams,\n payload: configuration?.payload || this.payload,\n params: (configuration?.params || this.params) as\n | EmptyTypes\n | (Endpoint extends string ? ExtractUrlParams<Endpoint> : never),\n };\n\n const cloned = new Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint,\n Client,\n NewData,\n NewParams,\n NewQueryParams,\n MutationContext\n >(this.client, this.requestOptions, initialRequestConfiguration);\n\n // Inherit methods\n cloned.unstable_payloadMapper = this.unstable_payloadMapper;\n cloned.unstable_responseMapper = this.unstable_responseMapper as typeof cloned.unstable_responseMapper;\n cloned.unstable_requestMapper = this.unstable_requestMapper;\n cloned.retryOnError = this.retryOnError;\n\n cloned.unstable_mock = this.unstable_mock;\n cloned.isMockerEnabled = this.isMockerEnabled;\n cloned.optimistic = this.optimistic;\n cloned.$hooks = createRequestHooks(this.$hooks.__snapshot());\n\n return cloned;\n }\n\n /** Abort all in-flight requests sharing this request's abort key. */\n public abort = () => {\n const { requestManager } = this.client;\n requestManager.abortByKey(scopeKey(this.abortKey, this.scope));\n\n return this.clone();\n };\n\n /** Extract the current cache data for this request into a portable hydration payload (useful for SSR). */\n public dehydrate = (config?: {\n /** in case of using adapter without cache we can provide response to dehydrate */\n response?: ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;\n /** override cache data */\n override?: boolean;\n }):\n | HydrateDataType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n | undefined => {\n const { response, override = true } = config || {};\n\n if (response) {\n return {\n override,\n cacheTime: this.cacheTime,\n staleTime: this.staleTime,\n cacheKey: this.cacheKey,\n scope: this.scope,\n timestamp: Date.now(),\n hydrated: true,\n cache: true,\n response,\n };\n }\n\n const cacheData = this.client.cache.get<Response, LocalError | ExtractClientGlobalError<Client>>(\n scopeKey(this.cacheKey, this.scope),\n );\n\n if (!cacheData) {\n return undefined;\n }\n\n return {\n override,\n cacheTime: this.cacheTime,\n staleTime: this.staleTime,\n cacheKey: this.cacheKey,\n scope: this.scope,\n timestamp: Date.now(),\n hydrated: true,\n cache: true,\n response: {\n data: cacheData.data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra,\n requestTimestamp: cacheData.requestTimestamp,\n responseTimestamp: cacheData.responseTimestamp,\n },\n };\n };\n\n /**\n * Read the response from cache data\n *\n * If it returns error and data at the same time, it means that latest request was failed\n * and we show previous data from cache together with error received from actual request\n */\n public read():\n | ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>\n | undefined {\n const cacheData = this.client.cache.get<Response, LocalError | ExtractClientGlobalError<Client>>(\n scopeKey(this.cacheKey, this.scope),\n );\n\n if (cacheData) {\n return {\n data: cacheData.data,\n error: cacheData.error,\n status: cacheData.status,\n success: cacheData.success,\n extra: cacheData.extra,\n requestTimestamp: cacheData.requestTimestamp,\n responseTimestamp: cacheData.responseTimestamp,\n };\n }\n return undefined;\n }\n\n /**\n * Method to use the request WITHOUT adding it to cache and queues. This mean it will make simple request without queue side effects.\n * @param options\n * @disableReturns\n * @returns\n * ```tsx\n * Promise<[Data | null, Error | null, HttpStatus]>\n * ```\n */\n public exec: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {\n const { adapter, requestManager } = this.client;\n const request = this.clone(options);\n\n const requestId = this.client.unstable_requestIdMapper(this);\n\n const scopedAbortKey = scopeKey(this.abortKey, this.scope);\n\n // Listen for aborting\n requestManager.addAbortController(scopedAbortKey, requestId);\n\n const response = await adapter.fetch(request, requestId);\n\n // Stop listening for aborting\n requestManager.removeAbortController(scopedAbortKey, requestId);\n\n if (request.unstable_responseMapper) {\n return request.unstable_responseMapper(response);\n }\n\n return response;\n };\n\n /**\n * Method used to perform requests with usage of cache and queues\n * @param options\n * @param requestCallback\n * @disableReturns\n * @returns\n * ```tsx\n * Promise<{ data: Data | null, error: Error | null, status: HttpStatus, ... }>\n * ```\n */\n public send: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {\n const { dispatcherType: _dispatcherType, cachePolicy = \"network-only\", ...configuration } = options || {};\n\n const request = this.clone(configuration) as unknown as this;\n\n const sendRequestOptions = options === undefined ? undefined : { ...options, cachePolicy: undefined };\n\n if (cachePolicy === \"network-only\") {\n return sendRequest(request, sendRequestOptions);\n }\n\n const cached = request.read();\n\n if (cachePolicy === \"cache-first\") {\n if (cached) {\n return mapResponseForSend(request, cached);\n }\n return sendRequest(request, sendRequestOptions);\n }\n\n // revalidate\n if (cached) {\n const resolved = await mapResponseForSend(request, cached);\n // Background revalidation; promise from send() already resolved with cache snapshot\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n sendRequest(request, sendRequestOptions);\n return resolved;\n }\n\n return sendRequest(request, sendRequestOptions);\n };\n\n /** Reconstruct a Request instance from a previously serialized JSON representation. */\n static fromJSON = <\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint extends string,\n NewClient extends ClientInstance,\n NewHasPayload extends true | false = false,\n NewHasParams extends true | false = false,\n NewHasQuery extends true | false = false,\n >(\n client: NewClient,\n json: RequestJSON<\n Request<\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint,\n NewClient,\n NewHasPayload,\n NewHasParams,\n NewHasQuery\n >\n >,\n ) => {\n return new Request<\n NewResponse,\n NewPayload,\n NewQueryParams,\n NewLocalError,\n NewEndpoint,\n NewClient,\n NewHasPayload,\n NewHasParams,\n NewHasQuery\n >(client, json.requestOptions, json);\n };\n}\n","import type { AdapterInstance, ResponseType } from \"adapter\";\nimport type {\n CacheOptionsType,\n CacheAsyncStorageType,\n CacheStorageType,\n CacheValueType,\n CacheSetState,\n RequestCacheType,\n} from \"cache\";\nimport { getCacheData, getCacheEvents, replaceEqualDeep } from \"cache\";\nimport type { ClientInstance } from \"client\";\nimport type { ResponseDetailsType, LoggerMethods } from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport { Request, scopeKey } from \"request\";\nimport type { ExtractAdapterType, ExtractErrorType, ExtractResponseType } from \"types\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * Cache class handles the data exchange with the dispatchers.\n *\n * @note\n * Keys used to save the values are created dynamically on the Request class\n *\n */\nexport class Cache<Adapter extends AdapterInstance> {\n public emitter = new EventEmitter();\n public events: ReturnType<typeof getCacheEvents>;\n\n public storage: CacheStorageType;\n public lazyStorage?: CacheAsyncStorageType = undefined;\n public version: string;\n public garbageCollectors = new Map<string, ReturnType<typeof setTimeout>>();\n private logger: LoggerMethods;\n private client: ClientInstance<{ adapter: Adapter }>;\n\n constructor(public options?: CacheOptionsType) {\n const { storage = new Map<string, CacheValueType>(), lazyStorage, version = \"0.0.1\" } = options ?? {};\n\n this.emitter?.setMaxListeners(1000);\n this.events = getCacheEvents(this.emitter);\n\n this.storage = storage;\n this.version = version;\n this.lazyStorage = lazyStorage;\n }\n\n /** Initialize the cache with a client reference, set up logging, and start garbage collection. */\n initialize = (client: ClientInstance<{ adapter: Adapter }>) => {\n this.client = client;\n this.logger = client.loggerManager.initialize(client, \"Cache\");\n\n // Going back from offline should re-trigger garbage collection\n client.appManager.events.onOnline(() => {\n [...this.storage.keys()].forEach(this.scheduleGarbageCollector);\n });\n\n [...this.storage.keys()].forEach(this.scheduleGarbageCollector);\n\n return this;\n };\n\n /**\n * Set the cache data to the storage\n * @param request\n * @param response\n * @returns\n */\n set = <Request extends RequestCacheType<RequestInstance>>(\n request: Request,\n response: CacheSetState<\n ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>> &\n ResponseDetailsType\n > & { hydrated?: boolean },\n ): void => {\n this.logger.debug({ title: \"Processing cache response\", type: \"system\", extra: { request, response } });\n const { cacheKey, cache, staleTime, cacheTime, scope } = request;\n const storageKey = scopeKey(cacheKey, scope);\n const previousCacheData = this.storage.get<\n ExtractResponseType<Request>,\n ExtractErrorType<Request>,\n ExtractAdapterType<Request>\n >(storageKey);\n\n // Once refresh error occurs we don't want to override already valid data in our cache with the thrown error\n // We need to check it against cache and return last valid data we have\n const processedResponse = typeof response === \"function\" ? response(previousCacheData || null) : response;\n const data = getCacheData(previousCacheData, processedResponse);\n\n // Keep references of the unchanged data parts, so deeply equal responses don't produce new objects\n if (request.structuralSharing !== false && previousCacheData) {\n data.data = replaceEqualDeep(previousCacheData.data, data.data);\n }\n\n const newCacheData: CacheValueType<any, any, ExtractAdapterType<Request>> = {\n ...data,\n scope,\n staleTime,\n version: this.version,\n cacheKey,\n cacheTime,\n cached: !!request.cache,\n };\n\n const isServerMode = this.client.mode === \"server\";\n const isCachingAllowed = cache && (!isServerMode || !!(request as any).scope);\n\n // Only success data is valid for the cache store\n if (processedResponse.success && isCachingAllowed) {\n this.logger.debug({ title: \"Saving response to cache storage\", type: \"system\", extra: { request, data } });\n this.storage.set<Response, Error, ExtractAdapterType<Request>>(storageKey, newCacheData);\n this.lazyStorage?.set<Response, Error, ExtractAdapterType<Request>>(storageKey, newCacheData);\n this.client.triggerPlugins(\"onCacheItemChange\", {\n cache: this,\n cacheKey,\n prevData: (previousCacheData || null) as CacheValueType<any, any, AdapterInstance>,\n newData: newCacheData as CacheValueType<any, any, AdapterInstance>,\n });\n\n this.scheduleGarbageCollector(storageKey);\n } else {\n // If request should not use cache - just emit response data\n this.logger.debug({ title: \"Prevented saving response to cache\", type: \"system\", extra: { request, data } });\n }\n\n this.logger.debug({ title: \"Emitting cache response\", type: \"system\", extra: { request, data } });\n this.events.emitCacheData<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>(\n newCacheData,\n );\n };\n\n /**\n * Update the cache data with partial response data\n * @param request\n * @param partialResponse\n * @returns\n */\n update = <Request extends RequestCacheType<RequestInstance>>(\n request: Request,\n partialResponse: CacheSetState<\n Partial<\n ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>> &\n ResponseDetailsType\n >\n >,\n ): void => {\n this.logger.debug({ title: \"Processing cache update\", type: \"system\", extra: { request, partialResponse } });\n const { cacheKey, scope } = request;\n const storageKey = scopeKey(cacheKey, scope);\n const cachedData = this.storage.get<\n ExtractResponseType<Request>,\n ExtractErrorType<Request>,\n ExtractAdapterType<Request>\n >(storageKey);\n\n const processedResponse =\n typeof partialResponse === \"function\" ? partialResponse(cachedData || null) : partialResponse;\n if (cachedData) {\n this.set(request, { ...cachedData, ...processedResponse });\n }\n };\n\n /**\n * Get particular record from storage by cacheKey. It will trigger lazyStorage to emit lazy load event for reading it's data.\n * @param cacheKey\n * @returns\n */\n get = <Response, Error>(cacheKey: string): CacheValueType<Response, Error, Adapter> | undefined => {\n this.getLazyResource<Response, Error>(cacheKey);\n const cachedData = this.storage.get<Response, Error, Adapter>(cacheKey);\n return cachedData;\n };\n\n /**\n * Get sync storage keys, lazyStorage keys will not be included\n * @returns\n */\n keys = (): string[] => {\n const values = this.storage.keys();\n\n return [...values];\n };\n\n /**\n * Delete record from storages and trigger invalidation event\n * @param cacheKey\n */\n delete = (cacheKey: string): void => {\n this.logger.debug({ title: \"Deleting cache element\", type: \"system\", extra: { cacheKey } });\n this.storage.delete(cacheKey);\n this.lazyStorage?.delete(cacheKey);\n\n this.client.triggerPlugins(\"onCacheItemDelete\", {\n cache: this,\n cacheKey,\n });\n\n this.events.emitDelete(cacheKey);\n };\n\n /**\n * Invalidate cache by cacheKey or partial matching with RegExp\n * It emits invalidation event for each matching cacheKey and sets staleTime to 0 to indicate out of time cache\n * Called without arguments it invalidates every cached element.\n * @param cacheKeys - cacheKey or Request instance or RegExp for partial matching (defaults to all elements)\n */\n invalidate = (cacheKeys: string | RegExp | RequestInstance | (string | RegExp | RequestInstance)[] = /.*/) => {\n this.logger.debug({ title: \"Revalidating cache element\", type: \"system\", extra: { cacheKeys } });\n\n const onInvalidate = (key: string | RegExp | RequestInstance) => {\n const keys = [...this.storage.keys()];\n const handleInvalidation = (invalidateStorageKey: string, notifyCacheKey: string = invalidateStorageKey) => {\n const value = this.storage.get(invalidateStorageKey);\n if (value) {\n this.storage.set(invalidateStorageKey, { ...value, staleTime: 0 });\n }\n\n this.client.triggerPlugins(\"onCacheItemInvalidate\", {\n cache: this,\n cacheKey: notifyCacheKey,\n });\n\n this.events.emitInvalidation(notifyCacheKey);\n };\n\n if (key instanceof Request) {\n handleInvalidation(scopeKey(key.cacheKey, key.scope), key.cacheKey);\n } else if (typeof key === \"string\") {\n handleInvalidation(key);\n } else if (keys.length > 0) {\n keys.forEach((entityKey) => {\n if (key.test(entityKey)) {\n handleInvalidation(entityKey);\n }\n });\n }\n };\n\n if (Array.isArray(cacheKeys)) {\n cacheKeys.forEach(onInvalidate.bind(this));\n } else {\n onInvalidate.bind(this)(cacheKeys);\n }\n };\n\n /**\n * Used to receive data from lazy storage\n * @param cacheKey\n */\n getLazyResource = async <Response, Error>(\n cacheKey: string,\n ): Promise<CacheValueType<Response, Error, Adapter> | undefined> => {\n const data = await this.lazyStorage?.get<Response, Error, Adapter>(cacheKey);\n const syncData = this.storage.get<Response, Error, Adapter>(cacheKey);\n\n // No data in lazy storage\n const hasLazyData = this.lazyStorage && data;\n if (hasLazyData) {\n const now = Date.now();\n const isNewestData = syncData ? syncData.responseTimestamp < data.responseTimestamp : true;\n const isStaleData = data.staleTime <= now - data.responseTimestamp;\n const isValidLazyData = data.version === this.version;\n\n if (!isValidLazyData) {\n this.lazyStorage?.delete(cacheKey);\n }\n if (isNewestData && !isStaleData && isValidLazyData) {\n this.storage.set<Response, Error, Adapter>(cacheKey, data);\n this.events.emitCacheData<Response, Error, Adapter>({ ...data, cacheKey, cached: true });\n return data;\n }\n }\n\n const isValidData = syncData?.version === this.version;\n if (syncData && !isValidData) {\n this.delete(cacheKey);\n }\n return syncData;\n };\n\n /**\n * Used to receive keys from lazy storage only\n */\n getLazyKeys = async () => {\n const keys = (await this.lazyStorage?.keys()) || [];\n\n return [...new Set(keys)];\n };\n\n /**\n * Used to receive deduplicated keys from both sync storage and lazy storage\n */\n getAllKeys = async () => {\n const keys = await this.lazyStorage?.keys();\n const asyncKeys = [...(keys || [])];\n const syncKeys = [...this.storage.keys()];\n\n return [...new Set([...asyncKeys, ...syncKeys])];\n };\n\n /**\n * Schedule garbage collection for given key\n * @param cacheKey\n * @returns\n */\n scheduleGarbageCollector = (cacheKey: string) => {\n // We need to make sure that all of the values will be removed, also that we have the proper data\n const cacheData = this.storage.get(cacheKey);\n\n // Clear running garbage collectors for given key\n clearTimeout(this.garbageCollectors.get(cacheKey));\n\n // Garbage collect\n if (cacheData) {\n const timeLeft = cacheData.cacheTime + cacheData.responseTimestamp - Date.now();\n // null\n if (cacheData.cacheTime === null) {\n this.logger.debug({ title: \"Cache time is null\", type: \"system\", extra: { cacheKey } });\n }\n // Infinity\n else if (\n (cacheData.cacheTime !== null && JSON.stringify(cacheData.cacheTime) === \"null\") ||\n cacheData.cacheTime === Infinity\n ) {\n this.logger.debug({ title: \"Cache time is Infinite\", type: \"system\", extra: { cacheKey } });\n }\n // Run garbage collector\n else if (timeLeft >= 0) {\n this.garbageCollectors.set(\n cacheKey,\n setTimeout(() => {\n if (this.client.appManager.isOnline) {\n this.logger.info({ title: \"Garbage collecting cache data\", type: \"system\", extra: { cacheKey } });\n this.delete(cacheKey);\n }\n }, timeLeft),\n );\n }\n // Delete if value is stale and we are online\n else if (this.client.appManager.isOnline) {\n this.logger.info({ title: \"Garbage collecting cache data\", type: \"system\", extra: { cacheKey } });\n this.delete(cacheKey);\n }\n }\n };\n\n /**\n * Clear cache storages\n */\n clear = async (): Promise<void> => {\n this.garbageCollectors.forEach((timeout) => clearTimeout(timeout));\n this.storage.clear();\n };\n}\n","import type { ResponseDetailsType } from \"managers\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtractAdapterResolvedType } from \"types\";\n\nexport const getCacheData = <T extends RequestInstance>(\n previousResponse: ExtractAdapterResolvedType<T> | undefined,\n response: ExtractAdapterResolvedType<T> & ResponseDetailsType,\n): ExtractAdapterResolvedType<T> & ResponseDetailsType => {\n const { data, success } = response;\n\n const previousData = !success && previousResponse ? previousResponse.data : null;\n const computedData = data || previousData;\n\n return { ...response, data: computedData };\n};\n\nexport const getInvalidateKey = (): string => {\n return `invalidate`;\n};\nexport const getInvalidateByKey = (key: string): string => {\n return `${key}_invalidate`;\n};\nexport const getDeleteKey = (): string => {\n return `delete`;\n};\nexport const getDeleteByKey = (key: string): string => {\n return `${key}_delete`;\n};\nexport const getCacheByKey = (key: string): string => {\n return `${key}_cache`;\n};\nexport const getCacheKey = (): string => {\n return `cache`;\n};\n\n/**\n * Check if value is a plain object (object literal or `Object.create(null)`).\n * Class instances, Dates, Maps, Blobs etc. are not plain objects.\n */\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (Object.prototype.toString.call(value) !== \"[object Object]\") {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === null || prototype === Object.prototype;\n};\n\nconst isPlainArray = (value: unknown): value is unknown[] => {\n return Array.isArray(value) && Object.keys(value).length === value.length;\n};\n\n/**\n * Structural sharing - returns `next` with every part that is deeply equal to `prev` replaced by the `prev` reference.\n * When both values are deeply equal the `prev` reference is returned, so consumers can rely on `===` checks.\n * Only plain objects and arrays are traversed, other values are compared with `Object.is`.\n * @param prev previous value\n * @param next incoming value\n * @returns `next` sharing unchanged references with `prev`\n */\nexport const replaceEqualDeep = <T>(prev: unknown, next: T): T => {\n if (Object.is(prev, next)) {\n return prev as T;\n }\n\n const isArray = isPlainArray(prev) && isPlainArray(next);\n if (!isArray && !(isPlainObject(prev) && isPlainObject(next))) {\n return next;\n }\n\n const prevItems = prev as Record<string, unknown>;\n const nextItems = next as Record<string, unknown>;\n const prevKeys = Object.keys(prevItems);\n const nextKeys = Object.keys(nextItems);\n const copy: Record<string, unknown> = isArray ? ([] as unknown as Record<string, unknown>) : {};\n\n let equalItems = 0;\n nextKeys.forEach((key) => {\n const prevValue = prevItems[key];\n const nextValue = nextItems[key];\n const value = replaceEqualDeep(prevValue, nextValue);\n copy[key] = value;\n // undefined values are equal only when the key existed before\n // eslint-disable-next-line prefer-object-has-own -- Object.hasOwn is not available in older runtimes\n if (value === prevValue && (value !== undefined || Object.prototype.hasOwnProperty.call(prevItems, key))) {\n equalItems += 1;\n }\n });\n\n return (prevKeys.length === nextKeys.length && equalItems === prevKeys.length ? prev : copy) as T;\n};\n","import type { AdapterInstance } from \"adapter\";\nimport type { CacheValueType } from \"cache\";\nimport { getInvalidateByKey, getInvalidateKey, getCacheByKey, getCacheKey, getDeleteKey, getDeleteByKey } from \"cache\";\nimport type EventEmitter from \"events\";\n\n/** Create the cache event emitters and listeners for data changes, invalidation, and deletion. */\nexport const getCacheEvents = (emitter: EventEmitter) => ({\n /**\n * Set cache data\n * @param data\n */\n emitCacheData: <Response, Error, Adapter extends AdapterInstance>(\n data: CacheValueType<Response, Error, Adapter> & { cached: boolean },\n isTriggeredExternally = false,\n ): void => {\n emitter.emit(getCacheKey(), data, isTriggeredExternally);\n emitter.emit(getCacheByKey(data.cacheKey), data, isTriggeredExternally);\n },\n /**\n * Invalidate cache values event\n */\n emitInvalidation: (cacheKey: string, isTriggeredExternally = false): void => {\n emitter.emit(getInvalidateKey(), cacheKey, isTriggeredExternally);\n emitter.emit(getInvalidateByKey(cacheKey), isTriggeredExternally);\n },\n /**\n * Delete of cache values\n */\n emitDelete: (cacheKey: string, isTriggeredExternally = false): void => {\n emitter.emit(getDeleteKey(), cacheKey, isTriggeredExternally);\n emitter.emit(getDeleteByKey(cacheKey), isTriggeredExternally);\n },\n /**\n * Cache data listener for all keys\n * @param callback\n * @returns\n */\n onData: <Response, Error, Adapter extends AdapterInstance>(\n callback: (data: CacheValueType<Response, Error, Adapter> & { cached: boolean }) => void,\n ): VoidFunction => {\n emitter.on(getCacheKey(), callback);\n return () => emitter.removeListener(getCacheKey(), callback);\n },\n /**\n * Cache data listener filtered by a specific cache key\n * @param cacheKey\n * @param callback\n * @returns\n */\n onDataByKey: <Response, Error, Adapter extends AdapterInstance>(\n cacheKey: string,\n callback: (data: CacheValueType<Response, Error, Adapter>) => void,\n ): VoidFunction => {\n emitter.on(getCacheByKey(cacheKey), callback);\n return () => emitter.removeListener(getCacheByKey(cacheKey), callback);\n },\n /**\n * Cache invalidation listener\n * @param callback\n * @returns\n */\n onInvalidate: (callback: (cacheKey: string) => void): VoidFunction => {\n emitter.on(getInvalidateKey(), callback);\n return () => emitter.removeListener(getInvalidateKey(), callback);\n },\n /**\n * Cache invalidation listener\n * @param cacheKey\n * @param callback\n * @returns\n */\n onInvalidateByKey: (cacheKey: string, callback: () => void): VoidFunction => {\n emitter.on(getInvalidateByKey(cacheKey), callback);\n return () => emitter.removeListener(getInvalidateByKey(cacheKey), callback);\n },\n /** Cache deletion listener for all keys */\n onDelete: (callback: (cacheKey: string) => void): VoidFunction => {\n emitter.on(getDeleteKey(), callback);\n return () => emitter.removeListener(getDeleteKey(), callback);\n },\n /** Cache deletion listener filtered by a specific cache key */\n onDeleteByKey: (cacheKey: string, callback: () => void): VoidFunction => {\n emitter.on(getDeleteByKey(cacheKey), callback);\n return () => emitter.removeListener(getDeleteByKey(cacheKey), callback);\n },\n});\n","export enum DispatcherMode {\n ONE_BY_ONE = \"one-by-one\",\n ALL_AT_ONCE = \"all-at-once\",\n PREVIOUS_CANCELED = \"previous-canceled\",\n DEDUPLICATED = \"deduplicated\",\n}\n","import type { QueueDataType, RunningRequestsChangeType } from \"dispatcher\";\nimport {\n getDispatcherChangeKey,\n getDispatcherChangeByKey,\n getDispatcherStatusKey,\n getDispatcherStatusByKey,\n getDispatcherDrainedKey,\n getDispatcherDrainedByKey,\n getDispatcherRunningKey,\n getDispatcherRunningByKey,\n} from \"dispatcher\";\nimport type EventEmitter from \"events\";\nimport type { RequestInstance } from \"request\";\n\nexport const getDispatcherEvents = (emitter: EventEmitter) => ({\n emitDrained: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherDrainedKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherDrainedByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitQueueStatusChanged: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherStatusKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherStatusByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitQueueChanged: <Request extends RequestInstance>(\n values: QueueDataType<Request>,\n isTriggeredExternally?: boolean,\n ): void => {\n emitter.emit(getDispatcherChangeKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherChangeByKey(values.queryKey), values, isTriggeredExternally);\n },\n emitRunningRequestsChanged: (values: RunningRequestsChangeType, isTriggeredExternally?: boolean): void => {\n emitter.emit(getDispatcherRunningKey(), values, isTriggeredExternally);\n emitter.emit(getDispatcherRunningByKey(values.queryKey), values, isTriggeredExternally);\n },\n /**\n * When queue becomes empty\n * @param callback\n * @returns\n */\n onDrained: <Request extends RequestInstance>(callback: (values: QueueDataType<Request>) => void): VoidFunction => {\n emitter.on(getDispatcherDrainedKey(), callback);\n return () => emitter.removeListener(getDispatcherDrainedKey(), callback);\n },\n /**\n * When queue becomes empty\n * @param queryKey\n * @param callback\n * @returns\n */\n onDrainedByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherDrainedByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherDrainedByKey(queryKey), callback);\n },\n /**\n * When queue status change from enabled to paused or vice versa\n * @param callback\n * @returns\n */\n onQueueStatusChange: <Request extends RequestInstance>(\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherStatusKey(), callback);\n return () => emitter.removeListener(getDispatcherStatusKey(), callback);\n },\n /**\n * When queue status change from enabled to paused or vice versa\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueStatusChangeByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherStatusByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherStatusByKey(queryKey), callback);\n },\n /**\n * When new elements are added or removed from the queue\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueChange: <Request extends RequestInstance>(\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherChangeKey(), callback);\n return () => emitter.removeListener(getDispatcherChangeKey(), callback);\n },\n /**\n * When new elements are added or removed from the queue\n * @param queryKey\n * @param callback\n * @returns\n */\n onQueueChangeByKey: <Request extends RequestInstance>(\n queryKey: string,\n callback: (values: QueueDataType<Request>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherChangeByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherChangeByKey(queryKey), callback);\n },\n /**\n * When requests start or stop running (sent, finished, canceled or cleared)\n * @param callback\n * @returns\n */\n onRunningRequestsChange: (callback: (values: RunningRequestsChangeType) => void): VoidFunction => {\n emitter.on(getDispatcherRunningKey(), callback);\n return () => emitter.removeListener(getDispatcherRunningKey(), callback);\n },\n /**\n * When requests start or stop running (sent, finished, canceled or cleared) for given queryKey\n * @param queryKey\n * @param callback\n * @returns\n */\n onRunningRequestsChangeByKey: (\n queryKey: string,\n callback: (values: RunningRequestsChangeType) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherRunningByKey(queryKey), callback);\n return () => emitter.removeListener(getDispatcherRunningByKey(queryKey), callback);\n },\n});\n","import type { AdapterInstance, RequestResponseType } from \"adapter\";\nimport { getErrorMessage } from \"adapter\";\nimport type { ClientInstance } from \"client\";\nimport type {\n QueueDataType,\n DispatcherOptionsType,\n DispatcherStorageType,\n ResolvedQueueDataType,\n ResolvedQueueItemType,\n RunningRequestValueType,\n} from \"dispatcher\";\nimport { getRequestType, canRetryRequest, getDispatcherEvents, DispatcherMode } from \"dispatcher\";\nimport type { ResponseDetailsType, LoggerMethods } from \"managers\";\nimport type { RequestInstance, RequestJSON } from \"request\";\nimport { Request, scopeKey } from \"request\";\nimport { EventEmitter } from \"utils\";\n\n/**\n * Dispatcher controls and manages the requests that are going to be executed with adapter. It manages them based on the options provided with request.\n * This class can also run them with different modes like deduplication, cancelation, queueing or run-all-at-once mode. With it's help we can pause,\n * stop, start and cancel requests.\n */\nexport class Dispatcher<Adapter extends AdapterInstance> {\n public emitter = new EventEmitter();\n public events = getDispatcherEvents(this.emitter);\n public storage: DispatcherStorageType = new Map<string, QueueDataType<any>>();\n\n private requestCount = new Map<string, number>();\n private runningRequests = new Map<string, RunningRequestValueType[]>();\n\n private logger: LoggerMethods;\n private client: ClientInstance<{ adapter: Adapter }>;\n\n constructor(public options?: DispatcherOptionsType) {\n this.emitter?.setMaxListeners(1000);\n\n if (this.options?.storage) {\n this.storage = this.options.storage;\n }\n }\n\n // eslint-disable-next-line class-methods-use-this\n private isRequestJSON = (\n request: RequestInstance | RequestJSON<RequestInstance>,\n ): request is RequestJSON<RequestInstance> => {\n return !(request instanceof Request);\n };\n\n initialize = (client: ClientInstance<{ adapter: Adapter }>) => {\n this.client = client;\n this.logger = client.loggerManager.initialize(client, \"Dispatcher\");\n\n // Going back from offline should re-trigger all requests\n this.client.appManager.events.onOnline(() => {\n this.flush();\n });\n\n return this;\n };\n\n // *********************************************************************\n // *********************************************************************\n // Queue\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Start request handling by queryKey\n */\n start = (queryKey: string) => {\n // Change status to running\n const queue = this.getQueue(queryKey);\n\n // Start the queue when its stopped\n queue.stopped = false;\n this.setQueue(queryKey, queue);\n this.flushQueue(queryKey);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"running\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Pause request queue, but do not cancel already started requests\n */\n pause = (queryKey: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n\n queue.stopped = true;\n this.setQueue(queryKey, queue);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"paused\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Stop request queue and cancel all started requests - those will be treated like not started\n */\n stop = (queryKey: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n\n queue.stopped = true;\n this.setQueue(queryKey, queue);\n\n // Cancel running requests\n this.cancelRunningRequests(queryKey);\n this.client.triggerPlugins(\"onDispatcherQueueRunning\", { dispatcher: this, queue, status: \"stopped\" });\n this.events.emitQueueStatusChanged(queue);\n };\n\n /**\n * Return all queue keys currently tracked by the dispatcher storage\n */\n getQueuesKeys = () => {\n return [...this.storage.keys()];\n };\n\n /**\n * Return queue state object.\n * Automatically reconstructs any serialized (JSON) requests back into\n * proper Request class instances so the rest of the pipeline can rely on\n * having a real `RequestInstance`.\n */\n getQueue = <R extends RequestInstance = RequestInstance>(queryKey: string): ResolvedQueueDataType<R> => {\n const initialQueueState: ResolvedQueueDataType<R> = { queryKey, requests: [], stopped: false };\n const storedEntity = this.storage.get<R>(queryKey);\n\n if (!storedEntity) {\n return initialQueueState;\n }\n\n const resolvedRequests: ResolvedQueueItemType<R>[] = storedEntity.requests.map((item) => {\n if (this.isRequestJSON(item.request)) {\n return { ...item, request: this.client.fromJSON(item.request as RequestJSON<RequestInstance>) as unknown as R };\n }\n return item as ResolvedQueueItemType<R>;\n });\n\n return { ...storedEntity, requests: resolvedRequests };\n };\n\n /**\n * Return request from queue state\n */\n getRequest = <Request extends RequestInstance = RequestInstance>(queryKey: string, requestId: string) => {\n const initialQueueState: QueueDataType<Request> = { queryKey, requests: [], stopped: false };\n const storedEntity = this.storage.get<Request>(queryKey) || initialQueueState;\n\n return storedEntity.requests.find((req) => req.requestId === requestId);\n };\n\n /**\n * Get value of the active queue status based on the stopped status\n */\n getIsActiveQueue = (queryKey: string) => {\n const queue = this.getQueue(queryKey);\n const hasAvailableRequests = queue.requests.some((req) => !req.stopped);\n const isRunningQueue = !queue.stopped;\n return hasAvailableRequests && isRunningQueue;\n };\n\n /**\n * Add new element to storage\n */\n addQueueItem = <Request extends RequestInstance = RequestInstance>(\n queryKey: string,\n element: ResolvedQueueItemType<Request>,\n ) => {\n const queue = this.getQueue<Request>(queryKey);\n queue.requests.push(element);\n\n this.client.triggerPlugins(\"onDispatcherItemAdded\", { dispatcher: this, queue, queueItem: element });\n\n this.setQueue<Request>(queryKey, queue);\n };\n\n /**\n * Set new queue storage value\n */\n setQueue = <Request extends RequestInstance = RequestInstance>(\n queryKey: string,\n queue: ResolvedQueueDataType<Request>,\n ) => {\n this.storage.set<Request>(queryKey, queue as QueueDataType<Request>);\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherQueueCreated\", { dispatcher: this, queue });\n this.events.emitQueueChanged(queue);\n\n return queue;\n };\n\n /**\n * Clear requests from queue cache\n */\n clearQueue = (queryKey: string) => {\n const queue = this.getQueue(queryKey);\n const newQueue = { queryKey, requests: [], stopped: queue.stopped };\n this.storage.set(queryKey, newQueue);\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherQueueCleared\", { dispatcher: this, queue: newQueue });\n this.events.emitQueueChanged(newQueue);\n this.events.emitDrained(newQueue);\n\n return newQueue;\n };\n\n /**\n * Method used to flush the queue requests\n */\n flushQueue = async (queryKey: string) => {\n const queue = this.getQueue(queryKey);\n const runningRequests = this.getRunningRequests(queryKey);\n const queueItem = queue.requests.find((request) => !request.stopped);\n\n const isStopped = queue && queue.stopped;\n const isOffline = !this.client.appManager.isOnline;\n const isConcurrent = !queueItem?.request.queued;\n const isInactive = runningRequests.length === 0;\n const isEmpty = !queueItem;\n\n // When there are no requests to flush, when its stopped, there is running request\n // or there is no request to trigger - we don't want to perform actions\n if (isStopped || isOffline || isEmpty) {\n this.logger.debug({ title: \"Skipping queue trigger\", type: \"system\", extra: { isStopped, isOffline, isEmpty } });\n } else if (isConcurrent) {\n queue.requests.forEach((element) => {\n if (!this.hasRunningRequest(queryKey, element.requestId)) {\n this.performRequest(element);\n }\n });\n } else if (isInactive) {\n await this.performRequest(queueItem);\n this.flushQueue(queryKey);\n }\n };\n\n /**\n * Flush all available requests from all queues\n */\n flush = async () => {\n const keys = this.getQueuesKeys();\n\n // eslint-disable-next-line no-restricted-syntax\n for (const key of keys) {\n const storageItem = this.getQueue(key);\n\n if (storageItem) {\n this.flushQueue(key);\n }\n }\n };\n\n /**\n * Clear all running requests and storage\n */\n clear = () => {\n const keys = this.getQueuesKeys();\n keys.forEach((queryKey) => this.cancelRunningRequests(queryKey));\n\n [...this.runningRequests.keys()].forEach((queryKey) => this.setRunningRequests(queryKey, []));\n this.runningRequests.clear();\n this.storage.clear();\n this.client.triggerPlugins(\"onDispatcherCleared\", { dispatcher: this });\n };\n\n // *********************************************************************\n // *********************************************************************\n // Requests\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Start particular request\n */\n startRequest = (queryKey: string, requestId: string) => {\n // Change status to running\n const queue = this.getQueue(queryKey);\n const request = queue.requests.find((element) => element.requestId === requestId);\n\n // Start the queue when its stopped\n if (request) {\n request.stopped = false;\n this.setQueue(queryKey, queue);\n this.flushQueue(queryKey);\n this.events.emitQueueStatusChanged(queue);\n }\n };\n\n /**\n * Stop particular request\n */\n stopRequest = (queryKey: string, requestId: string) => {\n // Change state to stopped\n const queue = this.getQueue(queryKey);\n const request = queue.requests.find((element) => element.requestId === requestId);\n\n if (request) {\n request.stopped = true;\n this.setQueue(queryKey, queue);\n\n // Cancel running requests\n this.cancelRunningRequest(queryKey, requestId);\n this.events.emitQueueStatusChanged(queue);\n }\n };\n\n /**\n * Get currently running requests from all queryKeys\n */\n getAllRunningRequests = () => {\n return [...this.runningRequests.values()].flat();\n };\n\n /**\n * Get currently running requests\n */\n getRunningRequests = (queryKey: string) => {\n return this.runningRequests.get(queryKey) || [];\n };\n\n /**\n * Get running request by id\n */\n getRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n return runningRequests.find((req) => req.requestId === requestId);\n };\n\n /**\n * Single place for changing the running requests - notifies about the change\n */\n private setRunningRequests = (queryKey: string, runningRequests: RunningRequestValueType[]) => {\n const previousRequests = this.getRunningRequests(queryKey);\n this.runningRequests.set(queryKey, runningRequests);\n if (\n previousRequests.length !== runningRequests.length ||\n previousRequests.some((req, i) => req !== runningRequests[i])\n ) {\n this.events.emitRunningRequestsChanged({ queryKey, runningRequests });\n }\n };\n\n /**\n * Add request to the running requests list\n */\n addRunningRequest = (queryKey: string, requestId: string, request: RequestInstance): RunningRequestValueType => {\n const newRunningRequest = { requestId, request, timestamp: Date.now() };\n this.setRunningRequests(queryKey, [...this.getRunningRequests(queryKey), newRunningRequest]);\n return newRunningRequest;\n };\n\n /**\n * Get the value based on the currently running requests\n */\n hasRunningRequests = (queryKey: string) => {\n return this.getRunningRequests(queryKey).length > 0;\n };\n\n /**\n * Check if request is currently processing\n */\n hasRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n return !!runningRequests.some((req) => req.requestId === requestId);\n };\n\n /**\n * Cancel all started requests, but do NOT remove it from main storage\n */\n cancelRunningRequests = (queryKey: string) => {\n this.runningRequests.get(queryKey)?.forEach((req) => {\n const ak = scopeKey(req.request.abortKey, req.request.scope);\n this.client.requestManager.abortByRequestId(ak, req.requestId);\n });\n this.deleteRunningRequests(queryKey);\n };\n /**\n * Cancel started request, but do NOT remove it from main storage\n */\n cancelRunningRequest = (queryKey: string, requestId: string) => {\n const requests = this.getRunningRequests(queryKey).filter((request) => {\n if (request.requestId === requestId) {\n const ak = scopeKey(request.request.abortKey, request.request.scope);\n this.client.requestManager.abortByRequestId(ak, request.requestId);\n return false;\n }\n return true;\n });\n\n this.setRunningRequests(queryKey, requests);\n };\n\n /**\n * Delete all started requests, but do NOT clear it from queue and do NOT cancel them\n */\n deleteRunningRequests = (queryKey: string) => {\n this.setRunningRequests(queryKey, []);\n };\n\n /**\n * Delete request by id, but do NOT clear it from queue and do NOT cancel them\n */\n deleteRunningRequest = (queryKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queryKey);\n this.setRunningRequests(\n queryKey,\n runningRequests.filter((req) => req.requestId !== requestId),\n );\n };\n\n /**\n * Get count of requests from the same queryKey\n */\n getQueueRequestCount = (queryKey: string) => {\n return this.requestCount.get(queryKey) || 0;\n };\n\n /**\n * Add request count to the queryKey\n */\n incrementQueueRequestCount = (queryKey: string) => {\n const count = this.requestCount.get(queryKey) || 0;\n this.requestCount.set(queryKey, count + 1);\n };\n\n /**\n * Create storage element from request\n */\n // eslint-disable-next-line class-methods-use-this\n createStorageItem = <R extends RequestInstance>(request: R): ResolvedQueueItemType<R> => {\n const requestId = this.client.unstable_requestIdMapper(request);\n return {\n requestId,\n timestamp: Date.now(),\n request,\n retries: 0,\n stopped: false,\n resolved: false,\n };\n };\n\n // *********************************************************************\n // *********************************************************************\n // Dispatching\n // *********************************************************************\n // *********************************************************************\n\n /**\n * Add request to the dispatcher handler\n */\n add = (request: RequestInstance) => {\n const queryKey = scopeKey(request.queryKey, request.scope);\n\n // Create dump of the request to allow storing it in localStorage, AsyncStorage or any other\n // This way we don't save the Class but the instruction of the request to be done\n const storageItem = this.createStorageItem(request);\n const { requestId } = storageItem;\n\n const queue = this.getQueue(queryKey);\n const [latestRequest] = queue.requests.slice(-1);\n const requestType = getRequestType(request, latestRequest);\n\n this.logger.debug({ title: \"Adding request to queue\", type: \"system\", extra: { requestType, request, requestId } });\n\n switch (requestType) {\n case DispatcherMode.ONE_BY_ONE: {\n // Requests will go one by one\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n case DispatcherMode.PREVIOUS_CANCELED: {\n // Cancel all previous on-going requests\n this.cancelRunningRequests(queryKey);\n this.clearQueue(queryKey);\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n case DispatcherMode.DEDUPLICATED: {\n this.client.requestManager.events.emitDeduplicated({\n request: latestRequest.request,\n requestId,\n deduplicatedRequest: request,\n });\n // Return the running requestId to fulfill the events\n return latestRequest.requestId;\n }\n default: {\n this.addQueueItem(queryKey, storageItem);\n this.flushQueue(queryKey);\n return requestId;\n }\n }\n };\n\n /**\n * Delete from the storage and cancel request\n */\n delete = (queryKey: string, requestId: string, abortKey: string) => {\n this.logger.debug({ title: \"Deleting request\", type: \"system\", extra: { queryKey, requestId, abortKey } });\n const queue = this.getQueue(queryKey);\n const queueItem = queue.requests.find((req) => req.requestId === requestId);\n\n if (!queueItem) {return;}\n\n queue.requests = queue.requests.filter((req) => req.requestId !== requestId);\n this.storage.set(queryKey, queue);\n\n // Clean controllers\n if (this.hasRunningRequest(queryKey, requestId)) {\n this.deleteRunningRequest(queryKey, requestId);\n this.client.requestManager.abortByRequestId(abortKey, requestId);\n }\n\n // Emit Queue Changes\n this.client.triggerPlugins(\"onDispatcherItemDeleted\", { queue, dispatcher: this, queueItem });\n\n this.events.emitQueueChanged(queue);\n this.client.requestManager.events.emitRemove({\n requestId,\n request: queueItem.request,\n resolved: queueItem.resolved,\n });\n\n if (queue.requests.length === 0) {\n this.client.triggerPlugins(\"onDispatcherQueueDrained\", { queue, dispatcher: this });\n this.events.emitDrained(queue);\n }\n\n return queue;\n };\n\n /**\n * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted\n * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved\n */\n performRequest = async (storageItem: ResolvedQueueItemType) => {\n const { request, requestId } = storageItem;\n this.logger.debug({ title: \"Performing request\", type: \"system\", extra: { request, requestId } });\n\n const { retry, retryTime, queryKey: rawQueryKey, abortKey: rawAbortKey, offline, scope } = request;\n const queryKey = scopeKey(rawQueryKey, scope);\n const abortKey = scopeKey(rawAbortKey, scope);\n const { adapter, requestManager, cache, appManager } = this.client;\n\n const canRetry = canRetryRequest(storageItem.retries, retry);\n // When offline not perform any request\n const isOffline = !appManager.isOnline && offline;\n // When request with this id was triggered again\n const isAlreadyRunning = this.hasRunningRequest(queryKey, requestId);\n const isStopped = storageItem.stopped;\n\n if (isOffline || isAlreadyRunning || isStopped) {\n return this.logger.warning({\n title: \"Unable to perform request\",\n type: \"system\",\n extra: { isOffline, isAlreadyRunning, isStopped },\n });\n }\n\n // Additionally keep the running request to possibly abort it later\n const runningRequest = this.addRunningRequest(queryKey, requestId, request);\n\n // Propagate the loading to all connected hooks\n requestManager.events.emitLoading({\n request,\n requestId,\n loading: true,\n isRetry: !!storageItem.retries,\n isOffline,\n });\n\n // Trigger Request\n this.incrementQueueRequestCount(queryKey);\n // Listen for aborting\n requestManager.addAbortController(abortKey, requestId);\n\n const response: RequestResponseType<any> = await adapter.fetch(request, requestId);\n\n // TODO: improve this\n // eslint-disable-next-line no-param-reassign\n storageItem.resolved = true;\n // Stop listening for aborting\n requestManager.removeAbortController(abortKey, requestId);\n // Do not continue the request handling when it got stopped and request was unsuccessful\n // Or when the request was aborted/canceled\n const isOfflineResponseStatus = !appManager.isOnline;\n // If there is no running request with this id, it means it was cancelled and removed during send\n const isCancelMessage = getErrorMessage(\"abort\").message === response.error?.message;\n const isCanceled = !this.hasRunningRequest(queryKey, requestId) || isCancelMessage;\n\n // Remove running request, must be called after isCancelled\n this.deleteRunningRequest(queryKey, requestId);\n\n const shouldRetryOnError = response.success || !canRetry || !request.retryOnError || request.retryOnError(response);\n const willRetry = !response.success && canRetry && shouldRetryOnError && !isCanceled && !isOfflineResponseStatus;\n\n const requestDetails: ResponseDetailsType = {\n isCanceled,\n isOffline: isOfflineResponseStatus,\n retries: storageItem.retries,\n willRetry,\n addedTimestamp: storageItem.timestamp,\n triggerTimestamp: runningRequest.timestamp,\n requestTimestamp: response.requestTimestamp,\n responseTimestamp: response.responseTimestamp,\n };\n\n // Global response emitter to handle request execution\n requestManager.events.emitResponse({ request, requestId, response, details: requestDetails });\n\n // Turn off loading\n requestManager.events.emitLoading({\n request,\n requestId,\n loading: false,\n isRetry: !!storageItem.retries,\n isOffline,\n });\n\n // Cache event to emit the data inside and store it\n cache.set(request, { ...response, ...requestDetails });\n this.logger.debug({\n title: \"Dispatcher processing response\",\n type: \"system\",\n extra: { requestId, request, response, details: requestDetails },\n });\n\n // On cancelled\n if (isCanceled) {\n const queue = this.getQueue(queryKey);\n const queueItem = queue.requests.find((req) => req.requestId === requestId);\n\n // do not remove cancelled request as it may be result of manual queue pause\n // if abort was done without stop action we can remove request\n if (!queue.stopped && !queueItem?.stopped) {\n this.logger.debug({ title: \"Request paused\", type: \"system\", extra: { response, requestDetails, request } });\n return this.delete(queryKey, requestId, abortKey);\n }\n return this.logger.debug({\n title: \"Request canceled\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n }\n // On offline\n if (!response.success && isOfflineResponseStatus) {\n // if we don't want to keep offline request - just delete them\n if (!offline) {\n this.logger.warning({\n title: \"Removing non-offline request\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n return this.delete(queryKey, requestId, abortKey);\n }\n // do not remove request from store as we want to re-send it later\n return this.logger.debug({\n title: \"Awaiting for network restoration\",\n type: \"system\",\n extra: { response, requestDetails, request },\n });\n }\n // On success\n if (response.success) {\n this.delete(queryKey, requestId, abortKey);\n return this.logger.debug({\n title: \"Successful response, removing request from queue.\",\n type: \"system\",\n extra: {\n response,\n requestDetails,\n request,\n },\n });\n }\n // On retry\n if (willRetry) {\n this.logger.debug({ title: \"Waiting for retry\", type: \"system\", extra: { response, requestDetails, request } });\n // Perform retry once request is failed\n setTimeout(() => {\n this.logger.warning({\n title: \"Error response, performing retry\",\n type: \"request\",\n extra: { response, requestDetails, request, requestId },\n });\n this.performRequest({\n ...storageItem,\n retries: storageItem.retries + 1,\n });\n }, retryTime || 0);\n } else {\n if (request.retry) {\n this.logger.error({\n title: \"All retries have been used. Removing request from queue.\",\n type: \"request\",\n extra: { response, requestDetails, request, requestId },\n });\n }\n this.delete(queryKey, requestId, abortKey);\n }\n };\n}\n","import type { ResolvedQueueItemType } from \"dispatcher\";\nimport { DispatcherMode } from \"dispatcher\";\nimport type { RequestInstance } from \"request\";\n\n// Events\n\nexport const getDispatcherDrainedKey = (): string => {\n return `drained-event`;\n};\nexport const getDispatcherDrainedByKey = (key: string): string => {\n return `${key}-drained-event`;\n};\nexport const getDispatcherStatusKey = (): string => {\n return `status-event`;\n};\nexport const getDispatcherStatusByKey = (key: string): string => {\n return `${key}-status-event`;\n};\nexport const getDispatcherChangeKey = (): string => {\n return `change-event`;\n};\nexport const getDispatcherChangeByKey = (key: string): string => {\n return `${key}-change-event`;\n};\nexport const getDispatcherRunningKey = (): string => {\n return `running-event`;\n};\nexport const getDispatcherRunningByKey = (key: string): string => {\n return `${key}-running-event`;\n};\n\n// Requesting\n\nexport const getIsEqualTimestamp = (currentTimestamp: number, threshold: number, queueTimestamp?: number): boolean => {\n if (!queueTimestamp) {\n return false;\n }\n return queueTimestamp - currentTimestamp <= threshold;\n};\n\nexport const canRetryRequest = (currentRetries: number, retry: number | undefined) => {\n if (retry && currentRetries < retry) {\n return true;\n }\n return false;\n};\n\nconst isInDeduplicateRange = (request: RequestInstance, latestRequest: ResolvedQueueItemType) => {\n if (request.deduplicateTime) {\n return Date.now() - latestRequest.timestamp <= request.deduplicateTime;\n }\n return true;\n};\n\nexport const getRequestType = (request: RequestInstance, latestRequest: ResolvedQueueItemType | undefined) => {\n const { queued, cancelable, deduplicate, used } = request;\n const canDeduplicate = latestRequest ? isInDeduplicateRange(request, latestRequest) : false;\n // Only join requests that are genuinely still ongoing. A resolved item already emitted its\n // response (a late joiner would wait forever), and a stopped item may never fire at all.\n const isOngoing = latestRequest ? !latestRequest.resolved && !latestRequest.stopped : false;\n\n if (queued) {\n return DispatcherMode.ONE_BY_ONE;\n }\n if (cancelable) {\n return DispatcherMode.PREVIOUS_CANCELED;\n }\n // A request marked with setUsed(true) is an intentional resend, like the auth interceptor\n // retrying after a token refresh. Deduplicating it against the original in-flight request\n // would deadlock: the retry would wait for a response that is blocked on the interceptor.\n if (canDeduplicate && isOngoing && deduplicate && !used) {\n return DispatcherMode.DEDUPLICATED;\n }\n return DispatcherMode.ALL_AT_ONCE;\n};\n","import { Time } from \"constants/time.constants\";\n\nimport type { HttpAdapterExtraType } from \"./http-adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\nexport const xhrExtra: HttpAdapterExtraType = {\n headers: {},\n};\n","import type { QueryParamsType, QueryParamType, QueryParamValuesType } from \"adapter\";\nimport { getErrorMessage } from \"adapter\";\nimport { stringifyDefaultOptions } from \"client\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtractErrorType, EmptyTypes } from \"types\";\n\nimport type { BufferEncoding, QueryStringifyOptionsType } from \"./http-adapter.types\";\n\n// Utils\n\nexport const getResponseHeaders = (headersString: string): Record<string, string> => {\n const arr = headersString.trim().split(/[\\r\\n]+/);\n\n const headers: Record<string, string> = {};\n arr.forEach((line) => {\n const parts = line.split(\": \");\n const header = parts.shift();\n const value = parts.join(\": \");\n if (header) {\n headers[header] = value;\n }\n });\n\n return headers;\n};\n\n// Responses\n\nexport const parseResponse = (response: string | unknown) => {\n try {\n return JSON.parse(response as string);\n } catch {\n return response;\n }\n};\n\nexport const handleResponse = (responseChunks: any[], responseType: string, responseEncoding: BufferEncoding) => {\n const bufferedResponse = Buffer.concat(responseChunks);\n switch (responseType) {\n case \"arraybuffer\": {\n return bufferedResponse;\n }\n case \"json\": {\n return parseResponse(bufferedResponse.toString(responseEncoding));\n }\n default: {\n return bufferedResponse.toString(responseEncoding);\n }\n }\n};\n\nexport const parseErrorResponse = <T extends RequestInstance>(response: unknown): ExtractErrorType<T> => {\n return response ? parseResponse(response) : (getErrorMessage() as ExtractErrorType<T>);\n};\n\n// Stringify\n\nconst isValidValue = (options: QueryStringifyOptionsType) => {\n return (value: QueryParamType) => {\n const { skipNull, skipEmptyString } = options;\n\n if (skipEmptyString && value === undefined) {\n return false;\n }\n if (skipEmptyString && value === \"\") {\n return false;\n }\n if (skipNull && value === null) {\n return false;\n }\n return true;\n };\n};\n\nconst encodeValue = (\n value: string,\n { encode, strict }: Pick<QueryStringifyOptionsType, \"encode\" | \"strict\">,\n): string => {\n if (encode && strict) {\n return encodeURIComponent(value).replaceAll(/[!'()*]/g, (s) => `%${s.codePointAt(0)!.toString(16).toUpperCase()}`);\n }\n if (encode) {\n return encodeURIComponent(value);\n }\n return value;\n};\n\nconst parseValue = (value: QueryParamValuesType, options: QueryStringifyOptionsType): string => {\n if (value instanceof Date) {\n return options.dateParser?.(value) || value.toISOString();\n }\n\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n return options.objectParser?.(value) || JSON.stringify(value);\n }\n\n return String(value);\n};\n\nconst encodeParams = (key: string, value: QueryParamType, options: QueryStringifyOptionsType) => {\n const shouldSkip = !isValidValue(options)(value);\n\n if (!key || shouldSkip) {\n return \"\";\n }\n\n return `${encodeValue(key, options)}=${encodeValue(parseValue(value as QueryParamValuesType, options), options)}`;\n};\n\nconst encodeArray = (key: string, array: QueryParamValuesType[], options: QueryStringifyOptionsType): string => {\n const { arrayFormat, arraySeparator } = options;\n const separator = arraySeparator || \"|\";\n const encodedKey = encodeValue(key, options);\n\n return array\n .filter(isValidValue(options))\n .reduce<string[]>((acc, value, index) => {\n const encodedValue = encodeValue(parseValue(value, options), options);\n\n switch (arrayFormat) {\n case \"index\": {\n acc.push(`${encodedKey}[${encodeValue(String(index), options)}]=${encodedValue}`);\n break;\n }\n case \"bracket\": {\n acc.push(`${encodedKey}[]=${encodedValue}`);\n break;\n }\n case \"comma\": {\n const keyValue = (acc.length === 0 && `${encodedKey}=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(\",\")];\n }\n case \"separator\": {\n const keyValue = (acc.length === 0 && `${encodedKey}=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(separator)];\n }\n case \"bracket-separator\": {\n const keyValue = (acc.length === 0 && `${encodedKey}[]=`) || \"\";\n return [[...acc, `${keyValue}${encodedValue}`].join(separator)];\n }\n default: {\n acc.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return acc;\n }, [])\n .join(\"&\");\n};\n\nexport const stringifyQueryParams = (\n queryParams: QueryParamsType | string | EmptyTypes,\n options?: QueryStringifyOptionsType,\n): string => {\n // Merge with defaults so a partial config (e.g. `{ arrayFormat: \"comma\" }`) keeps encoding and skipping enabled\n const config: QueryStringifyOptionsType = { ...stringifyDefaultOptions, ...options };\n\n if (!queryParams || Object.keys(queryParams).length === 0) {\n return \"\";\n }\n\n if (typeof queryParams === \"string\") {\n const hasQuestionMark = queryParams[0] === \"?\";\n return hasQuestionMark ? queryParams : `?${queryParams}`;\n }\n\n const stringified = Object.entries(queryParams)\n .map(([key, value]): string => {\n if (Array.isArray(value)) {\n return encodeArray(key, value, config);\n }\n\n return encodeParams(key, value, config);\n })\n .filter(Boolean)\n .join(\"&\");\n\n if (stringified) {\n return `?${stringified}`;\n }\n return \"\";\n};\n","import type { QueryParamsType } from \"adapter\";\nimport { HttpMethods, SAFE_HTTP_METHODS } from \"constants/http.constants\";\nimport type { HttpMethodsType, HttpStatusType } from \"types\";\n\nimport { Adapter } from \"../adapter/adapter\";\nimport { defaultTimeout, xhrExtra } from \"./http-adapter.constants\";\nimport type { HttpAdapterExtraType, FetchAdapterOptionsType } from \"./http-adapter.types\";\nimport { parseErrorResponse, parseResponse, stringifyQueryParams } from \"./http-adapter.utils\";\n\nconst defaultExtra = xhrExtra;\n\nexport const getAdapter = () =>\n new Adapter<\n FetchAdapterOptionsType,\n HttpMethodsType,\n HttpStatusType,\n HttpAdapterExtraType,\n QueryParamsType | string | null,\n undefined,\n string\n >({\n name: \"http\",\n defaultMethod: HttpMethods.GET,\n defaultExtra,\n systemErrorStatus: 0 as number,\n systemErrorExtra: defaultExtra,\n })\n .setQueryParamsMapper(stringifyQueryParams)\n // Safe reads (GET, QUERY) deduplicate by default: concurrent identical requests collapse\n // into one network call. Explicit `deduplicate` in request options still wins.\n .setRequestDefaults((options) => {\n const method = options.method ?? HttpMethods.GET;\n if (SAFE_HTTP_METHODS.includes(method)) {\n return { deduplicate: true };\n }\n return {};\n })\n .setFetcher(\n async ({\n request,\n url,\n endpoint,\n queryParams,\n adapterOptions,\n headers,\n payload,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n getAbortController,\n onResponseProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onSuccess,\n }) => {\n const { method } = request;\n const fullUrl = `${url}${endpoint}${queryParams}`;\n\n const controller = getAbortController();\n const { timeout: timeoutMs = defaultTimeout, streaming = false, ...restOptions } = adapterOptions || {};\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n // Abort listener handles user-initiated aborts (e.g. request.abort())\n // For fetch, onAbort is a no-op since the signal is already passed to fetch()\n const unmountListener = createAbortListener({\n status: 0,\n extra: defaultExtra,\n });\n\n if (timeoutMs > 0 && controller) {\n timeoutId = setTimeout(() => {\n timedOut = true;\n unmountListener();\n controller.abort();\n }, timeoutMs);\n }\n\n onBeforeRequest();\n onRequestStart();\n\n try {\n const init: RequestInit = {\n method,\n headers: headers as Record<string, string>,\n signal: controller?.signal,\n ...restOptions,\n };\n\n if (payload && method !== \"GET\" && method !== \"HEAD\") {\n init.body = payload as BodyInit;\n\n if (typeof payload === \"string\") {\n const total = new Blob([payload]).size;\n onRequestProgress({ total, loaded: total } as ProgressEvent);\n }\n }\n\n onRequestEnd();\n\n const response = await fetch(fullUrl, init);\n\n if (timeoutId) {clearTimeout(timeoutId);}\n\n onResponseStart();\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n const extra: HttpAdapterExtraType = { headers: responseHeaders };\n const { status } = response;\n\n if (streaming && response.body) {\n onResponseEnd();\n unmountListener();\n\n if (response.ok) {\n onSuccess({ data: response.body as any, status, extra });\n } else {\n const errorBody = await response.text();\n const error = parseErrorResponse(errorBody);\n onError({ error, status, extra });\n }\n } else {\n let body: string;\n\n if (response.body && typeof response.body.getReader === \"function\") {\n const reader = response.body.getReader();\n const contentLength = parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n let receivedLength = 0;\n const chunks: Uint8Array[] = [];\n\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 chunks.push(value);\n receivedLength += value.length;\n onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);\n }\n\n const allChunks = new Uint8Array(receivedLength);\n let position = 0;\n // eslint-disable-next-line no-restricted-syntax\n for (const chunk of chunks) {\n allChunks.set(chunk, position);\n position += chunk.length;\n }\n body = new TextDecoder().decode(allChunks);\n } else {\n body = await response.text();\n }\n\n onResponseEnd();\n unmountListener();\n\n if (response.ok) {\n const data = parseResponse(body);\n onSuccess({ data, status, extra });\n } else {\n const error = parseErrorResponse(body);\n onError({ error, status, extra });\n }\n }\n } catch (error: any) {\n if (timeoutId) {clearTimeout(timeoutId);}\n unmountListener();\n\n if (controller?.signal?.aborted) {\n if (timedOut) {\n onTimeoutError({ status: 0, extra: defaultExtra });\n }\n return;\n }\n\n onError({ error, status: 0, extra: defaultExtra });\n }\n },\n );\n","import type { HttpAdapterType } from \"http-adapter/http-adapter.types\";\n\nimport { getAdapter } from \"./http-adapter.fetch\";\n\nexport const HttpAdapter = (): HttpAdapterType => {\n return getAdapter();\n};\n","import type { ResponseType } from \"adapter\";\nimport type { RequestInstance } from \"request\";\nimport type { ExtendRequest, ExtractClientAdapterType } from \"types\";\n\nimport type {\n ClientInstance,\n ClientMode,\n ClientModeOption,\n RequestInterceptorType,\n ResponseInterceptorType,\n} from \"./client.types\";\n\n/** Picks effective {@link ClientMode}: explicit override, else environment detection. */\nexport function resolveClientMode(modeOption: ClientModeOption | undefined): ClientMode {\n if (modeOption === \"client\" || modeOption === \"server\") {\n return modeOption;\n }\n\n const inBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\n if (inBrowser) {\n return \"client\";\n }\n\n return \"server\";\n}\n\nexport const interceptRequest = async (interceptors: RequestInterceptorType[], request: RequestInstance) => {\n let newRequest = request;\n if (!request.requestOptions.disableRequestInterceptors) {\n // eslint-disable-next-line no-restricted-syntax\n for (const interceptor of interceptors) {\n // eslint-disable-next-line no-await-in-loop\n newRequest = (await interceptor(request)) as RequestInstance;\n if (!newRequest) {throw new Error(\"Request modifier must return request\");}\n }\n }\n return newRequest;\n};\n\nexport const interceptResponse = async <GlobalErrorType, Client extends ClientInstance>(\n interceptors: ResponseInterceptorType<Client>[],\n response: ResponseType<any, GlobalErrorType, ExtractClientAdapterType<Client>>,\n request: ExtendRequest<RequestInstance, { client: Client }>,\n) => {\n let newResponse = response;\n if (!request.requestOptions.disableResponseInterceptors) {\n // eslint-disable-next-line no-restricted-syntax\n for (const interceptor of interceptors) {\n // eslint-disable-next-line no-await-in-loop\n newResponse = await interceptor(response, request);\n if (!newResponse) {throw new Error(\"Response modifier must return data\");}\n }\n }\n return newResponse;\n};\n","import type { AdapterInstance, ResponseType } from \"adapter\";\nimport { Cache } from \"cache\";\nimport type {\n ClientErrorType,\n ClientInstance,\n ClientMode,\n ClientOptionsType,\n RequestGenericType,\n RequestInterceptorType,\n ResponseInterceptorType,\n} from \"client\";\nimport { Dispatcher } from \"dispatcher\";\nimport type { HttpAdapterType } from \"http-adapter\";\nimport { parseResponse, HttpAdapter } from \"http-adapter\";\nimport type { LogLevel } from \"managers\";\nimport { AppManager, LoggerManager, RequestManager } from \"managers\";\nimport type { PluginInstance, PluginMethodParameters, PluginMethods } from \"plugin\";\nimport type { RequestInstance, RequestJSON, RequestOptionsType } from \"request\";\nimport { getRequestKey, getSimpleKey, Request, scopeKey } from \"request\";\nimport type {\n EmptyTypes,\n TypeWithDefaults,\n ExtractAdapterMethodType,\n ExtractAdapterOptionsType,\n ExtractAdapterQueryParamsType,\n ExtractAdapterEndpointType,\n ExtractUnionAdapter,\n HydrateDataType,\n HydrationOptions,\n ExtractAdapterDefaultQueryParamsType,\n ExtractAdapterRequestOptionsType,\n} from \"types\";\nimport { getUniqueRequestId } from \"utils\";\n\nimport { interceptRequest, interceptResponse, resolveClientMode } from \"./client.utils\";\n\n/**\n * **Client** is a class that allows you to configure the connection with the server and then use it to create\n * requests. It allows you to set global defaults for the requests configuration, query params configuration.\n * It is also orchestrator for all of the HyperFetch modules like Cache, Dispatcher, AppManager, LoggerManager,\n * RequestManager and more.\n */\nexport class Client<\n GlobalErrorType extends ClientErrorType = Error,\n Adapter extends AdapterInstance = HttpAdapterType,\n> {\n url: string;\n readonly mode: ClientMode;\n public debug: boolean;\n\n // Private\n unstable_onErrorCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onSuccessCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onResponseCallbacks: ResponseInterceptorType<ClientInstance>[] = [];\n unstable_onAuthCallbacks: RequestInterceptorType[] = [];\n unstable_onRequestCallbacks: RequestInterceptorType[] = [];\n\n // Managers\n loggerManager: LoggerManager = new LoggerManager();\n requestManager: RequestManager = new RequestManager();\n appManager: AppManager;\n\n // Config\n adapter: Adapter;\n cache: Cache<Adapter>;\n fetchDispatcher: Dispatcher<Adapter>;\n submitDispatcher: Dispatcher<Adapter>;\n isMockerEnabled = true;\n\n // Registered requests effect\n plugins: PluginInstance[] = [];\n\n /** @internal */\n unstable_abortKeyMapper: (request: RequestInstance) => string = getSimpleKey;\n\n /** @internal */\n unstable_cacheKeyMapper: (request: RequestInstance) => string = getRequestKey;\n\n /** @internal */\n unstable_queryKeyMapper: (request: RequestInstance) => string = getRequestKey;\n\n /** @internal */\n unstable_requestIdMapper: (request: RequestInstance) => string = getUniqueRequestId;\n\n // Logger\n logger = this.loggerManager.initialize(this, \"Client\");\n\n constructor(public options: ClientOptionsType<Client<GlobalErrorType, Adapter>>) {\n const { url, appManager, cache, fetchDispatcher, submitDispatcher, mode: modeOption } = this.options;\n this.url = url;\n this.mode = resolveClientMode(modeOption);\n this.adapter = HttpAdapter() as Adapter;\n\n this.appManager = appManager?.() || new AppManager();\n this.cache = cache?.() || new Cache();\n this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();\n this.submitDispatcher = submitDispatcher?.() || new Dispatcher();\n\n // IMPORTANT: Do not change initialization order as it's crucial for dependencies injection\n this.adapter.initialize(this);\n this.appManager.initialize();\n this.cache.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.fetchDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.submitDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n }\n\n /**\n * Set the base url used by the next requests - e.g. when switching tenants, regions or environments at runtime.\n * Cache keys don't include the base url, so data cached for the previous url stays in place unless you pass\n * `invalidate: true`. Pass `abort: true` to cancel the requests that are still in progress for the previous url.\n * @param url new base url\n * @param options.abort abort all ongoing requests\n * @param options.invalidate invalidate the cache (and requests aborted by `abort`), so active consumers refetch\n */\n setUrl = (url: string, options: { abort?: boolean; invalidate?: boolean } = {}): Client<GlobalErrorType, Adapter> => {\n if (url === this.url) {\n return this;\n }\n\n const { abort = false, invalidate = false } = options;\n const runningRequests = this.fetchDispatcher.getAllRunningRequests().map(({ request }) => request);\n\n this.url = url;\n\n if (abort) {\n this.requestManager.abortAll();\n }\n if (invalidate) {\n this.cache.invalidate();\n // Aborted requests never land in the cache, so the full invalidation above would not notify their consumers\n if (abort && runningRequests.length > 0) {\n this.cache.invalidate(runningRequests);\n }\n }\n\n return this;\n };\n\n /**\n * This method enables the logger usage and display the logs in console\n */\n setDebug = (enabled: boolean): Client<GlobalErrorType, Adapter> => {\n this.debug = enabled;\n return this;\n };\n\n /**\n * Set the logger severity of the messages displayed to the console\n */\n setLogLevel = (severity: LogLevel): Client<GlobalErrorType, Adapter> => {\n this.loggerManager.setSeverity(severity);\n return this;\n };\n\n /**\n * Set the new logger instance to the Client\n */\n setLogger = (callback: (Client: ClientInstance) => LoggerManager): Client<GlobalErrorType, Adapter> => {\n this.loggerManager = callback(this);\n this.loggerManager.initialize(this, \"Client\");\n return this;\n };\n\n /**\n * Set globally if mocking should be enabled or disabled for all client requests.\n * @param isMockerEnabled\n */\n setEnableGlobalMocking = (isMockerEnabled: boolean) => {\n this.isMockerEnabled = isMockerEnabled;\n return this;\n };\n\n /**\n * Set custom http adapter to handle graphql, rest, firebase or others\n */\n setAdapter = <NewAdapter extends AdapterInstance>(adapter: NewAdapter): Client<GlobalErrorType, NewAdapter> => {\n this.adapter = adapter as unknown as Adapter;\n this.adapter.initialize(this);\n return this as unknown as Client<GlobalErrorType, NewAdapter>;\n };\n\n /**\n * Method of manipulating requests before sending the request. We can for example add custom header with token to the request which request had the auth set to true.\n */\n onAuth = (callback: RequestInterceptorType): Client<GlobalErrorType, Adapter> => {\n this.unstable_onAuthCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on auth.\n * */\n removeOnAuthInterceptors = (callbacks: RequestInterceptorType[]): Client<GlobalErrorType, Adapter> => {\n this.unstable_onAuthCallbacks = this.unstable_onAuthCallbacks.filter((callback) => !callbacks.includes(callback));\n return this;\n };\n\n /**\n * Method for intercepting error responses. It can be used for example to refresh tokens.\n */\n onError = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onErrorCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on error.\n * */\n removeOnErrorInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onErrorCallbacks = this.unstable_onErrorCallbacks.filter((callback) => !callbacks.includes(callback));\n return this;\n };\n\n /**\n * Method for intercepting success responses.\n */\n onSuccess = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onSuccessCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on success.\n * */\n removeOnSuccessInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onSuccessCallbacks = this.unstable_onSuccessCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Method of manipulating requests before sending the request.\n */\n onRequest = (callback: RequestInterceptorType): Client<GlobalErrorType, Adapter> => {\n this.unstable_onRequestCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing listeners on request.\n * */\n removeOnRequestInterceptors = (callbacks: RequestInterceptorType[]): Client<GlobalErrorType, Adapter> => {\n this.unstable_onRequestCallbacks = this.unstable_onRequestCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Method for intercepting any responses.\n */\n onResponse = <ErrorType = null>(\n callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>,\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onResponseCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for removing response interceptors.\n * */\n removeOnResponseInterceptors = (\n callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],\n ): Client<GlobalErrorType, Adapter> => {\n this.unstable_onResponseCallbacks = this.unstable_onResponseCallbacks.filter(\n (callback) => !callbacks.includes(callback),\n );\n return this;\n };\n\n /**\n * Add persistent plugins which trigger on the request lifecycle\n */\n addPlugin = (plugin: PluginInstance) => {\n this.plugins.push(plugin);\n\n plugin.initialize(this);\n plugin.trigger(\"onMount\", { client: this });\n\n return this;\n };\n\n /**\n * Remove plugins from Client\n */\n removePlugin = (plugin: PluginInstance) => {\n const pluginCount = this.plugins.length;\n this.plugins = this.plugins.filter((p) => p !== plugin);\n\n if (this.plugins.length !== pluginCount) {\n plugin.trigger(\"onUnmount\", { client: this });\n }\n\n return this;\n };\n\n triggerPlugins = <Key extends keyof PluginMethods<Client>>(key: Key, data: PluginMethodParameters<Key, Client>) => {\n if (this.plugins.length === 0) {\n return this;\n }\n\n this.plugins.forEach((plugin) => {\n plugin.trigger(key, data);\n });\n\n return this;\n };\n\n /**\n * Key setters\n */\n\n /** Set a custom mapper that generates the abort key used to cancel in-flight requests. */\n setAbortKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_abortKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the cache key used to store and retrieve cached responses. */\n setCacheKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_cacheKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the query key used to identify requests in the dispatcher queue. */\n setQueryKeyMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_queryKeyMapper = callback;\n return this;\n };\n /** Set a custom mapper that generates the unique request ID for deduplication and tracking. */\n setRequestIdMapper = (callback: (request: RequestInstance) => string) => {\n this.unstable_requestIdMapper = callback;\n return this;\n };\n\n /**\n * Helper used by http adapter to apply the modifications on response error\n * @private\n */\n unstable_modifyAuth = async (request: RequestInstance) => interceptRequest(this.unstable_onAuthCallbacks, request);\n\n /**\n * Private helper to run async pre-request processing\n * @private\n */\n unstable_modifyRequest = async (request: RequestInstance) =>\n interceptRequest(this.unstable_onRequestCallbacks, request);\n\n /**\n * Private helper to run async on-error response processing\n * @private\n */\n unstable_modifyErrorResponse = async (\n response: ResponseType<any, GlobalErrorType, Adapter>,\n request: RequestInstance,\n ) => interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onErrorCallbacks, response, request);\n\n /**\n * Private helper to run async on-success response processing\n * @private\n */\n unstable_modifySuccessResponse = async (\n response: ResponseType<any, GlobalErrorType, Adapter>,\n request: RequestInstance,\n ) => interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onSuccessCallbacks, response, request);\n\n /**\n * Private helper to run async response processing\n * @private\n */\n unstable_modifyResponse = async (response: ResponseType<any, GlobalErrorType, Adapter>, request: RequestInstance) =>\n interceptResponse<GlobalErrorType, ClientInstance>(this.unstable_onResponseCallbacks, response, request);\n\n /**\n * Reconstruct a Request class instance from its serialized JSON form.\n * Useful when dispatcher storage serializes queue data (e.g. MMKV, AsyncStorage)\n * and the deserialized request loses its class identity.\n */\n fromJSON = <RequestProperties extends RequestGenericType<ExtractAdapterQueryParamsType<Adapter>> = {}>(\n json: RequestJSON<RequestInstance>,\n ) => {\n type DefaultQueryParams = ExtractAdapterDefaultQueryParamsType<Adapter>;\n\n type Response = TypeWithDefaults<RequestProperties, \"response\", undefined>;\n type Payload = TypeWithDefaults<RequestProperties, \"payload\", undefined>;\n type LocalError = TypeWithDefaults<RequestProperties, \"error\", GlobalErrorType>;\n type QueryParams = TypeWithDefaults<RequestProperties, \"queryParams\", DefaultQueryParams, never>;\n type Endpoint = TypeWithDefaults<RequestProperties, \"endpoint\", string>;\n\n return Request.fromJSON(this as unknown as ClientInstance, json) as unknown as Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string ? Endpoint : string,\n Client<GlobalErrorType, Adapter>\n >;\n };\n\n /**\n * Clears the Client instance and remove all listeners on it's dependencies\n */\n clear = () => {\n const { appManager, cache, fetchDispatcher, submitDispatcher } = this.options;\n\n this.requestManager.abortControllers.clear();\n this.fetchDispatcher.clear();\n this.submitDispatcher.clear();\n this.cache.clear();\n\n this.requestManager.emitter.removeAllListeners();\n this.fetchDispatcher.emitter.removeAllListeners();\n this.submitDispatcher.emitter.removeAllListeners();\n this.cache.emitter.removeAllListeners();\n this.appManager.unmount();\n\n this.cache = cache?.() || new Cache();\n this.appManager = appManager?.() || new AppManager();\n this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();\n this.submitDispatcher = submitDispatcher?.() || new Dispatcher();\n\n // DO NOT CHANGE INITIALIZATION ORDER\n this.appManager.initialize();\n this.cache.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.fetchDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n this.submitDispatcher.initialize(this as unknown as ClientInstance<{ adapter: Adapter }>);\n };\n\n /**\n * Hydrate your SSR cache data\n * @param hydrationData\n * @param options\n */\n hydrate = (\n hydrationData: (HydrateDataType | EmptyTypes)[],\n options?: Partial<HydrationOptions> | ((item: HydrateDataType) => Partial<HydrationOptions>),\n ) => {\n hydrationData?.forEach((item) => {\n if (!item) {\n return;\n }\n\n const { cacheKey, scope, response, ...fallbackOptions } = item;\n const defaults = {\n cache: true,\n override: true,\n } satisfies Partial<HydrationOptions>;\n const config =\n typeof options === \"function\"\n ? { ...defaults, ...fallbackOptions, ...options(item) }\n : { ...defaults, ...fallbackOptions, ...options };\n\n if (!config.override) {\n const cachedData = this.cache.get(scopeKey(cacheKey, scope));\n if (cachedData) {\n return;\n }\n }\n\n const parsedData = parseResponse(response);\n this.cache.set({ ...config, cacheKey, scope }, parsedData);\n });\n };\n\n /**\n * Create requests based on the Client setup\n *\n * @template Response Your response\n */\n createRequest = <RequestProperties extends RequestGenericType<ExtractAdapterQueryParamsType<Adapter>> = {}>(\n /**\n * `createRequest` must be initialized twice(currying).\n *\n * ✅ Good:\n * ```ts\n * const request = createRequest<RequestProperties>()(params)\n * ```\n * ⛔ Bad:\n * ```ts\n * const request = createRequest<RequestProperties>(params)\n * ```\n *\n * We are using currying to achieve auto generated types for the endpoint string.\n *\n * This solution will be removed once https://github.com/microsoft/TypeScript/issues/10571 get resolved.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _USE_DOUBLE_INITIALIZATION?: never,\n ) => {\n type DefaultQueryParams = ExtractAdapterDefaultQueryParamsType<Adapter>;\n\n type Response = TypeWithDefaults<RequestProperties, \"response\", undefined>;\n type Payload = TypeWithDefaults<RequestProperties, \"payload\", undefined>;\n type LocalError = TypeWithDefaults<RequestProperties, \"error\", GlobalErrorType>;\n /** we pass never to prevent the type from being empty, but we allow it to be undefined (optional) */\n type QueryParams = TypeWithDefaults<RequestProperties, \"queryParams\", DefaultQueryParams, never>;\n\n return <\n EndpointType extends ExtractAdapterEndpointType<Adapter>,\n AdapterOptions extends ExtractAdapterOptionsType<Adapter>,\n MethodType extends ExtractAdapterMethodType<Adapter>,\n >(\n params: RequestOptionsType<EndpointType, AdapterOptions, MethodType> & ExtractAdapterRequestOptionsType<Adapter>,\n ) => {\n type Endpoint = TypeWithDefaults<RequestProperties, \"endpoint\", EndpointType>;\n\n const endpoint = this.adapter.unstable_endpointMapper(params.endpoint);\n\n // Splitting this type prevents \"Type instantiation is excessively deep and possibly infinite\" error\n type ExtractedAdapter = ExtractUnionAdapter<\n Adapter,\n {\n method: MethodType;\n options: AdapterOptions;\n queryParams: QueryParams;\n }\n >;\n type ExtractedAdapterType = ExtractedAdapter extends EmptyTypes ? Adapter : ExtractedAdapter;\n\n const mappedParams: RequestOptionsType<\n Endpoint extends string ? Endpoint : typeof endpoint,\n AdapterOptions,\n MethodType\n > = {\n ...params,\n endpoint: String(endpoint) as Endpoint extends string ? Endpoint : typeof endpoint,\n };\n\n const request = new Request<\n Response,\n Payload,\n QueryParams,\n LocalError,\n Endpoint extends string ? Endpoint : typeof endpoint,\n Client<GlobalErrorType, ExtractedAdapterType>\n >(this as unknown as Client<GlobalErrorType, ExtractedAdapterType>, mappedParams);\n\n this.plugins.forEach((plugin) => plugin.trigger(\"onRequestCreate\", { request }));\n\n return request;\n };\n };\n}\n","export const stringifyDefaultOptions = {\n strict: true,\n encode: true,\n arrayFormat: \"bracket\",\n arraySeparator: \"|\",\n sort: false,\n skipNull: true,\n skipEmptyString: true,\n} as const;\n","import type { ClientErrorType, ClientOptionsType } from \"client\";\nimport { Client } from \"client\";\nimport type { HttpAdapterType } from \"http-adapter\";\nimport type { TypeWithDefaults } from \"types\";\n\nexport type ClientGenericType = {\n error?: ClientErrorType;\n};\n\nexport function createClient<ClientProperties extends ClientGenericType = {}>(\n options: ClientOptionsType<Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>>>,\n): Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>, HttpAdapterType> {\n return new Client<NonNullable<TypeWithDefaults<ClientProperties, \"error\", Error>>, HttpAdapterType>(options);\n}\n","import type { ClientInstance } from \"client\";\nimport type { RequestInstance } from \"request\";\nimport { Request } from \"request\";\nimport type {\n ExtractEndpointType,\n ExtractResponseType,\n ExtractPayloadType,\n ExtractQueryParamsType,\n ExtractLocalErrorType,\n ExtractHasPayloadType,\n ExtractHasParamsType,\n ExtractHasQueryParamsType,\n ExtractMutationContextType,\n} from \"types\";\n\nexport type RecursiveSchemaType = Record<\n string, // for example users / $userId / posts / $postId\n any\n>;\n\n/**\n * Recursively walks a schema and rebuilds every `Request` leaf with the SDK's actual client\n * type injected into the `Client` generic slot. Lets users omit `client` from their\n * `RequestModel<{...}>` declarations - the SDK fills it in from the client passed to\n * `createSdk(client)`.\n *\n * Non-Request leaves (primitive values, plain types) are passed through unchanged. Nested\n * schema objects are recursed into. Depth is guarded at 10 levels to keep the type checker\n * within reasonable bounds.\n */\nexport type InjectClient<T, TClient extends ClientInstance, Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? T\n : T extends RequestInstance\n ? Request<\n ExtractResponseType<T>,\n ExtractPayloadType<T>,\n ExtractQueryParamsType<T>,\n ExtractLocalErrorType<T>,\n ExtractEndpointType<T> extends string ? ExtractEndpointType<T> : string,\n TClient,\n ExtractHasPayloadType<T> extends boolean ? ExtractHasPayloadType<T> : false,\n ExtractHasParamsType<T> extends boolean ? ExtractHasParamsType<T> : false,\n ExtractHasQueryParamsType<T> extends boolean ? ExtractHasQueryParamsType<T> : false,\n ExtractMutationContextType<T>\n >\n : T extends Record<string, any>\n ? { [K in keyof T]: InjectClient<T[K], TClient, [...Depth, unknown]> }\n : T;\n\n/**\n * Per-request defaults that can be applied via SDK configuration.\n * These mirror the chainable setters on Request (headers, cache, retry, etc.).\n */\nexport type SdkRequestDefaults = {\n headers?: HeadersInit;\n auth?: boolean;\n cache?: boolean;\n cacheTime?: number;\n staleTime?: number;\n retry?: number;\n retryTime?: number;\n cancelable?: boolean;\n queued?: boolean;\n offline?: boolean;\n deduplicate?: boolean;\n deduplicateTime?: number | null;\n structuralSharing?: boolean;\n};\n\n/**\n * Configuration value: either a static property bag or a function that receives\n * the request and returns a modified request (full access to every Request setter).\n */\nexport type SdkConfigurationValue = SdkRequestDefaults | ((request: RequestInstance) => RequestInstance);\n\n/**\n * Recursively extracts all endpoint strings from an SDK schema type.\n * Leaf nodes (keys starting with $) are RequestInstance — extract endpoint from those.\n * Other keys are nested schema segments to recurse into.\n */\ntype ExtractSdkEndpoints<T, Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? never\n : {\n [K in keyof T]: K extends `$${string}`\n ? T[K] extends RequestInstance\n ? ExtractEndpointType<T[K]>\n : never\n : T[K] extends Record<string, any>\n ? ExtractSdkEndpoints<T[K], [...Depth, unknown]>\n : never;\n }[keyof T];\n\n/**\n * Recursively extracts dot-path accessor keys from an SDK schema.\n * These mirror the SDK property chain: \"users.$get\", \"users.$userId.$get\", etc.\n */\ntype ExtractSdkPaths<T, Prefix extends string = \"\", Depth extends unknown[] = []> = Depth[\"length\"] extends 10\n ? never\n : {\n [K in keyof T & string]: T[K] extends RequestInstance\n ? `${Prefix}${K}`\n : T[K] extends Record<string, any>\n ? ExtractSdkPaths<T[K], `${Prefix}${K}.`, [...Depth, unknown]>\n : never;\n }[keyof T & string];\n\n/**\n * Builds the set of valid configuration keys from an SDK schema:\n * - \"*\" (global wildcard)\n * - exact endpoint paths extracted from RequestInstance nodes (group keys)\n * - wildcard patterns like \"/users/*\" (group keys)\n * - dot-path accessor keys like \"users.$get\" (method-specific keys)\n */\ntype SdkConfigurationKeys<Schema extends RecursiveSchemaType> =\n | \"*\"\n | ExtractSdkEndpoints<Schema>\n | `${ExtractSdkEndpoints<Schema> & string}/*`\n | ExtractSdkPaths<Schema>;\n\n/**\n * Maps endpoint paths, wildcard patterns, or dot-path accessor keys to request defaults.\n * Keys are validated against the SDK schema.\n *\n * Values can be:\n * - A plain `SdkRequestDefaults` object (shorthand for common settings)\n * - A function `(request) => request` for full access to every Request setter\n */\nexport type SdkConfigurationMap<Schema extends RecursiveSchemaType = RecursiveSchemaType> = Partial<\n Record<SdkConfigurationKeys<Schema>, SdkConfigurationValue>\n>;\n\nexport type CreateSdkOptions<Schema extends RecursiveSchemaType = RecursiveSchemaType> = {\n /** @default true */\n camelCaseToKebabCase?: boolean;\n /** @default (method) => method.toUpperCase() */\n methodTransform?: (method: string) => string;\n /** Per-endpoint request defaults */\n defaults?: SdkConfigurationMap<Schema>;\n};\n\nconst OPTIONAL_REQUEST_FIELDS = Request.OPTIONAL_FIELDS;\n\nconst getMethod = (key: string, options?: CreateSdkOptions<any>) => {\n const { methodTransform = (method: string) => method.toUpperCase() } = options ?? {};\n return methodTransform(key);\n};\n\nconst endpointMatchesPattern = (endpoint: string, pattern: string): boolean => {\n if (pattern === \"*\") {return true;}\n if (pattern === endpoint) {return true;}\n // Simple wildcard: \"/users/*\" matches \"/users/:userId\", \"/users/:userId/posts\", etc.\n if (pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -1);\n return endpoint.startsWith(prefix) || endpoint === prefix.slice(0, -1);\n }\n return false;\n};\n\nconst isDotPath = (key: string): boolean => {\n return key.includes(\".\") && !key.startsWith(\"/\");\n};\n\nconst applyObjectDefaults = (request: RequestInstance, config: SdkRequestDefaults): RequestInstance => {\n let result = request;\n if (config.headers) {result = result.setHeaders(config.headers);}\n if (config.auth !== undefined) {result = result.setAuth(config.auth);}\n if (config.cache !== undefined) {result = result.setCache(config.cache);}\n if (config.cacheTime !== undefined) {result = result.setCacheTime(config.cacheTime);}\n if (config.staleTime !== undefined) {result = result.setStaleTime(config.staleTime);}\n if (config.retry !== undefined) {result = result.setRetry(config.retry);}\n if (config.retryTime !== undefined) {result = result.setRetryTime(config.retryTime);}\n if (config.cancelable !== undefined) {result = result.setCancelable(config.cancelable);}\n if (config.queued !== undefined) {result = result.setQueued(config.queued);}\n if (config.offline !== undefined) {result = result.setOffline(config.offline);}\n if (config.deduplicate !== undefined) {result = result.setDeduplicate(config.deduplicate);}\n if (config.deduplicateTime !== undefined && config.deduplicateTime !== null) {\n result = result.setDeduplicateTime(config.deduplicateTime);\n }\n if (config.structuralSharing !== undefined) {\n result = result.setStructuralSharing(config.structuralSharing);\n }\n return result;\n};\n\nconst applyDefaults = (\n request: RequestInstance,\n context: { endpoint: string; sdkPath: string; defaults?: Partial<Record<string, SdkConfigurationValue>> },\n): RequestInstance => {\n const { endpoint, sdkPath, defaults } = context;\n if (!defaults) {return request;}\n\n let result = request;\n const entries = Object.entries(defaults);\n\n // Sort: \"*\" first, then endpoint groups (start with \"/\"), then dot-path (method-specific) last\n const globalEntries: [string, SdkConfigurationValue][] = [];\n const groupEntries: [string, SdkConfigurationValue][] = [];\n const pathEntries: [string, SdkConfigurationValue][] = [];\n\n for (let i = 0; i < entries.length; i += 1) {\n const [key, value] = entries[i];\n if (!value) {continue;}\n const entry: [string, SdkConfigurationValue] = [key, value];\n if (entry[0] === \"*\") {\n globalEntries.push(entry);\n } else if (isDotPath(entry[0])) {\n pathEntries.push(entry);\n } else {\n groupEntries.push(entry);\n }\n }\n\n const sorted = [...globalEntries, ...groupEntries, ...pathEntries];\n\n for (let i = 0; i < sorted.length; i += 1) {\n const [pattern, config] = sorted[i];\n\n let matches = false;\n if (isDotPath(pattern)) {\n matches = pattern === sdkPath;\n } else {\n matches = endpointMatchesPattern(endpoint, pattern);\n }\n\n if (matches) {\n if (typeof config === \"function\") {\n result = config(result);\n } else {\n result = applyObjectDefaults(result, config);\n }\n }\n }\n\n return result;\n};\n\nconst createRecursiveProxy = (\n client: ClientInstance,\n context: { path: string[]; sdkKeys: string[]; options?: CreateSdkOptions<any> },\n): any => {\n const { path, sdkKeys, options } = context;\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n return new Proxy(() => {}, {\n get: (_target, key: string) => {\n if (typeof key === \"symbol\" || key === \"inspect\") {\n return;\n }\n\n // Check if this is a method (starts with $) or a path segment\n let isMethod = false;\n let methodName = key;\n let pathSegment = key;\n\n if (key.startsWith(\"$\")) {\n isMethod = true;\n methodName = key.slice(1);\n pathSegment = `:${key.slice(1)}`;\n } else if (options?.camelCaseToKebabCase) {\n pathSegment = key.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n }\n\n // Build the sdk dot-path for method-specific configuration matching\n const currentSdkKeys = [...sdkKeys, key];\n const sdkPath = currentSdkKeys.join(\".\");\n\n // Always create a request assuming this is a method call\n const endpoint = `/${path.join(\"/\")}`;\n const method = getMethod(isMethod ? methodName : key, options);\n let request: RequestInstance = client.createRequest()({ endpoint, method });\n request = applyDefaults(request, { endpoint, sdkPath, defaults: options?.defaults });\n\n // But also, assume the key is a new path segment for a deeper call\n const newPath = [...path, pathSegment];\n const deeperProxy = createRecursiveProxy(client, { path: newPath, sdkKeys: currentSdkKeys, options });\n\n // Return a new proxy that wraps both the request and the deeper proxy\n return new Proxy(request, {\n get: (reqTarget, reqKey: string) => {\n // If the property exists on the request instance (like .send(), .setParams()), return it.\n // Optional fields are checked by name as well: transpilers that compile class\n // properties in loose mode (Metro on React Native) drop uninitialized field\n // declarations, and falling through to the deeper proxy would hand callers a\n // truthy path proxy where they expect undefined.\n if (reqKey in reqTarget || (OPTIONAL_REQUEST_FIELDS as readonly string[]).includes(reqKey)) {\n return reqTarget[reqKey as keyof typeof reqTarget];\n }\n // Otherwise, it's a deeper path, so delegate to the deeper proxy.\n return deeperProxy[reqKey];\n },\n });\n },\n });\n};\n\n/**\n * The fully-resolved SDK instance type returned by `createSdk`.\n *\n * The schema is rewritten via {@link InjectClient} so every `Request` leaf carries the\n * actual client type passed to `createSdk(client)` - users do not need to repeat\n * `client: AppClient` in every `RequestModel<{...}>` declaration.\n */\nexport type SdkInstance<\n Schema extends RecursiveSchemaType,\n TClient extends ClientInstance = ClientInstance,\n> = InjectClient<Schema, TClient> & {\n /**\n * Apply request defaults to the SDK. Returns a new SDK instance with the configuration applied.\n * Use \"*\" to match all endpoints, or specific endpoint strings / wildcard patterns.\n */\n $configure: (defaults: SdkConfigurationMap<Schema>) => SdkInstance<Schema, TClient>;\n};\n\nexport const createSdk = <Client extends ClientInstance, RecursiveSchema extends RecursiveSchemaType>(\n client: Client,\n options?: CreateSdkOptions<RecursiveSchema>,\n): SdkInstance<RecursiveSchema, Client> => {\n const {\n camelCaseToKebabCase = true,\n methodTransform = (method: string) => method.toUpperCase(),\n ...rest\n } = options ?? {};\n\n const mergedOptions: CreateSdkOptions<RecursiveSchema> = { camelCaseToKebabCase, methodTransform, ...rest };\n // Break inference for TypeDoc / tsserver (TS2589) — runtime value is unchanged.\n const proxy = createRecursiveProxy(client, { path: [], sdkKeys: [], options: mergedOptions as never });\n\n return new Proxy(proxy, {\n get: (target, key: string) => {\n if (key === \"$configure\") {\n return (defaults: SdkConfigurationMap<RecursiveSchema>) => {\n const existingDefaults = mergedOptions.defaults || {};\n return createSdk<Client, RecursiveSchema>(client, {\n ...mergedOptions,\n defaults: { ...existingDefaults, ...defaults } as SdkConfigurationMap<RecursiveSchema>,\n });\n };\n }\n return target[key];\n },\n }) as SdkInstance<RecursiveSchema, Client>;\n};\n\n/**\n * Type-safe factory for creating SDK configuration maps.\n *\n * @example\n * const config = createConfiguration<MySdkSchema>()({ \"*\": { retry: 3 } })\n */\nexport const createConfiguration = <Schema extends RecursiveSchemaType>() => {\n return (defaults: SdkConfigurationMap<Schema>): SdkConfigurationMap<Schema> => defaults;\n};\n"],"x_google_ignoreList":[6],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,IAAa,SAAb,MAAuF;CACrF;CACA;CAEA,SAAoC,KAAA;CAEpC,gBAAwD,EAAE;CAE1D,YAAY,QAA8C;AAAvC,OAAA,SAAA;AACjB,OAAK,OAAO,OAAO;AACnB,MAAI,OAAO,KACT,MAAK,OAAO,OAAO;;;CAKvB,cAAc,WAAmB;AAC/B,OAAK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