@hyper-fetch/core 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/.eslintrc.json +7 -0
  2. package/README.md +83 -0
  3. package/dist/builder/builder.constants.d.ts +9 -0
  4. package/dist/builder/builder.d.ts +141 -0
  5. package/dist/builder/builder.types.d.ts +45 -0
  6. package/dist/builder/builder.utils.d.ts +10 -0
  7. package/dist/builder/index.d.ts +4 -0
  8. package/dist/cache/cache.d.ts +76 -0
  9. package/dist/cache/cache.events.d.ts +28 -0
  10. package/dist/cache/cache.types.d.ts +49 -0
  11. package/dist/cache/cache.utils.d.ts +6 -0
  12. package/dist/cache/index.d.ts +4 -0
  13. package/dist/client/fetch.client.bindings.d.ts +25 -0
  14. package/dist/client/fetch.client.constants.d.ts +1 -0
  15. package/dist/client/fetch.client.d.ts +2 -0
  16. package/dist/client/fetch.client.types.d.ts +57 -0
  17. package/dist/client/fetch.client.utils.d.ts +5 -0
  18. package/dist/client/index.d.ts +5 -0
  19. package/dist/command/command.d.ts +87 -0
  20. package/dist/command/command.types.d.ts +196 -0
  21. package/dist/command/command.utils.d.ts +22 -0
  22. package/dist/command/index.d.ts +3 -0
  23. package/dist/constants/http.constants.d.ts +7 -0
  24. package/dist/constants/time.constants.d.ts +11 -0
  25. package/dist/dispatcher/dispatcher.constants.d.ts +6 -0
  26. package/dist/dispatcher/dispatcher.d.ts +155 -0
  27. package/dist/dispatcher/dispatcher.events.d.ts +11 -0
  28. package/dist/dispatcher/dispatcher.types.d.ts +31 -0
  29. package/dist/dispatcher/dispatcher.utils.d.ts +10 -0
  30. package/dist/dispatcher/index.d.ts +5 -0
  31. package/dist/effect/fetch.effect.d.ts +14 -0
  32. package/dist/effect/fetch.effect.types.d.ts +32 -0
  33. package/dist/effect/index.d.ts +2 -0
  34. package/dist/index.cjs.js +2 -0
  35. package/dist/index.cjs.js.map +7 -0
  36. package/dist/index.d.ts +10 -0
  37. package/dist/index.esm.js +2 -0
  38. package/dist/index.esm.js.map +7 -0
  39. package/dist/managers/app/app.manager.constants.d.ts +9 -0
  40. package/dist/managers/app/app.manager.d.ts +35 -0
  41. package/dist/managers/app/app.manager.events.d.ts +11 -0
  42. package/dist/managers/app/app.manager.types.d.ts +7 -0
  43. package/dist/managers/app/app.manager.utils.d.ts +4 -0
  44. package/dist/managers/app/index.d.ts +5 -0
  45. package/dist/managers/command/command.manager.d.ts +43 -0
  46. package/dist/managers/command/command.manager.events.d.ts +36 -0
  47. package/dist/managers/command/command.manager.types.d.ts +23 -0
  48. package/dist/managers/command/command.manager.utils.d.ts +16 -0
  49. package/dist/managers/command/index.d.ts +4 -0
  50. package/dist/managers/index.d.ts +3 -0
  51. package/dist/managers/logger/index.d.ts +4 -0
  52. package/dist/managers/logger/logger.manager.constants.d.ts +4 -0
  53. package/dist/managers/logger/logger.manager.d.ts +19 -0
  54. package/dist/managers/logger/logger.manager.types.d.ts +30 -0
  55. package/dist/managers/logger/logger.manager.utils.d.ts +3 -0
  56. package/dist/types/fetch.types.d.ts +15 -0
  57. package/dist/types/helpers.types.d.ts +11 -0
  58. package/dist/types/http.types.d.ts +1 -0
  59. package/dist/types/index.d.ts +3 -0
  60. package/dist/utils/index.d.ts +1 -0
  61. package/dist/utils/uuid.utils.d.ts +1 -0
  62. package/package.json +60 -0
  63. package/src/builder/builder.constants.ts +9 -0
  64. package/src/builder/builder.ts +309 -0
  65. package/src/builder/builder.types.ts +57 -0
  66. package/src/builder/builder.utils.ts +178 -0
  67. package/src/builder/index.ts +4 -0
  68. package/src/cache/cache.events.ts +44 -0
  69. package/src/cache/cache.ts +221 -0
  70. package/src/cache/cache.types.ts +56 -0
  71. package/src/cache/cache.utils.ts +29 -0
  72. package/src/cache/index.ts +4 -0
  73. package/src/client/fetch.client.bindings.ts +290 -0
  74. package/src/client/fetch.client.constants.ts +3 -0
  75. package/src/client/fetch.client.ts +98 -0
  76. package/src/client/fetch.client.types.ts +83 -0
  77. package/src/client/fetch.client.utils.ts +28 -0
  78. package/src/client/index.ts +5 -0
  79. package/src/command/command.ts +539 -0
  80. package/src/command/command.types.ts +268 -0
  81. package/src/command/command.utils.ts +179 -0
  82. package/src/command/index.ts +3 -0
  83. package/src/constants/http.constants.ts +7 -0
  84. package/src/constants/time.constants.ts +11 -0
  85. package/src/dispatcher/dispatcher.constants.ts +6 -0
  86. package/src/dispatcher/dispatcher.events.ts +42 -0
  87. package/src/dispatcher/dispatcher.ts +596 -0
  88. package/src/dispatcher/dispatcher.types.ts +39 -0
  89. package/src/dispatcher/dispatcher.utils.ts +55 -0
  90. package/src/dispatcher/index.ts +5 -0
  91. package/src/effect/fetch.effect.ts +28 -0
  92. package/src/effect/fetch.effect.types.ts +35 -0
  93. package/src/effect/index.ts +2 -0
  94. package/src/index.ts +12 -0
  95. package/src/managers/app/app.manager.constants.ts +24 -0
  96. package/src/managers/app/app.manager.events.ts +34 -0
  97. package/src/managers/app/app.manager.ts +74 -0
  98. package/src/managers/app/app.manager.types.ts +8 -0
  99. package/src/managers/app/app.manager.utils.ts +34 -0
  100. package/src/managers/app/index.ts +5 -0
  101. package/src/managers/command/command.manager.events.ts +212 -0
  102. package/src/managers/command/command.manager.ts +68 -0
  103. package/src/managers/command/command.manager.types.ts +25 -0
  104. package/src/managers/command/command.manager.utils.ts +19 -0
  105. package/src/managers/command/index.ts +4 -0
  106. package/src/managers/index.ts +3 -0
  107. package/src/managers/logger/index.ts +4 -0
  108. package/src/managers/logger/logger.manager.constants.ts +24 -0
  109. package/src/managers/logger/logger.manager.ts +70 -0
  110. package/src/managers/logger/logger.manager.types.ts +35 -0
  111. package/src/managers/logger/logger.manager.utils.ts +27 -0
  112. package/src/types/fetch.types.ts +39 -0
  113. package/src/types/helpers.types.ts +15 -0
  114. package/src/types/http.types.ts +1 -0
  115. package/src/types/index.ts +3 -0
  116. package/src/utils/index.ts +1 -0
  117. package/src/utils/uuid.utils.ts +3 -0
  118. package/tsconfig.json +8 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/effect/fetch.effect.ts", "../src/client/fetch.client.utils.ts", "../src/client/fetch.client.ts", "../src/utils/uuid.utils.ts", "../src/constants/time.constants.ts", "../src/constants/http.constants.ts", "../src/command/command.ts", "../src/dispatcher/dispatcher.constants.ts", "../src/dispatcher/dispatcher.events.ts", "../src/dispatcher/dispatcher.ts", "../src/dispatcher/dispatcher.utils.ts", "../src/command/command.utils.ts", "../src/client/fetch.client.bindings.ts", "../src/client/fetch.client.constants.ts", "../src/cache/cache.ts", "../src/cache/cache.utils.ts", "../src/cache/cache.events.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/command/command.manager.ts", "../src/managers/command/command.manager.utils.ts", "../src/managers/command/command.manager.events.ts", "../src/managers/logger/logger.manager.ts", "../src/managers/logger/logger.manager.utils.ts", "../src/managers/logger/logger.manager.constants.ts", "../src/builder/builder.utils.ts", "../src/builder/builder.ts", "../src/builder/builder.constants.ts"],
4
+ "sourcesContent": ["import { ExtractError } from \"types\";\nimport { FetchEffectConfig } from \"effect\";\nimport { CommandInstance } from \"command\";\nimport { ClientResponseErrorType, ClientResponseType, ClientResponseSuccessType } from \"client\";\n\nexport class FetchEffect<T extends CommandInstance> {\n constructor(public config: FetchEffectConfig<T>) {}\n\n getEffectKey = () => {\n return this.config.effectKey;\n };\n\n onTrigger = (command: T) => {\n this.config.onTrigger?.(command);\n };\n onStart = (command: T) => {\n this.config.onStart?.(command);\n };\n onSuccess = (response: ClientResponseSuccessType<ResponseType>, command: T) => {\n this.config.onSuccess?.(response, command);\n };\n onError = (response: ClientResponseErrorType<ExtractError<T>>, command: T) => {\n this.config.onError?.(response, command);\n };\n onFinished = (response: ClientResponseType<ResponseType, ExtractError<T>>, command: T) => {\n this.config.onFinished?.(response, command);\n };\n}\n", "import { CommandInstance } from \"command\";\nimport { ExtractError } from \"types\";\n\n// Utils\n\nexport const getErrorMessage = (errorCase?: \"timeout\" | \"abort\" | \"deleted\") => {\n if (errorCase === \"timeout\") {\n return new Error(\"Request timeout\");\n }\n if (errorCase === \"abort\") {\n return new Error(\"Request cancelled\");\n }\n return new Error(\"Unexpected error\");\n};\n\n// Responses\n\nexport const parseResponse = (response: string | unknown) => {\n try {\n return JSON.parse(response as string);\n } catch (err) {\n return response;\n }\n};\n\nexport const parseErrorResponse = <T extends CommandInstance>(response: unknown): ExtractError<T> => {\n return response ? parseResponse(response) : getErrorMessage();\n};\n", "import { getClientBindings, defaultTimeout, ClientResponseType, ClientType } from \"client\";\nimport { parseErrorResponse, parseResponse } from \"./fetch.client.utils\";\n\nexport const fetchClient: ClientType = async (command, requestId) => {\n if (!window.XMLHttpRequest) {\n throw new Error(\"There is no XMLHttpRequest, make sure it's provided to use Hyper Fetch built-in client.\");\n }\n\n const {\n fullUrl,\n headers,\n payload,\n config,\n createAbortListener,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onRequestEnd,\n onResponseStart,\n onResponseProgress,\n onSuccess,\n // onAbortError,\n // onTimeoutError,\n onError,\n onResponseEnd,\n } = await getClientBindings(command, requestId);\n\n const { method } = command;\n\n const xhr = new XMLHttpRequest();\n xhr.timeout = defaultTimeout;\n\n const abort = () => xhr.abort();\n\n return new Promise<ClientResponseType<unknown, unknown>>((resolve) => {\n // Inject xhr options\n Object.entries(config).forEach(([name, value]) => {\n xhr[name] = value;\n });\n\n // Open connection\n xhr.open(method, fullUrl, true);\n\n // Set Headers\n Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));\n\n // Listen to abort signal\n const unmountListener = createAbortListener(abort, resolve);\n\n // Request handlers\n xhr.upload.onprogress = onRequestProgress;\n\n // Response handlers\n xhr.onloadstart = (): void => {\n onRequestEnd();\n onResponseStart();\n };\n\n xhr.onprogress = onResponseProgress;\n\n xhr.onloadend = () => {\n onResponseEnd();\n unmountListener();\n };\n\n // Error listeners\n // xhr.onabort = () => onAbortError(resolve);\n // xhr.ontimeout = () => onTimeoutError(resolve);\n // xhr.upload.onabort = () => onAbortError(resolve);\n // xhr.upload.ontimeout = () => onTimeoutError(resolve);\n\n // Data handler\n xhr.onreadystatechange = (e: Event) => {\n const event = e as unknown as ProgressEvent<XMLHttpRequest>;\n const finishedState = 4;\n\n if (event.target && event.target.readyState === finishedState) {\n const { status } = event.target;\n const isSuccess = String(status).startsWith(\"2\") || String(status).startsWith(\"3\");\n\n if (isSuccess) {\n const data = parseResponse(event.target.response);\n onSuccess(data, status, resolve);\n } else {\n // delay to finish after onabort/ontimeout\n const data = parseErrorResponse(event.target.response);\n onError(data, status, resolve);\n }\n }\n };\n\n // Start request\n onBeforeRequest();\n onRequestStart();\n\n xhr.send(payload);\n });\n};\n", "export const getUniqueRequestId = (key: string) => {\n return `${key}_${Date.now().toString(36)}_${Math.random().toString(36).substring(2)}`;\n};\n", "export enum DateInterval {\n second = 1e3,\n minute = 6e4,\n hour = 3.6e6,\n day = 8.64e7,\n week = 6.048e8,\n month30 = 2.592e9,\n month31 = 2.6784e9,\n year = 3.1536e10,\n yearLeap = 3.16224e10,\n}\n", "export enum HttpMethodsEnum {\n get = \"GET\",\n post = \"POST\",\n put = \"PUT\",\n patch = \"PATCH\",\n delete = \"DELETE\",\n}\n", "import {\n FetchType,\n ParamsType,\n getSimpleKey,\n getCommandKey,\n FetchMethodType,\n CommandData,\n CommandDump,\n CommandConfig,\n ExtractRouteParams,\n commandSendRequest,\n CommandCurrentType,\n} from \"command\";\nimport { Builder } from \"builder\";\nimport { getUniqueRequestId } from \"utils\";\nimport { ClientQueryParamsType } from \"client\";\nimport { HttpMethodsType, NegativeTypes } from \"types\";\nimport { DateInterval } from \"constants/time.constants\";\nimport { HttpMethodsEnum } from \"constants/http.constants\";\n\n/**\n * Fetch command it is designed to prepare the necessary setup to execute the request to the server.\n * We can setup basic options for example endpoint, method, headers and advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.\n * :::info Usage\n * We should not use this class directly in the standard development flow. We can initialize it using the `createCommand` method on the **Builder** class.\n * :::\n *\n * @attention\n * The most important thing about the command is that it keeps data in the format that can be dumped. This is necessary for the persistance 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 */\nexport class Command<\n ResponseType,\n RequestDataType,\n QueryParamsType extends ClientQueryParamsType | string,\n GlobalErrorType, // Global Error Type\n LocalErrorType, // Additional Error for specific endpoint\n EndpointType extends string,\n ClientOptions,\n HasData extends true | false = false,\n HasParams extends true | false = false,\n HasQuery extends true | false = false,\n MappedData = undefined,\n> {\n endpoint: EndpointType;\n headers?: HeadersInit;\n auth: boolean;\n method: HttpMethodsType;\n params: ExtractRouteParams<EndpointType> | NegativeTypes;\n data: CommandData<RequestDataType, MappedData>;\n queryParams: QueryParamsType | NegativeTypes;\n options?: ClientOptions | undefined;\n cancelable: boolean;\n retry: number;\n retryTime: number;\n cache: boolean;\n cacheTime: number;\n queued: boolean;\n offline: boolean;\n abortKey: string;\n cacheKey: string;\n queueKey: string;\n effectKey: string;\n used: boolean;\n deduplicate: boolean;\n deduplicateTime: number;\n\n private updatedAbortKey: boolean;\n private updatedCacheKey: boolean;\n private updatedQueueKey: boolean;\n private updatedEffectKey: boolean;\n\n constructor(\n readonly builder: Builder<GlobalErrorType, ClientOptions>,\n readonly commandOptions: CommandConfig<EndpointType, ClientOptions>,\n readonly commandDump?:\n | CommandCurrentType<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType | LocalErrorType,\n EndpointType,\n ClientOptions,\n MappedData\n >\n | undefined,\n readonly dataMapper?: (data: RequestDataType) => MappedData,\n ) {\n const {\n endpoint,\n headers,\n auth = true,\n method = HttpMethodsEnum.get,\n options,\n cancelable = false,\n retry = 0,\n retryTime = 500,\n cache = true,\n cacheTime = DateInterval.minute * 5,\n queued = false,\n offline = true,\n abortKey,\n cacheKey,\n queueKey,\n effectKey,\n deduplicate = false,\n deduplicateTime = 10,\n } = { ...this.builder.commandConfig?.(commandOptions), ...commandOptions };\n\n this.endpoint = commandDump?.endpoint ?? endpoint;\n this.headers = commandDump?.headers ?? headers;\n this.auth = commandDump?.auth ?? auth;\n this.method = method;\n this.params = commandDump?.params;\n this.data = commandDump?.data;\n this.queryParams = commandDump?.queryParams;\n this.options = commandDump?.options ?? options;\n this.cancelable = commandDump?.cancelable ?? cancelable;\n this.retry = commandDump?.retry ?? retry;\n this.retryTime = commandDump?.retryTime ?? retryTime;\n this.cache = commandDump?.cache ?? cache;\n this.cacheTime = commandDump?.cacheTime ?? cacheTime;\n this.queued = commandDump?.queued ?? queued;\n this.offline = commandDump?.offline ?? offline;\n this.abortKey = commandDump?.abortKey ?? abortKey ?? getSimpleKey(this);\n this.cacheKey = commandDump?.cacheKey ?? cacheKey ?? getCommandKey(this);\n this.queueKey = commandDump?.queueKey ?? queueKey ?? getSimpleKey(this);\n this.effectKey = commandDump?.effectKey ?? effectKey ?? getSimpleKey(this);\n this.used = commandDump?.used ?? false;\n this.deduplicate = commandDump?.deduplicate ?? deduplicate;\n this.deduplicateTime = commandDump?.deduplicateTime ?? deduplicateTime;\n\n this.updatedAbortKey = commandDump?.updatedAbortKey ?? false;\n this.updatedCacheKey = commandDump?.updatedCacheKey ?? false;\n this.updatedQueueKey = commandDump?.updatedQueueKey ?? false;\n this.updatedEffectKey = commandDump?.updatedEffectKey ?? false;\n }\n\n public setHeaders = (headers: HeadersInit) => {\n return this.clone({ headers });\n };\n\n public setAuth = (auth: boolean) => {\n return this.clone({ auth });\n };\n\n public setParams = (params: ExtractRouteParams<EndpointType>) => {\n return this.clone<HasData, true, HasQuery>({ params });\n };\n\n public setData = (data: RequestDataType) => {\n const modifiedData = this.dataMapper?.(data) || data;\n return this.clone<true, HasParams, HasQuery, MappedData>({\n data: modifiedData as CommandData<RequestDataType, MappedData>,\n });\n };\n\n public setQueryParams = (queryParams: QueryParamsType) => {\n return this.clone<HasData, HasParams, true>({ queryParams });\n };\n\n public setOptions = (options: ClientOptions) => {\n return this.clone<HasData, HasParams, true>({ options });\n };\n\n public setCancelable = (cancelable: boolean) => {\n return this.clone({ cancelable });\n };\n\n public setRetry = (retry: CommandConfig<EndpointType, ClientOptions>[\"retry\"]) => {\n return this.clone({ retry });\n };\n\n public setRetryTime = (retryTime: CommandConfig<EndpointType, ClientOptions>[\"retryTime\"]) => {\n return this.clone({ retryTime });\n };\n\n public setCache = (cache: CommandConfig<EndpointType, ClientOptions>[\"cache\"]) => {\n return this.clone({ cache });\n };\n\n public setCacheTime = (cacheTime: CommandConfig<EndpointType, ClientOptions>[\"cacheTime\"]) => {\n return this.clone({ cacheTime });\n };\n\n public setQueued = (queued: boolean) => {\n return this.clone({ queued });\n };\n\n public setAbortKey = (abortKey: string) => {\n this.updatedAbortKey = true;\n return this.clone({ abortKey });\n };\n\n public setCacheKey = (cacheKey: string) => {\n this.updatedCacheKey = true;\n return this.clone({ cacheKey });\n };\n\n public setQueueKey = (queueKey: string) => {\n this.updatedQueueKey = true;\n return this.clone({ queueKey });\n };\n\n public setEffectKey = (effectKey: string) => {\n this.updatedEffectKey = true;\n return this.clone({ effectKey });\n };\n\n public setDeduplicate = (deduplicate: boolean) => {\n return this.clone({ deduplicate });\n };\n\n public setDeduplicateTime = (deduplicateTime: number) => {\n return this.clone({ deduplicateTime });\n };\n\n public setUsed = (used: boolean) => {\n return this.clone({ used });\n };\n\n public setOffline = (offline: boolean) => {\n return this.clone({ offline });\n };\n\n public setDataMapper = <DataMapper>(mapper: (data: RequestDataType) => DataMapper) => {\n return this.clone<HasData, HasParams, HasQuery, DataMapper>(undefined, mapper);\n };\n\n private paramsMapper = (\n params: ParamsType | null | undefined,\n queryParams: QueryParamsType | NegativeTypes,\n ): string => {\n let endpoint = this.commandOptions.endpoint as string;\n if (params) {\n Object.entries(params).forEach(([key, value]) => {\n endpoint = endpoint.replace(new RegExp(`:${key}`, \"g\"), String(value));\n });\n }\n if (queryParams) {\n endpoint += this.builder.stringifyQueryParams(queryParams);\n }\n return endpoint;\n };\n\n public dump(): CommandDump<\n Command<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType,\n LocalErrorType,\n EndpointType,\n ClientOptions,\n HasData,\n HasParams,\n HasQuery,\n MappedData\n >,\n ClientOptions,\n QueryParamsType\n > {\n return {\n commandOptions: this.commandOptions,\n endpoint: this.endpoint,\n headers: this.headers,\n auth: this.auth,\n method: this.method,\n params: this.params,\n data: this.data,\n queryParams: this.queryParams,\n options: this.options,\n cancelable: this.cancelable,\n retry: this.retry,\n retryTime: this.retryTime,\n cache: this.cache,\n cacheTime: this.cacheTime,\n queued: this.queued,\n offline: this.offline,\n abortKey: this.abortKey,\n cacheKey: this.cacheKey,\n queueKey: this.queueKey,\n effectKey: this.effectKey,\n used: this.used,\n disableResponseInterceptors: this.commandOptions.disableResponseInterceptors,\n disableRequestInterceptors: this.commandOptions.disableRequestInterceptors,\n updatedAbortKey: this.updatedAbortKey,\n updatedCacheKey: this.updatedCacheKey,\n updatedQueueKey: this.updatedQueueKey,\n updatedEffectKey: this.updatedEffectKey,\n deduplicate: this.deduplicate,\n deduplicateTime: this.deduplicateTime,\n };\n }\n\n public clone<\n D extends true | false = HasData,\n P extends true | false = HasParams,\n Q extends true | false = HasQuery,\n MapperData = MappedData,\n >(\n options?: CommandCurrentType<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType | LocalErrorType,\n EndpointType,\n ClientOptions,\n MapperData\n >,\n mapper?: (data: RequestDataType) => MapperData,\n ): Command<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType,\n LocalErrorType,\n EndpointType,\n ClientOptions,\n D,\n P,\n Q,\n MapperData\n > {\n const dump = this.dump();\n const commandDump: CommandCurrentType<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType | LocalErrorType,\n EndpointType,\n ClientOptions,\n MapperData\n > = {\n ...dump,\n ...options,\n abortKey: this.updatedAbortKey ? options?.abortKey || this.abortKey : undefined,\n cacheKey: this.updatedCacheKey ? options?.cacheKey || this.cacheKey : undefined,\n queueKey: this.updatedQueueKey ? options?.queueKey || this.queueKey : undefined,\n endpoint: this.paramsMapper(\n options?.params || this.params,\n options?.queryParams || this.queryParams,\n ) as EndpointType,\n queryParams: options?.queryParams || this.queryParams,\n // Typescript circular types issue - we have to leave any here\n data: (options?.data || this.data) as any,\n };\n\n const cloned = new Command<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType,\n LocalErrorType,\n EndpointType,\n ClientOptions,\n D,\n P,\n Q,\n MapperData\n >(this.builder, this.commandOptions, commandDump, mapper);\n\n return cloned;\n }\n\n public abort = () => {\n const { commandManager } = this.builder;\n commandManager.abortByKey(this.abortKey);\n\n return this.clone();\n };\n\n /**\n * Method to use the command WITHOUT adding it to cache and queues. This mean it will make simple request without queue side effects.\n * @param options\n * @returns\n */\n public exec: FetchMethodType<\n Command<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType,\n LocalErrorType,\n EndpointType,\n ClientOptions,\n HasData,\n HasParams,\n HasQuery,\n MappedData\n >\n > = async (\n options?: FetchType<\n Command<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType,\n LocalErrorType,\n EndpointType,\n ClientOptions,\n HasData,\n HasParams,\n HasQuery,\n MappedData\n >\n >,\n ) => {\n const { client } = this.builder;\n const command = this.clone(options as any);\n\n const requestId = getUniqueRequestId(this.queueKey);\n\n return client(command, requestId);\n };\n\n /**\n * Method used to perform requests with usage of cache and queues\n * @param options\n * @param requestCallback\n */\n public send: FetchMethodType<\n Command<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType,\n LocalErrorType,\n EndpointType,\n ClientOptions,\n HasData,\n HasParams,\n HasQuery,\n MappedData\n >\n > = async (\n options?: FetchType<\n Command<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType,\n LocalErrorType,\n EndpointType,\n ClientOptions,\n HasData,\n HasParams,\n HasQuery,\n MappedData\n >\n >,\n ) => {\n const { dispatcherType, ...rest } = options || {};\n\n const command = this.clone(rest as any);\n return commandSendRequest<\n Command<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType,\n LocalErrorType,\n EndpointType,\n ClientOptions,\n HasData,\n HasParams,\n HasQuery,\n MappedData\n >\n >(command, options);\n };\n}\n\n// Typescript test cases\n\n// const builder = new Builder({\n// baseUrl: \"http://localhost:3000\",\n// });\n\n// const getUsers = builder.createCommand<{ id: string }[]>()({\n// method: \"GET\",\n// endpoint: \"/users\",\n// });\n\n// const getUser = builder.createCommand<{ id: string }>()({\n// method: \"GET\",\n// endpoint: \"/users/:id\",\n// });\n\n// const postUser = builder.createCommand<{ id: string }, { name: string }>()({\n// method: \"POST\",\n// endpoint: \"/users\",\n// });\n\n// const patchUser = builder.createCommand<{ id: string }, { name: string }>()({\n// method: \"PATCH\",\n// endpoint: \"/users/:id\",\n// });\n\n// // OK\n// getUsers.send({ queryParams: \"\" });\n// getUsers.setQueryParams(\"\").send();\n// // Fail\n// getUsers.send({ data: \"\" });\n// getUsers.send({ params: \"\" });\n// getUsers.setQueryParams(\"\").send({ queryParams: \"\" });\n\n// // OK\n// getUser.send({ params: { id: \"\" }, queryParams: \"\" });\n// getUser.setParams({ id: \"\" }).send({ queryParams: \"\" });\n// // Fail\n// getUser.send({ queryParams: \"\" });\n// getUser.send();\n// getUser.setParams({ id: \"\" }).send({ params: { id: \"\" } });\n\n// // OK\n// postUser.send({ data: { name: \"\" } });\n// postUser.setData({ name: \"\" }).send();\n// // Fail\n// postUser.send({ queryParams: \"\" });\n// postUser.send({ data: null });\n// postUser.send();\n// postUser.setData({ name: \"\" }).send({ data: { name: \"\" } });\n\n// // OK\n// patchUser.send({ params: { id: \"\" }, data: { name: \"\" } });\n// patchUser.setParams({ id: \"\" }).setData({ name: \"\" }).send();\n// // Fail\n// patchUser.send({ queryParams: \"\" });\n// patchUser.send({ data: null });\n// patchUser.send();\n// patchUser\n// .setParams({ id: \"\" })\n// .setData({ name: \"\" })\n// .send({ data: { name: \"\" } });\n// patchUser\n// .setParams({ id: \"\" })\n// .setData({ name: \"\" })\n// .send({ params: { id: \"\" } });\n", "export enum DispatcherRequestType {\n oneByOne = \"one-by-one\",\n allAtOnce = \"all-at-once\",\n previousCanceled = \"previous-canceled\",\n deduplicated = \"deduplicated\",\n}\n", "import EventEmitter from \"events\";\n\nimport {\n DispatcherData,\n getDispatcherChangeEventKey,\n getDispatcherStatusEventKey,\n getDispatcherDrainedEventKey,\n} from \"dispatcher\";\nimport { CommandInstance } from \"command\";\n\nexport const getDispatcherEvents = (emitter: EventEmitter) => ({\n setDrained: <Command extends CommandInstance>(queueKey: string, values: DispatcherData<Command>): void => {\n emitter.emit(getDispatcherDrainedEventKey(queueKey), values);\n },\n setQueueStatus: <Command extends CommandInstance>(queueKey: string, values: DispatcherData<Command>): void => {\n emitter.emit(getDispatcherStatusEventKey(queueKey), values);\n },\n setQueueChanged: <Command extends CommandInstance>(queueKey: string, values: DispatcherData<Command>): void => {\n emitter.emit(getDispatcherChangeEventKey(queueKey), values);\n },\n onDrained: <Command extends CommandInstance>(\n queueKey: string,\n callback: (values: DispatcherData<Command>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherDrainedEventKey(queueKey), callback);\n return () => emitter.removeListener(getDispatcherDrainedEventKey(queueKey), callback);\n },\n onQueueStatus: <Command extends CommandInstance>(\n queueKey: string,\n callback: (values: DispatcherData<Command>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherStatusEventKey(queueKey), callback);\n return () => emitter.removeListener(getDispatcherStatusEventKey(queueKey), callback);\n },\n onQueueChange: <Command extends CommandInstance>(\n queueKey: string,\n callback: (values: DispatcherData<Command>) => void,\n ): VoidFunction => {\n emitter.on(getDispatcherChangeEventKey(queueKey), callback);\n return () => emitter.removeListener(getDispatcherChangeEventKey(queueKey), callback);\n },\n});\n", "import EventEmitter from \"events\";\n\nimport {\n DispatcherData,\n getRequestType,\n isFailedRequest,\n canRetryRequest,\n getDispatcherEvents,\n DispatcherRequestType,\n DispatcherOptionsType,\n DispatcherStorageType,\n DispatcherDumpValueType,\n RunningRequestValueType,\n} from \"dispatcher\";\nimport { BuilderInstance } from \"builder\";\nimport { getUniqueRequestId } from \"utils\";\nimport { CommandResponseDetails, LoggerType } from \"managers\";\nimport { CommandInstance, Command } from \"command\";\nimport { getErrorMessage } from \"client\";\n\n/**\n * Dispatcher class was made to store controlled request Fetches, and firing them all-at-once or one-by-one in command queue.\n * Generally requests should be flushed at the same time, the queue provide mechanism to fire them in the order.\n */\nexport class Dispatcher {\n public emitter = new EventEmitter();\n public events = getDispatcherEvents(this.emitter);\n public storage: DispatcherStorageType = new Map<string, DispatcherData<CommandInstance>>();\n\n private requestCount = new Map<string, number>();\n private runningRequests = new Map<string, RunningRequestValueType[]>();\n\n private logger: LoggerType;\n\n constructor(public builder: BuilderInstance, public options?: DispatcherOptionsType) {\n this.logger = builder.loggerManager.init(\"Dispatcher\");\n\n if (this.options?.storage) {\n this.storage = this.options.storage;\n }\n\n // Going back from offline should re-trigger all requests\n this.builder.appManager.events.onOnline(() => {\n this.flush();\n });\n\n this.options?.onInitialization?.(this);\n }\n\n // ********************\n // ********************\n // Queue\n // ********************\n // ********************\n\n /**\n * Start request handling by queueKey\n */\n start = (queueKey: string) => {\n // Change status to running\n const queue = this.getQueue(queueKey);\n\n // Start the queue when its stopped\n queue.stopped = false;\n this.setQueue(queueKey, queue);\n this.flushQueue(queueKey);\n this.events.setQueueStatus(queueKey, queue);\n };\n\n /**\n * Pause request queue, but not cancel already started requests\n */\n pause = (queueKey: string) => {\n // Change state to stopped\n const queue = this.getQueue(queueKey);\n\n queue.stopped = true;\n this.setQueue(queueKey, queue);\n this.events.setQueueStatus(queueKey, queue);\n };\n\n /**\n * Stop request queue and cancel all started requests - those will be treated like not started\n */\n stop = (queueKey: string) => {\n // Change state to stopped\n const queue = this.getQueue(queueKey);\n\n queue.stopped = true;\n this.setQueue(queueKey, queue);\n\n // Cancel running requests\n this.cancelRunningRequests(queueKey);\n this.events.setQueueStatus(queueKey, queue);\n };\n\n /**\n * Return all\n */\n getQueuesKeys = () => {\n return Array.from(this.storage.keys());\n };\n\n /**\n * Return queue state object\n */\n getQueue = <Command extends CommandInstance = CommandInstance>(queueKey: string) => {\n const initialQueueState: DispatcherData<Command> = { requests: [], stopped: false };\n const storedEntity = this.storage.get<Command>(queueKey);\n\n return storedEntity || initialQueueState;\n };\n\n /**\n * Return request from queue state\n */\n getRequest = <Command extends CommandInstance = CommandInstance>(queueKey: string, requestId: string) => {\n const initialQueueState: DispatcherData<Command> = { requests: [], stopped: false };\n const storedEntity = this.storage.get<Command>(queueKey) || 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 = (queueKey: string) => {\n const queue = this.getQueue(queueKey);\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 addQueueElement = <Command extends CommandInstance = CommandInstance>(\n queueKey: string,\n dispatcherDump: DispatcherDumpValueType<Command>,\n ) => {\n const queue = this.getQueue<Command>(queueKey);\n queue.requests.push(dispatcherDump);\n this.setQueue<Command>(queueKey, queue);\n };\n\n /**\n * Set new queue storage value\n */\n setQueue = <Command extends CommandInstance = CommandInstance>(queueKey: string, queue: DispatcherData<Command>) => {\n this.storage.set<Command>(queueKey, queue);\n\n // Emit Queue Changes\n this.options?.onUpdateStorage?.(queueKey, queue);\n this.events.setQueueChanged(queueKey, queue);\n\n return queue;\n };\n\n /**\n * Clear requests from queue cache\n */\n clearQueue = (queueKey: string) => {\n const queue = this.getQueue(queueKey);\n const newQueue = { requests: [], stopped: queue.stopped };\n this.storage.set(queueKey, newQueue);\n\n // Emit Queue Changes\n this.options?.onDeleteFromStorage?.(queueKey, newQueue);\n this.events.setQueueChanged(queueKey, newQueue);\n\n return newQueue;\n };\n\n /**\n * Method used to flush the queue requests\n */\n flushQueue = async (queueKey: string) => {\n const queue = this.getQueue(queueKey);\n const runningRequests = this.getRunningRequests(queueKey);\n const queueElement = queue.requests.find((request) => !request.stopped);\n\n const isStopped = queue && queue.stopped;\n const isOffline = !this.builder.appManager.isOnline;\n const isConcurrent = !queueElement?.commandDump.queued;\n const isInactive = !runningRequests.length;\n const isEmpty = !queueElement;\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(\"Skipping queue trigger\", { isStopped, isOffline, isEmpty });\n } else if (isConcurrent) {\n queue.requests.forEach((element) => {\n if (!this.hasRunningRequest(queueKey, element.requestId)) {\n this.performRequest(element);\n }\n });\n } else if (isInactive) {\n await this.performRequest(queueElement);\n this.flushQueue(queueKey);\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 storageElement = this.getQueue(key);\n\n if (storageElement) {\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((queueKey) => this.cancelRunningRequests(queueKey));\n\n this.runningRequests.clear();\n this.storage.clear();\n this.options?.onClearStorage?.(this);\n };\n\n // ********************\n // ********************\n // Requests\n // ********************\n // ********************\n\n /**\n * Start particular request\n */\n startRequest = (queueKey: string, requestId: string) => {\n // Change status to running\n const queue = this.getQueue(queueKey);\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(queueKey, queue);\n this.flushQueue(queueKey);\n this.events.setQueueStatus(queueKey, queue);\n }\n };\n\n /**\n * Stop particular request\n */\n stopRequest = (queueKey: string, requestId: string) => {\n // Change state to stopped\n const queue = this.getQueue(queueKey);\n const request = queue.requests.find((element) => element.requestId === requestId);\n\n if (request) {\n request.stopped = true;\n this.setQueue(queueKey, queue);\n\n // Cancel running requests\n this.cancelRunningRequest(queueKey, requestId);\n this.events.setQueueStatus(queueKey, queue);\n }\n };\n\n /**\n * Get currently running requests from all queueKeys\n */\n getAllRunningRequest = () => {\n return Array.from(this.runningRequests.values()).flat();\n };\n\n /**\n * Get currently running requests\n */\n getRunningRequests = (queueKey: string) => {\n return this.runningRequests.get(queueKey) || [];\n };\n\n /**\n * Get running request by id\n */\n getRunningRequest = (queueKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queueKey);\n return runningRequests.find((req) => req.requestId === requestId);\n };\n\n /**\n * Add request to the running requests list\n */\n addRunningRequest = (queueKey: string, requestId: string, command: CommandInstance) => {\n const runningRequests = this.getRunningRequests(queueKey);\n runningRequests.push({ requestId, command });\n this.runningRequests.set(queueKey, runningRequests);\n };\n\n /**\n * Get the value based on the currently running requests\n */\n hasRunningRequests = (queueKey: string) => {\n return !!this.getRunningRequests(queueKey).length;\n };\n\n /**\n * Check if request is currently processing\n */\n hasRunningRequest = (queueKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queueKey);\n return !!runningRequests.find((req) => req.requestId === requestId);\n };\n\n /**\n * Cancel all started requests, but do NOT remove it from main storage\n */\n cancelRunningRequests = (queueKey: string) => {\n this.runningRequests.get(queueKey)?.forEach((request) => {\n this.builder.commandManager.abortByRequestId(request.command.abortKey, request.requestId);\n });\n this.deleteRunningRequests(queueKey);\n };\n /**\n * Cancel started request, but do NOT remove it from main storage\n */\n cancelRunningRequest = (queueKey: string, requestId: string) => {\n const requests = this.getRunningRequests(queueKey).filter((request) => {\n if (request.requestId === requestId) {\n this.builder.commandManager.abortByRequestId(request.command.abortKey, request.requestId);\n return false;\n }\n return true;\n });\n\n this.runningRequests.set(queueKey, requests);\n };\n\n /**\n * Delete all started requests, but do NOT clear it from queue and do NOT cancel them\n */\n deleteRunningRequests = (queueKey: string) => {\n this.runningRequests.set(queueKey, []);\n };\n\n /**\n * Delete request by id, but do NOT clear it from queue and do NOT cancel them\n */\n deleteRunningRequest = (queueKey: string, requestId: string) => {\n const runningRequests = this.getRunningRequests(queueKey);\n this.runningRequests.set(\n queueKey,\n runningRequests.filter((req) => req.requestId !== requestId),\n );\n };\n\n /**\n * Get count of requests from the same queueKey\n */\n getQueueRequestCount = (queueKey: string) => {\n return this.requestCount.get(queueKey) || 0;\n };\n\n /**\n * Add request count to the queueKey\n */\n incrementQueueRequestCount = (queueKey: string) => {\n const count = this.requestCount.get(queueKey) || 0;\n this.requestCount.set(queueKey, count + 1);\n };\n\n /**\n * Create storage element from command\n */\n // eslint-disable-next-line class-methods-use-this\n createStorageElement = <Command extends CommandInstance>(command: Command) => {\n const requestId = getUniqueRequestId(command.queueKey);\n const storageElement: DispatcherDumpValueType<Command> = {\n requestId,\n timestamp: +new Date(),\n commandDump: command.dump(),\n retries: 0,\n stopped: false,\n };\n return storageElement;\n };\n\n // ********************\n // ********************\n // Dispatching\n // ********************\n // ********************\n\n /**\n * Add command to the dispatcher handler\n */\n add = (command: CommandInstance) => {\n const { queueKey } = command;\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 storageElement = this.createStorageElement(command);\n const { requestId } = storageElement;\n\n const queue = this.getQueue(queueKey);\n const [latestRequest] = queue.requests.slice(-1);\n const requestType = getRequestType(command, latestRequest);\n\n this.logger.debug(\"Adding request to queue\", { requestType, command, requestId });\n\n switch (requestType) {\n case DispatcherRequestType.oneByOne: {\n // Requests will go one by one\n this.addQueueElement(queueKey, storageElement);\n this.flushQueue(queueKey);\n return requestId;\n }\n case DispatcherRequestType.previousCanceled: {\n // Cancel all previous on-going requests\n this.cancelRunningRequests(queueKey);\n this.clearQueue(queueKey);\n this.addQueueElement(queueKey, storageElement);\n this.flushQueue(queueKey);\n return requestId;\n }\n case DispatcherRequestType.deduplicated: {\n // Return the running requestId to fullfil the events\n return queue.requests[0].requestId;\n }\n default: {\n this.addQueueElement(queueKey, storageElement);\n this.flushQueue(queueKey);\n return requestId;\n }\n }\n };\n\n /**\n * Delete from the storage and cancel request\n */\n delete = (queueKey: string, requestId: string, abortKey: string) => {\n this.logger.debug(\"Deleting request\", { queueKey, requestId, abortKey });\n const queue = this.getQueue(queueKey);\n const request = queue.requests.find((req) => req.requestId === requestId);\n\n if (!request) return;\n\n const command = new Command(this.builder, request.commandDump.commandOptions, request.commandDump);\n queue.requests = queue.requests.filter((req) => req.requestId !== requestId);\n this.storage.set(queueKey, queue);\n\n // Clean controllers\n if (this.hasRunningRequest(queueKey, requestId)) {\n this.deleteRunningRequest(queueKey, requestId);\n this.builder.commandManager.abortByRequestId(abortKey, requestId);\n }\n\n // Emit Queue Changes\n this.options?.onDeleteFromStorage?.(queueKey, queue);\n this.events.setQueueChanged(queueKey, queue);\n this.builder.commandManager.events.emitRemove(queueKey, requestId, { requestId, command });\n\n if (!queue.requests.length) {\n this.events.setDrained(queueKey, 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 (storageElement: DispatcherDumpValueType) => {\n const command = new Command(this.builder, storageElement.commandDump.commandOptions, storageElement.commandDump);\n const { commandDump, requestId } = storageElement;\n this.logger.info(\"Performing request\", { command, requestId });\n\n const { retry, retryTime, queueKey, cacheKey, abortKey, offline } = commandDump;\n const { client, commandManager, cache, appManager } = this.builder;\n\n const canRetry = canRetryRequest(storageElement.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(queueKey, requestId);\n const isStopped = storageElement.stopped;\n\n if (isOffline || isAlreadyRunning || isStopped) {\n return this.logger.warning(\"Unable to perform request\", { isOffline, isAlreadyRunning, isStopped });\n }\n\n // Additionally keep the running request to possibly abort it later\n this.addRunningRequest(queueKey, requestId, command);\n\n // Propagate the loading to all connected hooks\n commandManager.events.emitLoading(queueKey, requestId, {\n queueKey,\n requestId,\n loading: true,\n isRetry: !!storageElement.retries,\n isOffline,\n });\n\n // Trigger Request\n this.incrementQueueRequestCount(queueKey);\n\n const response = await client(command, requestId);\n\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 // Request is failed when there is the error message or the status is 0 or equal/bigger than 400\n const isFailed = isFailedRequest(response);\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[1]?.message;\n const isCanceled = !this.hasRunningRequest(queueKey, requestId) || isCancelMessage;\n\n // Remove running request, must be called after isCancelled\n this.deleteRunningRequest(queueKey, requestId);\n\n const requestDetails: CommandResponseDetails = {\n isFailed,\n isCanceled,\n isOffline: isOfflineResponseStatus,\n retries: storageElement.retries,\n timestamp: +new Date(),\n };\n\n // Turn off loading\n commandManager.events.emitLoading(queueKey, requestId, {\n queueKey,\n requestId,\n loading: false,\n isRetry: !!storageElement.retries,\n isOffline,\n });\n // Global response emitter to handle command execution\n commandManager.events.emitResponse(cacheKey, requestId, response, requestDetails);\n // Cache event to emit the data inside and store it\n cache.set(command, response, requestDetails);\n this.logger.info(\"Request finished\", { requestId, command, response, requestDetails });\n\n // On cancelled\n if (isCanceled) {\n const queue = this.getQueue(queueKey);\n const request = 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 && !request?.stopped) {\n this.logger.debug(\"Request paused\", { response, requestDetails, command });\n return this.delete(queueKey, requestId, abortKey);\n }\n return this.logger.debug(\"Request canceled\", { response, requestDetails, command });\n }\n // On offline\n if (isFailed && isOfflineResponseStatus) {\n // if we don't want to keep offline request - just delete them\n if (!offline) {\n this.logger.warning(\"Removing non-offline request\", { response, requestDetails, command });\n return this.delete(queueKey, requestId, abortKey);\n }\n // do not remove request from store as we want to re-send it later\n return this.logger.debug(\"Awaiting for network restoration\", { response, requestDetails, command });\n }\n // On success\n if (!isFailed) {\n this.delete(queueKey, requestId, abortKey);\n return this.logger.debug(\"Successful response, removing request from queue.\", {\n response,\n requestDetails,\n command,\n });\n }\n // On retry\n if (isFailed && canRetry) {\n this.logger.debug(\"Waiting for retry\", { response, requestDetails, command });\n // Perform retry once request is failed\n setTimeout(() => {\n this.logger.warning(\"Error response, performing retry\");\n this.performRequest({\n ...storageElement,\n retries: storageElement.retries + 1,\n });\n }, retryTime || 0);\n } else {\n this.logger.error(\"All retries have been used. Removing request from queue.\");\n this.delete(queueKey, requestId, abortKey);\n }\n };\n}\n", "import { CommandInstance } from \"command\";\nimport { ClientResponseType } from \"client\";\nimport { DispatcherRequestType, DispatcherDumpValueType } from \"dispatcher\";\n\n// Events\n\nexport const getDispatcherDrainedEventKey = (key: string): string => {\n return `${key}-drained-event`;\n};\nexport const getDispatcherStatusEventKey = (key: string): string => {\n return `${key}-status-event`;\n};\nexport const getDispatcherChangeEventKey = (key: string): string => {\n return `${key}-change-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\nexport const getRequestType = (command: CommandInstance, latestRequest: DispatcherDumpValueType | undefined) => {\n const { queued, cancelable, deduplicate } = command;\n const canDeduplicate = latestRequest ? +new Date() - latestRequest.timestamp <= command.deduplicateTime : false;\n\n if (queued) {\n return DispatcherRequestType.oneByOne;\n }\n if (cancelable) {\n return DispatcherRequestType.previousCanceled;\n }\n if (canDeduplicate && deduplicate) {\n return DispatcherRequestType.deduplicated;\n }\n return DispatcherRequestType.allAtOnce;\n};\n\nexport const isFailedRequest = (data: ClientResponseType<unknown, unknown>) => {\n const [, , status] = data;\n if (!status || status >= 400) {\n return true;\n }\n return false;\n};\n", "import { FetchProgressType, ClientResponseType, getErrorMessage } from \"client\";\nimport { ClientProgressEvent, CommandInstance, CommandDump, FetchType } from \"command\";\nimport { HttpMethodsEnum } from \"constants/http.constants\";\nimport { canRetryRequest, Dispatcher, isFailedRequest } from \"dispatcher\";\nimport { ExtractError, ExtractResponse } from \"types\";\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 Error();\n return data;\n } catch (_) {\n return \"\";\n }\n};\n\nexport const getProgressValue = ({ loaded, total }: ClientProgressEvent): 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 }: ClientProgressEvent,\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: ClientProgressEvent,\n): FetchProgressType => {\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 = (command: CommandInstance | CommandDump<CommandInstance>): string => {\n return `${command.method}_${command.commandOptions.endpoint}_${command.cancelable}`;\n};\n\n/**\n * Cache instance for individual command that collects individual requests responses from\n * the same endpoint (they may differ base on the custom key, endpoint params etc)\n * @param command\n * @param useInitialValues\n * @returns\n */\nexport const getCommandKey = (\n command: CommandInstance | CommandDump<CommandInstance>,\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(command.method);\n const endpointKey = useInitialValues ? command.commandOptions.endpoint : stringifyKey(command.endpoint);\n\n return `${methodKey}_${endpointKey}`;\n};\n\nexport const getCommandDispatcher = <Command extends CommandInstance>(\n command: Command,\n dispatcherType: \"auto\" | \"fetch\" | \"submit\" = \"auto\",\n): [Dispatcher, boolean] => {\n const { fetchDispatcher, submitDispatcher } = command.builder;\n const isGet = command.method === HttpMethodsEnum.get;\n const isFetchDispatcher = (dispatcherType === \"auto\" && isGet) || dispatcherType === \"fetch\";\n const dispatcher = isFetchDispatcher ? fetchDispatcher : submitDispatcher;\n\n return [dispatcher, isFetchDispatcher];\n};\n\nexport const commandSendRequest = <Command extends CommandInstance>(command: Command, options?: FetchType<Command>) => {\n const { commandManager } = command.builder;\n const [dispatcher] = getCommandDispatcher(command, options?.dispatcherType);\n\n return new Promise<ClientResponseType<ExtractResponse<Command>, ExtractError<Command>>>((resolve) => {\n const requestId = dispatcher.add(command);\n options?.onSettle?.(requestId, command);\n\n const unmountRequestStart = commandManager.events.onRequestStartById<Command>(requestId, (...props) =>\n options?.onRequestStart?.(...props),\n );\n\n const unmountResponseStart = commandManager.events.onResponseStartById<Command>(requestId, (...props) =>\n options?.onResponseStart?.(...props),\n );\n\n const unmountUpload = commandManager.events.onUploadProgressById<Command>(requestId, (...props) =>\n options?.onUploadProgress?.(...props),\n );\n\n const unmountDownload = commandManager.events.onDownloadProgressById<Command>(requestId, (...props) =>\n options?.onDownloadProgress?.(...props),\n );\n\n // When resolved\n const unmountResponse = commandManager.events.onResponseById<ExtractResponse<Command>, ExtractError<Command>>(\n requestId,\n (response, details) => {\n const isFailed = isFailedRequest(response);\n const isOfflineStatus = command.offline && details.isOffline;\n const willRetry = canRetryRequest(details.retries, command.retry);\n\n // When going offline we can't handle the request as it will be postponed to later resolve\n if (isFailed && isOfflineStatus) return;\n\n // When command is in retry mode we need to listen for retries end\n if (isFailed && willRetry) return;\n\n options?.onResponse?.(response, details);\n resolve(response);\n\n // Unmount Listeners\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n umountAll();\n },\n );\n\n // When removed from queue storage we need to clean event listeners and return proper error\n const unmountRemoveQueueElement = commandManager.events.onRemoveById<Command>(requestId, (...props) => {\n options?.onRemove?.(...props);\n resolve([null, getErrorMessage(\"deleted\") as unknown as ExtractError<Command>, 0]);\n\n // Unmount Listeners\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n umountAll();\n });\n\n function umountAll() {\n unmountRequestStart();\n unmountResponseStart();\n unmountUpload();\n unmountDownload();\n unmountResponse();\n unmountRemoveQueueElement();\n }\n });\n};\n", "import { getErrorMessage, ClientResponseSuccessType, ClientResponseErrorType, ProgressRequestDataType } from \"client\";\nimport { CommandInstance, getProgressData, ClientProgressEvent } from \"command\";\nimport { ExtractResponse, ExtractError } from \"types\";\n\nexport const getClientBindings = async (cmd: CommandInstance, requestId: string) => {\n const { baseUrl, commandManager, loggerManager, headerMapper, payloadMapper } = cmd.builder;\n\n const logger = loggerManager.init(\"Client\");\n\n let requestStartTimestamp: null | number = null;\n let responseStartTimestamp: null | number = null;\n let command = cmd;\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(`Starting command middleware callbacks`);\n\n command = await command.builder.__modifyRequest(cmd);\n\n if (command.auth) {\n command = await command.builder.__modifyAuth(cmd);\n }\n\n // Command Setup\n const { builder, abortKey, queueKey, endpoint, data } = command;\n\n commandManager.addAbortController(abortKey, requestId);\n\n const fullUrl = baseUrl + endpoint;\n const effects = builder.effects.filter((effect) => command.effectKey === effect.getEffectKey());\n const headers = headerMapper(command);\n const payload = payloadMapper(data);\n const config = { ...command.commandOptions.options };\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?: ProgressRequestDataType) => {\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: ClientProgressEvent,\n ) => {\n const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);\n\n if (previousRequestTotal !== 100) {\n previousRequestTotal = progress.total;\n commandManager.events.emitUploadProgress(queueKey, requestId, progress, { requestId, command });\n }\n };\n\n const handleResponseProgress = (\n startTimestamp: number,\n progressTimestamp: number,\n progressEvent: ClientProgressEvent,\n ) => {\n const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);\n\n if (previousResponseTotal !== 100) {\n previousResponseTotal = progress.total;\n commandManager.events.emitDownloadProgress(queueKey, requestId, progress, { requestId, command });\n }\n };\n\n // Pre-request\n\n const onBeforeRequest = () => {\n effects.forEach((effect) => effect.onTrigger(command));\n };\n\n // Request\n\n const onRequestStart = (progress?: ProgressRequestDataType) => {\n effects.forEach((action) => action.onStart(command));\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 = +new Date();\n handleRequestProgress(requestStartTimestamp, requestStartTimestamp, initialPayload);\n commandManager.events.emitRequestStart(queueKey, requestId, { requestId, command });\n return requestStartTimestamp;\n };\n\n const onRequestProgress = (progress: ProgressRequestDataType) => {\n if (!requestStartTimestamp) {\n requestStartTimestamp = +new Date();\n }\n requestTotal = getTotal(requestTotal, progress);\n\n const progressTimestamp = +new Date();\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 = +new Date();\n }\n\n const progressTimestamp = +new Date();\n handleRequestProgress(requestStartTimestamp, progressTimestamp, {\n total: requestTotal,\n loaded: requestTotal,\n });\n return progressTimestamp;\n };\n\n // Response\n\n const onResponseStart = (progress?: ProgressRequestDataType) => {\n responseStartTimestamp = +new Date();\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 commandManager.events.emitResponseStart(queueKey, requestId, { requestId, command });\n return responseStartTimestamp;\n };\n\n const onResponseProgress = (progress: ProgressRequestDataType) => {\n if (!responseStartTimestamp) {\n responseStartTimestamp = +new Date();\n }\n\n const progressTimestamp = +new Date();\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 = +new Date();\n }\n\n const progressTimestamp = +new Date();\n commandManager.removeAbortController(abortKey, requestId);\n handleResponseProgress(responseStartTimestamp, progressTimestamp, {\n total: responseTotal,\n loaded: responseTotal,\n });\n return progressTimestamp;\n };\n\n // Success\n\n const onSuccess = async <T extends CommandInstance>(\n responseData: unknown,\n status: number,\n resolve: (value: ClientResponseErrorType<ExtractError<T>>) => void,\n ): Promise<ClientResponseSuccessType<ExtractResponse<T>>> => {\n let response = [responseData, null, status] as ClientResponseSuccessType<ExtractResponse<T>>;\n response = await command.builder.__modifyResponse(response, command);\n response = await command.builder.__modifySuccessResponse(response, command);\n\n effects.forEach((effect) => effect.onSuccess(response, command));\n effects.forEach((effect) => effect.onFinished(response, command));\n\n resolve(response);\n\n return response;\n };\n\n // Errors\n\n const onError = async <T extends CommandInstance>(\n error: Error | ExtractError<T>,\n status: number,\n resolve: (value: ClientResponseErrorType<ExtractError<T>>) => void,\n ): Promise<ClientResponseErrorType<ExtractError<T>>> => {\n let responseData = [null, error, status] as ClientResponseErrorType<ExtractError<T>>;\n\n responseData = await command.builder.__modifyResponse(responseData, command);\n responseData = await command.builder.__modifyErrorResponse(responseData, command);\n\n effects.forEach((effect) => effect.onError(responseData, command));\n effects.forEach((effect) => effect.onFinished(responseData, command));\n\n resolve(responseData);\n\n return responseData;\n };\n\n const onAbortError = <T extends CommandInstance>(\n resolve: (value: ClientResponseErrorType<ExtractError<T>>) => void,\n ) => {\n const error = getErrorMessage(\"abort\");\n return onError(error, 0, resolve);\n };\n\n const onTimeoutError = <T extends CommandInstance>(\n resolve: (value: ClientResponseErrorType<ExtractError<T>>) => void,\n ) => {\n const error = getErrorMessage(\"timeout\");\n return onError(error, 0, resolve);\n };\n\n const onUnexpectedError = <T extends CommandInstance>(\n resolve: (value: ClientResponseErrorType<ExtractError<T>>) => void,\n ) => {\n const error = getErrorMessage();\n return onError(error, 0, resolve);\n };\n\n // Abort\n\n const getAbortController = () => {\n return commandManager.getAbortController(abortKey, requestId);\n };\n\n const createAbortListener = <T extends CommandInstance>(\n callback: () => void,\n resolve: (value: ClientResponseErrorType<ExtractError<T>>) => void,\n ) => {\n const controller = getAbortController();\n if (!controller) {\n throw new Error(\"Controller is not found\");\n }\n\n const fn = () => {\n callback();\n onAbortError(resolve);\n commandManager.events.emitAbort(abortKey, requestId, command);\n };\n\n controller.signal.addEventListener(\"abort\", fn);\n\n return () => controller.signal.removeEventListener(\"abort\", fn);\n };\n\n return {\n fullUrl,\n headers,\n payload,\n config,\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", "import { DateInterval } from \"constants/time.constants\";\n\nexport const defaultTimeout = DateInterval.second * 5;\n", "import EventEmitter from \"events\";\n\nimport { ClientResponseType } from \"client\";\nimport { BuilderInstance } from \"builder\";\nimport { CommandResponseDetails, LoggerType } from \"managers\";\nimport {\n CacheOptionsType,\n CacheAsyncStorageType,\n CacheStorageType,\n getCacheData,\n getCacheEvents,\n CacheValueType,\n} from \"cache\";\nimport { CommandDump, CommandInstance } from \"command\";\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 Command class\n *\n */\nexport class Cache {\n public emitter = new EventEmitter();\n public events: ReturnType<typeof getCacheEvents>;\n\n public storage: CacheStorageType;\n public lazyStorage?: CacheAsyncStorageType;\n public clearKey: string;\n public garbageCollectors = new Map<string, ReturnType<typeof setTimeout>>();\n private logger: LoggerType;\n\n constructor(public builder: BuilderInstance, public options?: CacheOptionsType) {\n this.storage = this.options?.storage || new Map<string, CacheValueType>();\n this.events = getCacheEvents(this.emitter);\n this.options?.onInitialization?.(this);\n\n this.clearKey = this.options?.clearKey || \"\";\n this.lazyStorage = this.options?.lazyStorage;\n this.logger = this.builder.loggerManager.init(\"Cache\");\n\n this.getLazyKeys().then((keys) => {\n keys.forEach(this.scheduleGarbageCollector);\n });\n\n // Going back from offline should re-trigger garbage collection\n this.builder.appManager.events.onOnline(() => {\n this.getLazyKeys().then((keys) => {\n keys.forEach(this.scheduleGarbageCollector);\n });\n });\n }\n\n /**\n * Set the cache data to the storage\n * @param command\n * @param response\n * @param details\n * @returns\n */\n set = <Response, Error>(\n command: CommandInstance | CommandDump<CommandInstance>,\n response: ClientResponseType<Response, Error>,\n details: CommandResponseDetails,\n ): void => {\n this.logger.debug(\"Processing cache response\", { command, response, details });\n const { cacheKey, cache, cacheTime } = command;\n const cachedData = this.storage.get<Response, Error>(cacheKey);\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 data = getCacheData(cachedData?.data, response);\n\n const newCacheData: CacheValueType = { data, details, cacheTime, clearKey: this.clearKey };\n\n this.events.emitCacheData<Response, Error>(cacheKey, newCacheData);\n this.logger.debug(\"Emitting cache response\", { command, response, details });\n\n // If request should not use cache - just emit response data\n if (!cache) {\n return this.logger.debug(\"Prevented saving response to cache\", { command, response, details });\n }\n\n // Only success data is valid for the cache store\n if (!details.isFailed) {\n this.logger.debug(\"Saving response to cache storage\", { command, response, details });\n this.storage.set<Response, Error>(cacheKey, newCacheData);\n this.lazyStorage?.set<Response, Error>(cacheKey, newCacheData);\n this.options?.onChange?.(cacheKey, newCacheData);\n this.scheduleGarbageCollector(cacheKey);\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> | undefined => {\n this.getLazyResource<Response, Error>(cacheKey);\n const cachedData = this.storage.get<Response, Error>(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 Array.from(values);\n };\n\n /**\n * Delete record from storages and trigger revalidation\n * @param cacheKey\n */\n delete = (cacheKey: string): void => {\n this.logger.debug(\"Deleting cache element\", { cacheKey });\n this.storage.delete(cacheKey);\n this.options?.onDelete?.(cacheKey);\n this.lazyStorage?.delete(cacheKey);\n };\n\n /**\n * Revalidate cache by cacheKey or partial matching with RegExp\n * @param cacheKey\n */\n revalidate = async (cacheKey: string | RegExp) => {\n this.logger.debug(\"Revalidating cache element\", { cacheKey });\n const keys = await this.getLazyKeys();\n\n if (typeof cacheKey === \"string\") {\n this.events.emitRevalidation(cacheKey);\n this.delete(cacheKey);\n } else {\n // eslint-disable-next-line no-restricted-syntax\n for (const entityKey of keys) {\n if (cacheKey.test(entityKey)) {\n this.events.emitRevalidation(entityKey);\n this.delete(entityKey);\n }\n }\n }\n };\n\n /**\n * Used to receive data from lazy storage\n * @param cacheKey\n */\n getLazyResource = async <Response, Error>(cacheKey: string): Promise<CacheValueType<Response, Error> | undefined> => {\n const data = await this.lazyStorage?.get<Response, Error>(cacheKey);\n const syncData = this.storage.get<Response, Error>(cacheKey);\n\n // No data in lazy storage\n if (!this.lazyStorage || !data) return syncData;\n\n const now = +new Date();\n const isNewestData = syncData ? syncData.details.timestamp < data.details.timestamp : true;\n const isStaleData = data.cacheTime <= now - data.details.timestamp;\n const isValidData = data.clearKey === this.clearKey;\n\n if (!isValidData) {\n this.lazyStorage.delete(cacheKey);\n }\n if (isNewestData && !isStaleData && isValidData) {\n this.storage.set<Response, Error>(cacheKey, data);\n this.events.emitCacheData<Response, Error>(cacheKey, data);\n return data;\n }\n return syncData;\n };\n\n /**\n * Used to receive keys from sync storage and lazy storage\n * @param cacheKey\n */\n getLazyKeys = async () => {\n const keys = await this.lazyStorage?.keys();\n const asyncKeys = Array.from(keys || []);\n const syncKeys = Array.from(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 = async (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 = await this.getLazyResource(cacheKey);\n\n if (cacheData) {\n const timeLeft = cacheData.cacheTime + cacheData.details.timestamp - +new Date();\n if (timeLeft >= 0) {\n clearTimeout(this.garbageCollectors.get(cacheKey));\n this.garbageCollectors.set(\n cacheKey,\n setTimeout(() => {\n if (this.builder.appManager.isOnline) {\n this.logger.info(\"Garbage collecting cache element\", { cacheKey });\n this.delete(cacheKey);\n }\n }, timeLeft),\n );\n } else if (this.builder.appManager.isOnline) {\n this.delete(cacheKey);\n }\n }\n };\n\n /**\n * Clear cache storages\n */\n clear = async (): Promise<void> => {\n this.storage.clear();\n };\n}\n", "import { CommandInstance } from \"command\";\nimport { isFailedRequest } from \"dispatcher\";\nimport { ExtractClientReturnType } from \"types\";\n\nexport const getCacheData = <T extends CommandInstance>(\n previousResponse: ExtractClientReturnType<T> | undefined,\n response: ExtractClientReturnType<T>,\n): ExtractClientReturnType<T> => {\n const isFailed = isFailedRequest(response);\n\n const previousData = isFailed && previousResponse ? previousResponse[0] : null;\n const data = response[0] || previousData;\n const error = response[1];\n const status = response[2];\n\n return [data, error, status];\n};\n\nexport const getRevalidateEventKey = (key: string): string => {\n return `${key}_revalidate`;\n};\n\nexport const getCacheKey = (key: string): string => {\n return `${key}_cache`;\n};\n\nexport const getCacheIdKey = (key: string): string => {\n return `${key}_cache_by_id`;\n};\n", "import EventEmitter from \"events\";\n\nimport { CacheValueType, getRevalidateEventKey } from \"cache\";\nimport { getCacheKey } from \"./cache.utils\";\n\nexport const getCacheEvents = (emitter: EventEmitter) => ({\n /**\n * Set cache data\n * @param cacheKey\n * @param data\n */\n emitCacheData: <Response, Error>(cacheKey: string, data: CacheValueType<Response, Error>): void => {\n emitter.emit(getCacheKey(cacheKey), data);\n },\n /**\n * Revalidate cache values event\n */\n emitRevalidation: (cacheKey: string): void => {\n emitter.emit(getRevalidateEventKey(cacheKey));\n },\n /**\n * Cache data listener\n * @param cacheKey\n * @param callback\n * @returns\n */\n onData: <Response, Error>(\n cacheKey: string,\n callback: (data: CacheValueType<Response, Error>) => void,\n ): VoidFunction => {\n emitter.on(getCacheKey(cacheKey), callback);\n return () => emitter.removeListener(getCacheKey(cacheKey), callback);\n },\n /**\n * Cache invalidation listener\n * @param cacheKey\n * @param callback\n * @returns\n */\n onRevalidate: (cacheKey: string, callback: () => void): VoidFunction => {\n emitter.on(getRevalidateEventKey(cacheKey), callback);\n return () => emitter.removeListener(getRevalidateEventKey(cacheKey), callback);\n },\n});\n", "import EventEmitter from \"events\";\n\nimport { BuilderInstance } from \"builder\";\nimport { appManagerInitialOptions, AppManagerOptionsType, getAppManagerEvents } from \"managers\";\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 isOnline: boolean;\n isFocused: boolean;\n\n constructor(public builder: BuilderInstance, public options?: AppManagerOptionsType) {\n const {\n focusEvent = appManagerInitialOptions.focusEvent,\n onlineEvent = appManagerInitialOptions.onlineEvent,\n initiallyFocused = appManagerInitialOptions.initiallyFocused,\n initiallyOnline = appManagerInitialOptions.initiallyOnline,\n } = this.options || appManagerInitialOptions;\n\n this.setInitialFocus(initiallyFocused);\n this.setInitialOnline(initiallyOnline);\n\n focusEvent(this.setFocused, builder);\n onlineEvent(this.setOnline, builder);\n }\n\n private setInitialFocus = async (initValue: Exclude<AppManagerOptionsType[\"initiallyFocused\"], undefined>) => {\n if (typeof initValue === \"function\") {\n this.isFocused = false;\n this.isFocused = await initValue();\n } else {\n this.isFocused = initValue;\n }\n };\n\n private setInitialOnline = async (initValue: Exclude<AppManagerOptionsType[\"initiallyOnline\"], undefined>) => {\n if (typeof initValue === \"function\") {\n this.isOnline = false;\n this.isOnline = await initValue();\n } else {\n this.isOnline = initValue;\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 (err) {\n return false;\n }\n};\nexport const hasDocument = () => {\n try {\n return Boolean(hasWindow() && window.document && window.document.addEventListener);\n } catch (err) {\n return false;\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) => {\n if (hasWindow()) {\n window.addEventListener(key, listener, options);\n }\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) => {\n if (hasDocument()) {\n window.document.addEventListener(key, listener, options);\n }\n};\n", "import EventEmitter from \"events\";\n\nimport { AppEvents } from \"managers\";\n\nexport const getAppManagerEvents = (emitter: EventEmitter) => ({\n emitFocus: (): void => {\n emitter.emit(AppEvents.focus);\n },\n emitBlur: (): void => {\n emitter.emit(AppEvents.blur);\n },\n emitOnline: (): void => {\n emitter.emit(AppEvents.online);\n },\n emitOffline: (): void => {\n emitter.emit(AppEvents.offline);\n },\n onFocus: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.focus, callback);\n return () => emitter.removeListener(AppEvents.focus, callback);\n },\n onBlur: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.blur, callback);\n return () => emitter.removeListener(AppEvents.blur, callback);\n },\n onOnline: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.online, callback);\n return () => emitter.removeListener(AppEvents.online, callback);\n },\n onOffline: (callback: () => void): VoidFunction => {\n emitter.on(AppEvents.offline, callback);\n return () => emitter.removeListener(AppEvents.offline, callback);\n },\n});\n", "import { RequiredKeys } from \"types\";\nimport { AppManagerOptionsType } from \"managers\";\nimport { onWindowEvent, onDocumentEvent } 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: true,\n focusEvent: (setFocused) => {\n onDocumentEvent(\"visibilitychange\", () => setFocused(true));\n onWindowEvent(\"focus\", () => setFocused(true));\n onWindowEvent(\"blur\", () => setFocused(false));\n },\n onlineEvent: (setOnline) => {\n onWindowEvent(\"online\", () => setOnline(true));\n onWindowEvent(\"offline\", () => setOnline(false));\n },\n};\n", "import EventEmitter from \"events\";\n\nimport { getCommandManagerEvents } from \"managers\";\n\n/**\n * **Command Manager** is used to emit `command 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 builder instance.\n */\nexport class CommandManager {\n emitter = new EventEmitter();\n events = getCommandManagerEvents(this.emitter);\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 = Array.from(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 = Array.from(this.abortControllers.entries());\n entries.forEach(([abortKey, value]) => {\n const controllers = Array.from(value.entries());\n controllers.forEach(([requestId]) => {\n this.useAbortController(abortKey, requestId);\n });\n });\n };\n}\n", "// Events\n\nexport const getLoadingEventKey = (key: string): string => `${key}-loading-event`;\nexport const getLoadingIdEventKey = (key: string): string => `${key}-loading-event-by-id`;\nexport const getRemoveEventKey = (key: string): string => `${key}-remove-event`;\nexport const getRemoveIdEventKey = (key: string): string => `${key}-remove-event-by-id`;\n\nexport const getAbortEventKey = (key: string) => `${key}-request-abort`;\nexport const getAbortByIdEventKey = (key: string) => `${key}-request-abort-by-id`;\nexport const getResponseEventKey = (key: string) => `${key}-response`;\nexport const getResponseIdEventKey = (key: string) => `${key}-response-by-id`;\nexport const getRequestStartEventKey = (key: string) => `${key}-request-start`;\nexport const getRequestStartIdEventKey = (key: string) => `${key}-request-start-by-id`;\nexport const getResponseStartEventKey = (key: string) => `${key}-response-start`;\nexport const getResponseStartIdEventKey = (key: string) => `${key}-response-start-by-id`;\nexport const getUploadProgressEventKey = (key: string) => `${key}-request-progress`;\nexport const getUploadProgressIdEventKey = (key: string) => `${key}-request-progress-by-id`;\nexport const getDownloadProgressEventKey = (key: string) => `${key}-response-progress`;\nexport const getDownloadProgressIdEventKey = (key: string) => `${key}-response-progress-by-id`;\n", "import EventEmitter from \"events\";\n\nimport {\n getRequestStartEventKey,\n getResponseStartEventKey,\n getDownloadProgressEventKey,\n getUploadProgressEventKey,\n getResponseIdEventKey,\n getAbortEventKey,\n getAbortByIdEventKey,\n getResponseEventKey,\n getUploadProgressIdEventKey,\n getDownloadProgressIdEventKey,\n getResponseStartIdEventKey,\n getRequestStartIdEventKey,\n getLoadingEventKey,\n getLoadingIdEventKey,\n CommandEventDetails,\n CommandResponseDetails,\n CommandLoadingEventType,\n getRemoveEventKey,\n getRemoveIdEventKey,\n} from \"managers\";\nimport { FetchProgressType, ClientResponseType } from \"client\";\nimport { CommandInstance } from \"command\";\n\nexport const getCommandManagerEvents = (emitter: EventEmitter) => ({\n /**\n * Emiter\n */\n\n // Loading\n emitLoading: (queueKey: string, requestId: string, values: CommandLoadingEventType): void => {\n emitter.emit(getLoadingIdEventKey(requestId), values);\n emitter.emit(getLoadingEventKey(queueKey), values);\n },\n\n // Start\n emitRequestStart: (queueKey: string, requestId: string, details: CommandEventDetails<CommandInstance>): void => {\n emitter.emit(getRequestStartIdEventKey(requestId), details);\n emitter.emit(getRequestStartEventKey(queueKey), details);\n },\n emitResponseStart: (queueKey: string, requestId: string, details: CommandEventDetails<CommandInstance>): void => {\n emitter.emit(getResponseStartIdEventKey(requestId), details);\n emitter.emit(getResponseStartEventKey(queueKey), details);\n },\n\n // Progress\n emitUploadProgress: (\n queueKey: string,\n requestId: string,\n values: FetchProgressType,\n details: CommandEventDetails<CommandInstance>,\n ): void => {\n emitter.emit(getUploadProgressIdEventKey(requestId), values, details);\n emitter.emit(getUploadProgressEventKey(queueKey), values, details);\n },\n emitDownloadProgress: (\n queueKey: string,\n requestId: string,\n values: FetchProgressType,\n details: CommandEventDetails<CommandInstance>,\n ): void => {\n emitter.emit(getDownloadProgressIdEventKey(requestId), values, details);\n emitter.emit(getDownloadProgressEventKey(queueKey), values, details);\n },\n\n // Response\n emitResponse: (\n cacheKey: string,\n requestId: string,\n response: ClientResponseType<unknown, unknown>,\n details: CommandResponseDetails,\n ): void => {\n emitter.emit(getResponseIdEventKey(requestId), response, details);\n emitter.emit(getResponseEventKey(cacheKey), response, details);\n },\n\n // Abort\n emitAbort: (abortKey: string, requestId: string, command: CommandInstance): void => {\n emitter.emit(getAbortByIdEventKey(requestId), command);\n emitter.emit(getAbortEventKey(abortKey), command);\n },\n\n // Remove\n emitRemove: <T extends CommandInstance>(\n queueKey: string,\n requestId: string,\n details: CommandEventDetails<T>,\n ): void => {\n emitter.emit(getRemoveEventKey(queueKey), details);\n emitter.emit(getRemoveIdEventKey(requestId), details);\n },\n\n /**\n * Listeners\n */\n\n // Loading\n onLoading: (queueKey: string, callback: (values: CommandLoadingEventType) => void): VoidFunction => {\n emitter.on(getLoadingEventKey(queueKey), callback);\n return () => emitter.removeListener(getLoadingEventKey(queueKey), callback);\n },\n onLoadingById: (requestId: string, callback: (values: CommandLoadingEventType) => void): VoidFunction => {\n emitter.on(getLoadingIdEventKey(requestId), callback);\n return () => emitter.removeListener(getLoadingIdEventKey(requestId), callback);\n },\n\n // Request Start\n onRequestStart: <T extends CommandInstance>(\n queueKey: string,\n callback: (details: CommandEventDetails<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestStartEventKey(queueKey), callback);\n return () => emitter.removeListener(getRequestStartEventKey(queueKey), callback);\n },\n onRequestStartById: <T extends CommandInstance>(\n requestId: string,\n callback: (details: CommandEventDetails<T>) => void,\n ): VoidFunction => {\n emitter.on(getRequestStartIdEventKey(requestId), callback);\n return () => emitter.removeListener(getRequestStartIdEventKey(requestId), callback);\n },\n // Response Start\n onResponseStart: <T extends CommandInstance>(\n queueKey: string,\n callback: (details: CommandEventDetails<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseStartEventKey(queueKey), callback);\n return () => emitter.removeListener(getResponseStartEventKey(queueKey), callback);\n },\n onResponseStartById: <T extends CommandInstance>(\n requestId: string,\n callback: (details: CommandEventDetails<T>) => void,\n ): VoidFunction => {\n emitter.on(getResponseStartIdEventKey(requestId), callback);\n return () => emitter.removeListener(getResponseStartIdEventKey(requestId), callback);\n },\n\n // Progress\n onUploadProgress: <T extends CommandInstance = CommandInstance>(\n queueKey: string,\n callback: (values: FetchProgressType, details: CommandEventDetails<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressEventKey(queueKey), callback);\n return () => emitter.removeListener(getUploadProgressEventKey(queueKey), callback);\n },\n onUploadProgressById: <T extends CommandInstance = CommandInstance>(\n requestId: string,\n callback: (values: FetchProgressType, details: CommandEventDetails<T>) => void,\n ): VoidFunction => {\n emitter.on(getUploadProgressIdEventKey(requestId), callback);\n return () => emitter.removeListener(getUploadProgressIdEventKey(requestId), callback);\n },\n onDownloadProgress: <T extends CommandInstance = CommandInstance>(\n queueKey: string,\n callback: (values: FetchProgressType, details: CommandEventDetails<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressEventKey(queueKey), callback);\n return () => emitter.removeListener(getDownloadProgressEventKey(queueKey), callback);\n },\n onDownloadProgressById: <T extends CommandInstance = CommandInstance>(\n requestId: string,\n callback: (values: FetchProgressType, details: CommandEventDetails<T>) => void,\n ): VoidFunction => {\n emitter.on(getDownloadProgressIdEventKey(requestId), callback);\n return () => emitter.removeListener(getDownloadProgressIdEventKey(requestId), callback);\n },\n\n // Response\n onResponse: <ResponseType, ErrorType>(\n cacheKey: string,\n callback: (response: ClientResponseType<ResponseType, ErrorType>, details: CommandResponseDetails) => void,\n ): VoidFunction => {\n emitter.on(getResponseEventKey(cacheKey), callback);\n return () => emitter.removeListener(getResponseEventKey(cacheKey), callback);\n },\n // Response by requestId\n onResponseById: <ResponseType, ErrorType>(\n requestId: string,\n callback: (response: ClientResponseType<ResponseType, ErrorType>, details: CommandResponseDetails) => void,\n ): VoidFunction => {\n emitter.on(getResponseIdEventKey(requestId), callback);\n return () => emitter.removeListener(getResponseIdEventKey(requestId), callback);\n },\n\n // Abort\n onAbort: (abortKey: string, callback: (command: CommandInstance) => void): VoidFunction => {\n emitter.on(getAbortEventKey(abortKey), callback);\n return () => emitter.removeListener(getAbortEventKey(abortKey), callback);\n },\n onAbortById: (requestId: string, callback: (command: CommandInstance) => void): VoidFunction => {\n emitter.on(getAbortByIdEventKey(requestId), callback);\n return () => emitter.removeListener(getAbortByIdEventKey(requestId), callback);\n },\n\n // Remove\n onRemove: <T extends CommandInstance = CommandInstance>(\n queueKey: string,\n callback: (details: CommandEventDetails<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveEventKey(queueKey), callback);\n return () => emitter.removeListener(getRemoveEventKey(queueKey), callback);\n },\n onRemoveById: <T extends CommandInstance = CommandInstance>(\n requestId: string,\n callback: (details: CommandEventDetails<T>) => void,\n ): VoidFunction => {\n emitter.on(getRemoveIdEventKey(requestId), callback);\n return () => emitter.removeListener(getRemoveIdEventKey(requestId), callback);\n },\n});\n", "import EventEmitter from \"events\";\n\nimport { BuilderInstance } from \"builder\";\nimport { logger, LoggerType, SeverityType, LoggerMessageType, LoggerOptionsType, LoggerFunctionType } from \"managers\";\n\n/**\n * This class is used across the Hyper Fetch library to provide unified logging system with necessary setup per each builder.\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 Builder, Command etc. Which can give you better feedback on the logging itself.\n */\nexport class LoggerManager {\n logger: LoggerFunctionType;\n severity: SeverityType;\n\n public emitter = new EventEmitter();\n\n constructor(private builder: BuilderInstance, private options?: LoggerOptionsType) {\n this.logger = this.options?.logger || logger;\n this.severity = this.options?.severity || 2;\n }\n\n setSeverity = (severity: SeverityType) => {\n this.severity = severity;\n };\n\n init = (module: string): LoggerType => {\n return {\n error: (message: LoggerMessageType, ...additionalData: LoggerMessageType[]) => {\n this.logger({\n level: \"error\",\n module,\n message,\n additionalData,\n severity: this.severity,\n enabled: this.builder.debug,\n });\n },\n warning: (message: LoggerMessageType, ...additionalData: LoggerMessageType[]) => {\n this.logger({\n level: \"warning\",\n module,\n message,\n additionalData,\n severity: this.severity,\n enabled: this.builder.debug,\n });\n },\n info: (message: LoggerMessageType, ...additionalData: LoggerMessageType[]) => {\n this.logger({\n level: \"info\",\n module,\n message,\n additionalData,\n severity: this.severity,\n enabled: this.builder.debug,\n });\n },\n debug: (message: LoggerMessageType, ...additionalData: LoggerMessageType[]) => {\n this.logger({\n level: \"debug\",\n module,\n message,\n additionalData,\n severity: this.severity,\n enabled: this.builder.debug,\n });\n },\n };\n };\n}\n", "/* eslint-disable no-console */\nimport { loggerStyles, loggerIconLevels, LoggerFunctionType, severity } from \"managers\";\n\nexport const getTime = () => {\n const d = new Date();\n return `${d.toLocaleTimeString()}(:${d.getMilliseconds()})`;\n};\n\n// Logger\nexport const logger: LoggerFunctionType = (log) => {\n if (log.enabled && log.severity >= severity[log.level]) {\n const styles = loggerStyles[log.level];\n const emoji = loggerIconLevels[log.level];\n const module = `%c[${log.module}]:[${getTime()}]:`;\n const message = `${emoji}${module} ${log.message}`;\n\n if (log.additionalData?.length) {\n console.groupCollapsed(message, styles);\n log.additionalData.forEach((data) => {\n console.log(data);\n });\n console.groupEnd();\n } else {\n console.log(message, styles);\n }\n }\n};\n", "import { LoggerLevelType } from \"./logger.manager.types\";\n\nconst defaultStyles = \"background:rgba(0,0,0,0.2);padding:2px 5px;border-radius:5px;font-weight:bold;\";\n\nexport const loggerStyles: Record<LoggerLevelType, string> = {\n error: `${defaultStyles}color:#db2525`,\n warning: `${defaultStyles}color:#e1941e`,\n info: `${defaultStyles}color:#1e74e1`,\n debug: `${defaultStyles}color:#adadad`,\n};\n\nexport const loggerIconLevels: Record<LoggerLevelType, string> = {\n error: `\uD83D\uDEA8`,\n warning: `\uD83D\uDEA7`,\n info: `\u2139\uFE0F`,\n debug: `\uD83D\uDEE9\uFE0F`,\n};\n\nexport const severity: Record<LoggerLevelType, number> = {\n error: 0,\n warning: 1,\n info: 2,\n debug: 3,\n};\n", "import {\n ClientQueryParam,\n ClientQueryParamsType,\n ClientQueryParamValues,\n ClientResponseType,\n QueryStringifyOptions,\n} from \"client\";\nimport { CommandInstance } from \"command\";\nimport { stringifyDefaultOptions } from \"builder\";\nimport { NegativeTypes } from \"types\";\nimport { RequestInterceptorCallback, ResponseInterceptorCallback } from \"./builder.types\";\n\n// Utils\n\nexport const stringifyValue = (response: string | unknown): string => {\n try {\n return JSON.stringify(response as string);\n } catch (err) {\n return \"\";\n }\n};\n\nexport const interceptRequest = async (interceptors: RequestInterceptorCallback[], command: CommandInstance) => {\n let newCommand = command;\n if (!command.commandOptions.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 newCommand = (await interceptor(command)) as CommandInstance;\n if (!newCommand) throw new Error(\"Request modifier must return command\");\n }\n }\n return newCommand;\n};\n\nexport const interceptResponse = async <GlobalErrorType>(\n interceptors: ResponseInterceptorCallback[],\n response: ClientResponseType<any, GlobalErrorType>,\n command: CommandInstance,\n) => {\n let newResponse = response;\n if (!command.commandOptions.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, command);\n if (!newResponse) throw new Error(\"Response modifier must return data\");\n }\n }\n return newResponse;\n};\n// Mappers\n\nexport const getClientHeaders = (command: CommandInstance) => {\n const isFormData = command.data instanceof FormData;\n const headers: HeadersInit = {};\n\n if (!isFormData) headers[\"Content-Type\"] = \"application/json\";\n\n Object.assign(headers, command.headers);\n return headers as HeadersInit;\n};\n\nexport const getClientPayload = (data: unknown): string | FormData => {\n const isFormData = data instanceof FormData;\n if (isFormData) return data;\n\n return stringifyValue(data);\n};\n\n// Stringify\n\nconst isValidValue = (options: QueryStringifyOptions) => {\n return (value: ClientQueryParam) => {\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 = (value: string, { encode, strict }: Pick<QueryStringifyOptions, \"encode\" | \"strict\">): string => {\n if (encode && strict) {\n return encodeURIComponent(value).replace(/[!'()*]/g, (s) => `%${s.charCodeAt(0).toString(16).toUpperCase()}`);\n }\n if (encode) {\n return encodeURIComponent(value);\n }\n return value;\n};\n\nconst encodeParams = (key: string, value: ClientQueryParam, options: QueryStringifyOptions) => {\n const shouldSkip = !isValidValue(options)(value);\n\n if (!key || shouldSkip) {\n return \"\";\n }\n\n return `${encodeValue(key, options)}=${encodeValue(String(value), options)}`;\n};\n\nconst encodeArray = (key: string, array: Array<ClientQueryParamValues>, options: QueryStringifyOptions): string => {\n const { arrayFormat, arraySeparator } = options;\n\n return array\n .filter(isValidValue(options))\n .reduce<string[]>((acc, value, index) => {\n switch (arrayFormat) {\n case \"index\": {\n const keyValue = `${encodeValue(key, options)}[${encodeValue(String(index), options)}]=`;\n acc.push(`${keyValue}${encodeValue(String(value), options)}`);\n break;\n }\n case \"bracket\": {\n const keyValue = `${encodeValue(key, options)}[]=`;\n acc.push(`${keyValue}${encodeValue(String(value), options)}`);\n break;\n }\n case \"comma\": {\n const keyValue = (!acc.length && `${encodeValue(key, options)}=`) || \"\";\n return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(\",\")];\n }\n case \"separator\": {\n const keyValue = (!acc.length && `${encodeValue(key, options)}=`) || \"\";\n return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || \"|\")];\n }\n case \"bracket-separator\": {\n const keyValue = (!acc.length && `${encodeValue(key, options)}[]=`) || \"\";\n return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || \"|\")];\n }\n default: {\n const keyValue = `${encodeValue(key, options)}=`;\n acc.push(`${keyValue}${encodeValue(String(value), options)}`);\n }\n }\n\n return acc;\n }, [])\n .join(\"&\");\n};\n\nexport const stringifyQueryParams = (\n queryParams: ClientQueryParamsType | string | NegativeTypes,\n options: QueryStringifyOptions = stringifyDefaultOptions,\n): string => {\n if (!queryParams || !Object.keys(queryParams).length) {\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, options);\n }\n\n return encodeParams(key, value, options);\n })\n .filter(Boolean)\n .join(\"&\");\n\n if (stringified) {\n return `?${stringified}`;\n }\n return \"\";\n};\n", "import {\n ClientType,\n fetchClient,\n ClientDefaultOptionsType,\n ClientResponseType,\n ClientQueryParamsType,\n QueryStringifyOptions,\n ClientHeaderMappingCallback,\n ClientPayloadMappingCallback,\n} from \"client\";\nimport {\n stringifyQueryParams,\n getClientHeaders,\n getClientPayload,\n BuilderConfig,\n BuilderInstance,\n BuilderErrorType,\n StringifyCallbackType,\n RequestInterceptorCallback,\n ResponseInterceptorCallback,\n} from \"builder\";\nimport { Cache } from \"cache\";\nimport { Dispatcher } from \"dispatcher\";\nimport { FetchEffectInstance } from \"effect\";\nimport { Command, CommandConfig, CommandInstance } from \"command\";\nimport { AppManager, CommandManager, LoggerManager, SeverityType } from \"managers\";\nimport { interceptRequest, interceptResponse } from \"./builder.utils\";\n\n/**\n * **Builder** is a class that allows you to configure the connection with the server and then use it to create\n * commands which, when called using the appropriate method, will cause the server to be queried for the endpoint and\n * method specified in the command.\n */\nexport class Builder<GlobalErrorType extends BuilderErrorType = Error, RequestConfigType = ClientDefaultOptionsType> {\n readonly baseUrl: string;\n readonly isNodeJS: boolean;\n debug: boolean;\n\n // Private\n __onErrorCallbacks: ResponseInterceptorCallback[] = [];\n __onSuccessCallbacks: ResponseInterceptorCallback[] = [];\n __onResponseCallbacks: ResponseInterceptorCallback[] = [];\n __onAuthCallbacks: RequestInterceptorCallback[] = [];\n __onRequestCallbacks: RequestInterceptorCallback[] = [];\n\n // Managers\n commandManager: CommandManager = new CommandManager();\n appManager: AppManager;\n loggerManager: LoggerManager = new LoggerManager(this);\n\n // Config\n client: ClientType;\n cache: Cache;\n fetchDispatcher: Dispatcher;\n submitDispatcher: Dispatcher;\n\n // Registered requests effect\n effects: FetchEffectInstance[] = [];\n\n // Options\n requestConfig?: (command: CommandInstance) => RequestConfigType;\n commandConfig?: (\n commandOptions: CommandConfig<string, RequestConfigType>,\n ) => Partial<CommandConfig<string, RequestConfigType>>;\n queryParamsConfig?: QueryStringifyOptions;\n\n // Utils\n\n /**\n * Method to stringify query params from objects.\n */\n stringifyQueryParams: StringifyCallbackType = (queryParams) =>\n stringifyQueryParams(queryParams, this.queryParamsConfig);\n /**\n * Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats.\n */\n headerMapper: ClientHeaderMappingCallback = getClientHeaders;\n /**\n * Method to get request data and transform them to the required format. It handles FormData and JSON by default.\n */\n payloadMapper: ClientPayloadMappingCallback = getClientPayload;\n\n // Logger\n logger = this.loggerManager.init(\"Builder\");\n\n constructor(public options: BuilderConfig) {\n const { baseUrl, isNodeJS, client, appManager, cache, fetchDispatcher, submitDispatcher } = this.options;\n this.baseUrl = baseUrl;\n this.isNodeJS = isNodeJS;\n this.client = client || fetchClient;\n\n // IMPORTANT: Do not change initialization order as it's crucial for dependencies injection\n this.appManager = appManager?.(this) || new AppManager(this);\n this.cache = cache?.(this) || new Cache(this);\n this.fetchDispatcher = fetchDispatcher?.(this) || new Dispatcher(this);\n this.submitDispatcher = submitDispatcher?.(this) || new Dispatcher(this);\n }\n\n /**\n * This method allows to configure global defaults for the command configuration like method, auth, deduplication etc.\n */\n setCommandConfig = (\n callback: (command: CommandInstance) => Partial<CommandConfig<string, RequestConfigType>>,\n ): Builder<GlobalErrorType, RequestConfigType> => {\n this.commandConfig = callback;\n return this;\n };\n\n /**\n * This method enables the logger usage and display the logs in console\n */\n setDebug = (debug: boolean): Builder<GlobalErrorType, RequestConfigType> => {\n this.debug = debug;\n return this;\n };\n\n /**\n * Set the logger severity of the messages displayed to the console\n */\n setLoggerSeverity = (severity: SeverityType): Builder<GlobalErrorType, RequestConfigType> => {\n this.loggerManager.setSeverity(severity);\n return this;\n };\n\n /**\n * Set the new logger instance to the builder\n */\n setLogger = (callback: (builder: BuilderInstance) => LoggerManager): Builder<GlobalErrorType, RequestConfigType> => {\n this.loggerManager = callback(this);\n return this;\n };\n\n /**\n * Set config for the query params stringify method, we can set here, among others, arrayFormat, skipNull, encode, skipEmptyString and more\n */\n setQueryParamsConfig = (queryParamsConfig: QueryStringifyOptions): Builder<GlobalErrorType, RequestConfigType> => {\n this.queryParamsConfig = queryParamsConfig;\n return this;\n };\n\n /**\n * Set the custom query params stringify method to the builder\n * @param stringifyFn Custom callback handling query params stringify\n */\n setStringifyQueryParams = (stringifyFn: StringifyCallbackType): Builder<GlobalErrorType, RequestConfigType> => {\n this.stringifyQueryParams = stringifyFn;\n return this;\n };\n\n /**\n * Set the custom header mapping function\n */\n setHeaderMapper = (headerMapper: ClientHeaderMappingCallback): Builder<GlobalErrorType, RequestConfigType> => {\n this.headerMapper = headerMapper;\n return this;\n };\n\n /**\n * Set the request payload mapping function which get triggered before request get send\n */\n setPayloadMapper = (payloadMapper: ClientPayloadMappingCallback): Builder<GlobalErrorType, RequestConfigType> => {\n this.payloadMapper = payloadMapper;\n return this;\n };\n\n /**\n * Set custom http client to handle graphql, rest, firebase or other\n */\n setClient = (callback: (builder: BuilderInstance) => ClientType): Builder<GlobalErrorType, RequestConfigType> => {\n this.client = callback(this);\n return this;\n };\n\n /**\n * Method of manipulating commands before sending the request. We can for example add custom header with token to the request which command had the auth set to true.\n */\n onAuth = (callback: RequestInterceptorCallback): Builder<GlobalErrorType, RequestConfigType> => {\n this.__onAuthCallbacks.push(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: ResponseInterceptorCallback<any, ErrorType | GlobalErrorType>,\n ): Builder<GlobalErrorType, RequestConfigType> => {\n this.__onErrorCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for intercepting success responses.\n */\n onSuccess = <ErrorType = null>(\n callback: ResponseInterceptorCallback<any, ErrorType | GlobalErrorType>,\n ): Builder<GlobalErrorType, RequestConfigType> => {\n this.__onSuccessCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method of manipulating commands before sending the request.\n */\n onRequest = (callback: RequestInterceptorCallback): Builder<GlobalErrorType, RequestConfigType> => {\n this.__onRequestCallbacks.push(callback);\n return this;\n };\n\n /**\n * Method for intercepting any responses.\n */\n onResponse = <ErrorType = null>(\n callback: ResponseInterceptorCallback<any, ErrorType | GlobalErrorType>,\n ): Builder<GlobalErrorType, RequestConfigType> => {\n this.__onResponseCallbacks.push(callback);\n return this;\n };\n\n /**\n * Add persistent effects which trigger on the request lifecycle\n */\n addEffect = (effect: FetchEffectInstance | FetchEffectInstance[]) => {\n this.effects = this.effects.concat(effect);\n\n return this;\n };\n\n /**\n * Remove effects from builder\n */\n removeEffect = (effect: FetchEffectInstance | string) => {\n const name = typeof effect === \"string\" ? effect : effect.getEffectKey();\n this.effects = this.effects.filter((currentEffect) => currentEffect.getEffectKey() !== name);\n\n return this;\n };\n\n /**\n * Create commands based on the builder setup\n */\n createCommand = <\n ResponseType,\n RequestDataType = undefined,\n LocalErrorType extends BuilderErrorType | undefined = undefined,\n QueryParamsType extends ClientQueryParamsType | string = ClientQueryParamsType | string,\n >() => {\n return <EndpointType extends string>(params: CommandConfig<EndpointType, RequestConfigType>) =>\n new Command<\n ResponseType,\n RequestDataType,\n QueryParamsType,\n GlobalErrorType,\n LocalErrorType,\n EndpointType,\n RequestConfigType\n >(this, params);\n };\n\n /**\n * Clears the builder instance and remove all listeners on it's dependencies\n */\n clear = () => {\n const { appManager, cache, fetchDispatcher, submitDispatcher } = this.options;\n\n this.commandManager.abortControllers.clear();\n this.fetchDispatcher.clear();\n this.submitDispatcher.clear();\n this.cache.clear();\n\n this.commandManager.emitter.removeAllListeners();\n this.fetchDispatcher.emitter.removeAllListeners();\n this.submitDispatcher.emitter.removeAllListeners();\n this.cache.emitter.removeAllListeners();\n\n this.appManager = appManager?.(this) || new AppManager(this);\n this.cache = cache?.(this) || new Cache(this);\n this.fetchDispatcher = fetchDispatcher?.(this) || new Dispatcher(this);\n this.submitDispatcher = submitDispatcher?.(this) || new Dispatcher(this);\n };\n\n /**\n * Helper used by http client to apply the modifications on response error\n */\n __modifyAuth = async (command: CommandInstance) => interceptRequest(this.__onAuthCallbacks, command);\n\n /**\n * Private helper to run async pre-request processing\n */\n __modifyRequest = async (command: CommandInstance) => interceptRequest(this.__onRequestCallbacks, command);\n\n /**\n * Private helper to run async on-error response processing\n */\n __modifyErrorResponse = async (response: ClientResponseType<any, GlobalErrorType>, command: CommandInstance) =>\n interceptResponse<GlobalErrorType>(this.__onErrorCallbacks, response, command);\n\n /**\n * Private helper to run async on-success response processing\n */\n __modifySuccessResponse = async (response: ClientResponseType<any, GlobalErrorType>, command: CommandInstance) =>\n interceptResponse<GlobalErrorType>(this.__onSuccessCallbacks, response, command);\n\n /**\n * Private helper to run async response processing\n */\n __modifyResponse = async (response: ClientResponseType<any, GlobalErrorType>, command: CommandInstance) =>\n interceptResponse<GlobalErrorType>(this.__onResponseCallbacks, response, command);\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"],
5
+ "mappings": "kzBAKO,GAAM,IAAN,KAA6C,CAClD,YAAmB,EAA8B,CAA9B,cAEnB,kBAAe,IACN,KAAK,OAAO,UAGrB,eAAY,AAAC,GAAe,CAZ9B,QAaI,WAAK,QAAO,YAAZ,eAAwB,EAC1B,EACA,aAAU,AAAC,GAAe,CAf5B,QAgBI,WAAK,QAAO,UAAZ,eAAsB,EACxB,EACA,eAAY,CAAC,EAAmD,IAAe,CAlBjF,QAmBI,WAAK,QAAO,YAAZ,eAAwB,EAAU,EACpC,EACA,aAAU,CAAC,EAAoD,IAAe,CArBhF,QAsBI,WAAK,QAAO,UAAZ,eAAsB,EAAU,EAClC,EACA,gBAAa,CAAC,EAA6D,IAAe,CAxB5F,QAyBI,WAAK,QAAO,aAAZ,eAAyB,EAAU,EACrC,CApBkD,CAqBpD,ECtBO,GAAM,GAAkB,AAAC,GAC1B,IAAc,UACT,GAAI,OAAM,iBAAiB,EAEhC,IAAc,QACT,GAAI,OAAM,mBAAmB,EAE/B,GAAI,OAAM,kBAAkB,EAKxB,GAAgB,AAAC,GAA+B,CAC3D,GAAI,CACF,MAAO,MAAK,MAAM,CAAkB,CACtC,OAAS,EAAP,CACA,MAAO,EACT,CACF,EAEa,GAAqB,AAA4B,GACrD,EAAW,GAAc,CAAQ,EAAI,EAAgB,ECvBvD,GAAM,IAA0B,CAAO,EAAS,IAAc,0BACnE,GAAI,CAAC,OAAO,eACV,KAAM,IAAI,OAAM,yFAAyF,EAG3G,GAAM,CACJ,UACA,UACA,UACA,SACA,sBACA,kBAC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";
3
+ export declare enum AppEvents {
4
+ focus = "focus",
5
+ blur = "blur",
6
+ online = "online",
7
+ offline = "offline"
8
+ }
9
+ export declare const appManagerInitialOptions: RequiredKeys<AppManagerOptionsType>;
@@ -0,0 +1,35 @@
1
+ /// <reference types="node" />
2
+ import EventEmitter from "events";
3
+ import { BuilderInstance } from "../../builder";
4
+ import { AppManagerOptionsType } from "./..";
5
+ /**
6
+ * App manager handles main application states - focus and online. Those two values can answer questions:
7
+ * - Is the tab or current view instance focused and visible for user?
8
+ * - Is our application online or offline?
9
+ * With the app manager it is not a problem to get the valid answer for this question.
10
+ *
11
+ * @caution
12
+ * Make sure to apply valid focus/online handlers for different environments like for example for native mobile applications.
13
+ */
14
+ export declare class AppManager {
15
+ builder: BuilderInstance;
16
+ options?: AppManagerOptionsType;
17
+ emitter: EventEmitter;
18
+ events: {
19
+ emitFocus: () => void;
20
+ emitBlur: () => void;
21
+ emitOnline: () => void;
22
+ emitOffline: () => void;
23
+ onFocus: (callback: () => void) => VoidFunction;
24
+ onBlur: (callback: () => void) => VoidFunction;
25
+ onOnline: (callback: () => void) => VoidFunction;
26
+ onOffline: (callback: () => void) => VoidFunction;
27
+ };
28
+ isOnline: boolean;
29
+ isFocused: boolean;
30
+ constructor(builder: BuilderInstance, options?: AppManagerOptionsType);
31
+ private setInitialFocus;
32
+ private setInitialOnline;
33
+ setFocused: (isFocused: boolean) => void;
34
+ setOnline: (isOnline: boolean) => void;
35
+ }
@@ -0,0 +1,11 @@
1
+ import EventEmitter from "events";
2
+ export declare const getAppManagerEvents: (emitter: EventEmitter) => {
3
+ emitFocus: () => void;
4
+ emitBlur: () => void;
5
+ emitOnline: () => void;
6
+ emitOffline: () => void;
7
+ onFocus: (callback: () => void) => VoidFunction;
8
+ onBlur: (callback: () => void) => VoidFunction;
9
+ onOnline: (callback: () => void) => VoidFunction;
10
+ onOffline: (callback: () => void) => VoidFunction;
11
+ };
@@ -0,0 +1,7 @@
1
+ import { BuilderInstance } from "../../builder";
2
+ export declare type AppManagerOptionsType = {
3
+ initiallyFocused?: boolean | (() => boolean | Promise<boolean>);
4
+ initiallyOnline?: boolean | (() => boolean | Promise<boolean>);
5
+ focusEvent?: (setFocused: (isFocused: boolean) => void, builder: BuilderInstance) => void;
6
+ onlineEvent?: (setOnline: (isOnline: boolean) => void, builder: BuilderInstance) => void;
7
+ };
@@ -0,0 +1,4 @@
1
+ export declare const hasWindow: () => boolean;
2
+ export declare const hasDocument: () => boolean;
3
+ export declare const onWindowEvent: <K extends keyof WindowEventMap>(key: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined) => void;
4
+ export declare const onDocumentEvent: <K extends keyof DocumentEventMap>(key: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined) => void;
@@ -0,0 +1,5 @@
1
+ export * from "./app.manager";
2
+ export * from "./app.manager.types";
3
+ export * from "./app.manager.utils";
4
+ export * from "./app.manager.events";
5
+ export * from "./app.manager.constants";
@@ -0,0 +1,43 @@
1
+ /// <reference types="node" />
2
+ import EventEmitter from "events";
3
+ /**
4
+ * **Command Manager** is used to emit `command lifecycle events` like - request start, request end, upload and download progress.
5
+ * It is also the place of `request aborting` system, here we store all the keys and controllers that are isolated for each builder instance.
6
+ */
7
+ export declare class CommandManager {
8
+ emitter: EventEmitter;
9
+ events: {
10
+ emitLoading: (queueKey: string, requestId: string, values: import("./..").CommandLoadingEventType) => void;
11
+ emitRequestStart: (queueKey: string, requestId: string, details: import("./..").CommandEventDetails<import("../..").CommandInstance>) => void;
12
+ emitResponseStart: (queueKey: string, requestId: string, details: import("./..").CommandEventDetails<import("../..").CommandInstance>) => void;
13
+ emitUploadProgress: (queueKey: string, requestId: string, values: import("../..").FetchProgressType, details: import("./..").CommandEventDetails<import("../..").CommandInstance>) => void;
14
+ emitDownloadProgress: (queueKey: string, requestId: string, values: import("../..").FetchProgressType, details: import("./..").CommandEventDetails<import("../..").CommandInstance>) => void;
15
+ emitResponse: (cacheKey: string, requestId: string, response: import("../..").ClientResponseType<unknown, unknown>, details: import("./..").CommandResponseDetails) => void;
16
+ emitAbort: (abortKey: string, requestId: string, command: import("../..").CommandInstance) => void;
17
+ emitRemove: <T extends import("../..").CommandInstance>(queueKey: string, requestId: string, details: import("./..").CommandEventDetails<T>) => void;
18
+ onLoading: (queueKey: string, callback: (values: import("./..").CommandLoadingEventType) => void) => VoidFunction;
19
+ onLoadingById: (requestId: string, callback: (values: import("./..").CommandLoadingEventType) => void) => VoidFunction;
20
+ onRequestStart: <T_1 extends import("../..").CommandInstance>(queueKey: string, callback: (details: import("./..").CommandEventDetails<T_1>) => void) => VoidFunction;
21
+ onRequestStartById: <T_2 extends import("../..").CommandInstance>(requestId: string, callback: (details: import("./..").CommandEventDetails<T_2>) => void) => VoidFunction;
22
+ onResponseStart: <T_3 extends import("../..").CommandInstance>(queueKey: string, callback: (details: import("./..").CommandEventDetails<T_3>) => void) => VoidFunction;
23
+ onResponseStartById: <T_4 extends import("../..").CommandInstance>(requestId: string, callback: (details: import("./..").CommandEventDetails<T_4>) => void) => VoidFunction;
24
+ onUploadProgress: <T_5 extends import("../..").CommandInstance = import("../..").CommandInstance>(queueKey: string, callback: (values: import("../..").FetchProgressType, details: import("./..").CommandEventDetails<T_5>) => void) => VoidFunction;
25
+ onUploadProgressById: <T_6 extends import("../..").CommandInstance = import("../..").CommandInstance>(requestId: string, callback: (values: import("../..").FetchProgressType, details: import("./..").CommandEventDetails<T_6>) => void) => VoidFunction;
26
+ onDownloadProgress: <T_7 extends import("../..").CommandInstance = import("../..").CommandInstance>(queueKey: string, callback: (values: import("../..").FetchProgressType, details: import("./..").CommandEventDetails<T_7>) => void) => VoidFunction;
27
+ onDownloadProgressById: <T_8 extends import("../..").CommandInstance = import("../..").CommandInstance>(requestId: string, callback: (values: import("../..").FetchProgressType, details: import("./..").CommandEventDetails<T_8>) => void) => VoidFunction;
28
+ onResponse: <ResponseType_1, ErrorType>(cacheKey: string, callback: (response: import("../..").ClientResponseType<ResponseType_1, ErrorType>, details: import("./..").CommandResponseDetails) => void) => VoidFunction;
29
+ onResponseById: <ResponseType_2, ErrorType_1>(requestId: string, callback: (response: import("../..").ClientResponseType<ResponseType_2, ErrorType_1>, details: import("./..").CommandResponseDetails) => void) => VoidFunction;
30
+ onAbort: (abortKey: string, callback: (command: import("../..").CommandInstance) => void) => VoidFunction;
31
+ onAbortById: (requestId: string, callback: (command: import("../..").CommandInstance) => void) => VoidFunction;
32
+ onRemove: <T_9 extends import("../..").CommandInstance = import("../..").CommandInstance>(queueKey: string, callback: (details: import("./..").CommandEventDetails<T_9>) => void) => VoidFunction;
33
+ onRemoveById: <T_10 extends import("../..").CommandInstance = import("../..").CommandInstance>(requestId: string, callback: (details: import("./..").CommandEventDetails<T_10>) => void) => VoidFunction;
34
+ };
35
+ abortControllers: Map<string, Map<string, AbortController>>;
36
+ addAbortController: (abortKey: string, requestId: string) => void;
37
+ getAbortController: (abortKey: string, requestId: string) => AbortController;
38
+ removeAbortController: (abortKey: string, requestId: string) => void;
39
+ useAbortController: (abortKey: string, requestId: string) => void;
40
+ abortByKey: (abortKey: string) => void;
41
+ abortByRequestId: (abortKey: string, requestId: string) => void;
42
+ abortAll: () => void;
43
+ }
@@ -0,0 +1,36 @@
1
+ import EventEmitter from "events";
2
+ import { CommandEventDetails, CommandResponseDetails, CommandLoadingEventType } from "./..";
3
+ import { FetchProgressType, ClientResponseType } from "../../client";
4
+ import { CommandInstance } from "../../command";
5
+ export declare const getCommandManagerEvents: (emitter: EventEmitter) => {
6
+ /**
7
+ * Emiter
8
+ */
9
+ emitLoading: (queueKey: string, requestId: string, values: CommandLoadingEventType) => void;
10
+ emitRequestStart: (queueKey: string, requestId: string, details: CommandEventDetails<CommandInstance>) => void;
11
+ emitResponseStart: (queueKey: string, requestId: string, details: CommandEventDetails<CommandInstance>) => void;
12
+ emitUploadProgress: (queueKey: string, requestId: string, values: FetchProgressType, details: CommandEventDetails<CommandInstance>) => void;
13
+ emitDownloadProgress: (queueKey: string, requestId: string, values: FetchProgressType, details: CommandEventDetails<CommandInstance>) => void;
14
+ emitResponse: (cacheKey: string, requestId: string, response: ClientResponseType<unknown, unknown>, details: CommandResponseDetails) => void;
15
+ emitAbort: (abortKey: string, requestId: string, command: CommandInstance) => void;
16
+ emitRemove: <T extends CommandInstance>(queueKey: string, requestId: string, details: CommandEventDetails<T>) => void;
17
+ /**
18
+ * Listeners
19
+ */
20
+ onLoading: (queueKey: string, callback: (values: CommandLoadingEventType) => void) => VoidFunction;
21
+ onLoadingById: (requestId: string, callback: (values: CommandLoadingEventType) => void) => VoidFunction;
22
+ onRequestStart: <T_1 extends CommandInstance>(queueKey: string, callback: (details: CommandEventDetails<T_1>) => void) => VoidFunction;
23
+ onRequestStartById: <T_2 extends CommandInstance>(requestId: string, callback: (details: CommandEventDetails<T_2>) => void) => VoidFunction;
24
+ onResponseStart: <T_3 extends CommandInstance>(queueKey: string, callback: (details: CommandEventDetails<T_3>) => void) => VoidFunction;
25
+ onResponseStartById: <T_4 extends CommandInstance>(requestId: string, callback: (details: CommandEventDetails<T_4>) => void) => VoidFunction;
26
+ onUploadProgress: <T_5 extends CommandInstance = CommandInstance>(queueKey: string, callback: (values: FetchProgressType, details: CommandEventDetails<T_5>) => void) => VoidFunction;
27
+ onUploadProgressById: <T_6 extends CommandInstance = CommandInstance>(requestId: string, callback: (values: FetchProgressType, details: CommandEventDetails<T_6>) => void) => VoidFunction;
28
+ onDownloadProgress: <T_7 extends CommandInstance = CommandInstance>(queueKey: string, callback: (values: FetchProgressType, details: CommandEventDetails<T_7>) => void) => VoidFunction;
29
+ onDownloadProgressById: <T_8 extends CommandInstance = CommandInstance>(requestId: string, callback: (values: FetchProgressType, details: CommandEventDetails<T_8>) => void) => VoidFunction;
30
+ onResponse: <ResponseType_1, ErrorType>(cacheKey: string, callback: (response: ClientResponseType<ResponseType_1, ErrorType>, details: CommandResponseDetails) => void) => VoidFunction;
31
+ onResponseById: <ResponseType_2, ErrorType_1>(requestId: string, callback: (response: ClientResponseType<ResponseType_2, ErrorType_1>, details: CommandResponseDetails) => void) => VoidFunction;
32
+ onAbort: (abortKey: string, callback: (command: CommandInstance) => void) => VoidFunction;
33
+ onAbortById: (requestId: string, callback: (command: CommandInstance) => void) => VoidFunction;
34
+ onRemove: <T_9 extends CommandInstance = CommandInstance>(queueKey: string, callback: (details: CommandEventDetails<T_9>) => void) => VoidFunction;
35
+ onRemoveById: <T_10 extends CommandInstance = CommandInstance>(requestId: string, callback: (details: CommandEventDetails<T_10>) => void) => VoidFunction;
36
+ };
@@ -0,0 +1,23 @@
1
+ import { CommandInstance } from "../../command";
2
+ export declare type CommandLoadingEventType = {
3
+ queueKey: string;
4
+ requestId: string;
5
+ loading: boolean;
6
+ isRetry: boolean;
7
+ isOffline: boolean;
8
+ };
9
+ export declare type CommandEventDetails<T extends CommandInstance> = {
10
+ requestId: string;
11
+ command: T;
12
+ };
13
+ export declare type CommandResponseDetails = {
14
+ retries: number;
15
+ timestamp: number;
16
+ isFailed: boolean;
17
+ isCanceled: boolean;
18
+ isOffline: boolean;
19
+ };
20
+ export declare type CommandRemoveDetails = {
21
+ queueKey: string;
22
+ requestId: string;
23
+ };
@@ -0,0 +1,16 @@
1
+ export declare const getLoadingEventKey: (key: string) => string;
2
+ export declare const getLoadingIdEventKey: (key: string) => string;
3
+ export declare const getRemoveEventKey: (key: string) => string;
4
+ export declare const getRemoveIdEventKey: (key: string) => string;
5
+ export declare const getAbortEventKey: (key: string) => string;
6
+ export declare const getAbortByIdEventKey: (key: string) => string;
7
+ export declare const getResponseEventKey: (key: string) => string;
8
+ export declare const getResponseIdEventKey: (key: string) => string;
9
+ export declare const getRequestStartEventKey: (key: string) => string;
10
+ export declare const getRequestStartIdEventKey: (key: string) => string;
11
+ export declare const getResponseStartEventKey: (key: string) => string;
12
+ export declare const getResponseStartIdEventKey: (key: string) => string;
13
+ export declare const getUploadProgressEventKey: (key: string) => string;
14
+ export declare const getUploadProgressIdEventKey: (key: string) => string;
15
+ export declare const getDownloadProgressEventKey: (key: string) => string;
16
+ export declare const getDownloadProgressIdEventKey: (key: string) => string;
@@ -0,0 +1,4 @@
1
+ export * from "./command.manager";
2
+ export * from "./command.manager.utils";
3
+ export * from "./command.manager.events";
4
+ export * from "./command.manager.types";
@@ -0,0 +1,3 @@
1
+ export * from "./app";
2
+ export * from "./command";
3
+ export * from "./logger";
@@ -0,0 +1,4 @@
1
+ export * from "./logger.manager";
2
+ export * from "./logger.manager.utils";
3
+ export * from "./logger.manager.types";
4
+ export * from "./logger.manager.constants";
@@ -0,0 +1,4 @@
1
+ import { LoggerLevelType } from "./logger.manager.types";
2
+ export declare const loggerStyles: Record<LoggerLevelType, string>;
3
+ export declare const loggerIconLevels: Record<LoggerLevelType, string>;
4
+ export declare const severity: Record<LoggerLevelType, number>;