@hyper-fetch/core 7.5.2 → 8.0.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.
- package/.eslintrc.cjs +12 -0
- package/__tests__/e2e/e2e.abort-timeout.spec.ts +101 -0
- package/__tests__/e2e/e2e.advanced.spec.ts +423 -0
- package/__tests__/e2e/e2e.methods.spec.ts +243 -0
- package/__tests__/e2e/e2e.payloads.spec.ts +154 -0
- package/__tests__/features/adapter/adapter.base.spec.ts +414 -0
- package/__tests__/features/adapter/adapter.bindings.spec.ts +1025 -0
- package/__tests__/features/adapter/adapter.browser.spec.ts +88 -0
- package/__tests__/features/adapter/adapter.server.spec.ts +369 -0
- package/__tests__/features/adapter/adapter.utils.spec.ts +165 -0
- package/__tests__/features/cache/cache.base.spec.ts +366 -0
- package/__tests__/features/cache/cache.events.spec.ts +219 -0
- package/__tests__/features/cache/cache.garbage-collector.spec.ts +175 -0
- package/__tests__/features/cache/cache.lazy-storage.spec.ts +132 -0
- package/__tests__/features/cache/cache.modes.spec.ts +145 -0
- package/__tests__/features/cache/cache.scoping.spec.ts +171 -0
- package/__tests__/features/cache/cache.typescript.spec.ts +147 -0
- package/__tests__/features/cache/cache.utils.spec.ts +126 -0
- package/__tests__/features/client/client.auth.spec.ts +125 -0
- package/__tests__/features/client/client.base.spec.ts +161 -0
- package/__tests__/features/client/client.from-json.spec.ts +182 -0
- package/__tests__/features/client/client.hydration.spec.ts +236 -0
- package/__tests__/features/client/client.interceptor.spec.ts +225 -0
- package/__tests__/features/client/client.methods.spec.ts +189 -0
- package/__tests__/features/client/client.middleware.spec.ts +118 -0
- package/__tests__/features/client/client.utils.spec.ts +292 -0
- package/__tests__/features/dispatcher/dispatcher.base.spec.ts +123 -0
- package/__tests__/features/dispatcher/dispatcher.custom-storage.spec.ts +189 -0
- package/__tests__/features/dispatcher/dispatcher.events.spec.ts +309 -0
- package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +462 -0
- package/__tests__/features/dispatcher/dispatcher.requests.spec.ts +241 -0
- package/__tests__/features/dispatcher/dispatcher.utils.spec.ts +142 -0
- package/__tests__/features/managers/app/app.manager.base.spec.ts +235 -0
- package/__tests__/features/managers/app/app.manager.ssr.spec.ts +43 -0
- package/__tests__/features/managers/logger/logger.base.spec.ts +109 -0
- package/__tests__/features/managers/logger/logger.utils.spec.ts +106 -0
- package/__tests__/features/managers/request/request.manager.base.spec.ts +224 -0
- package/__tests__/features/managers/request/request.manager.events.spec.ts +364 -0
- package/__tests__/features/mocker/mocker.base.spec.ts +639 -0
- package/__tests__/features/plugin/plugin.base.spec.ts +255 -0
- package/__tests__/features/request/request.base.spec.ts +225 -0
- package/__tests__/features/request/request.cloning.spec.ts +47 -0
- package/__tests__/features/request/request.hooks.spec.ts +173 -0
- package/__tests__/features/request/request.optimistic.spec.ts +93 -0
- package/__tests__/features/request/request.retry-on-error.spec.ts +359 -0
- package/__tests__/features/request/request.sending.spec.ts +364 -0
- package/__tests__/features/request/request.setters.spec.ts +164 -0
- package/__tests__/features/request/request.typescript.spec.ts +423 -0
- package/__tests__/features/request/request.utils.spec.ts +77 -0
- package/__tests__/features/sdk/sdk.base.spec.ts +132 -0
- package/__tests__/features/sdk/sdk.configuration.spec.ts +262 -0
- package/__tests__/features/utils/emitter.utils.spec.ts +88 -0
- package/__tests__/shared/callbacks.shared.ts +11 -0
- package/__tests__/shared/index.ts +2 -0
- package/__tests__/shared/progress.shared.ts +36 -0
- package/__tests__/tsconfig.json +24 -0
- package/__tests__/type-stress/generate-stress-test.ts +92 -0
- package/__tests__/type-stress/stress-10.ts +35 -0
- package/__tests__/type-stress/stress-just-create.ts +2107 -0
- package/__tests__/type-stress/stress-minimal.ts +23 -0
- package/__tests__/type-stress/stress-test-500.ts +2319 -0
- package/__tests__/type-stress/stress-test-sdk.ts +210 -0
- package/__tests__/type-stress/tsconfig.json +6 -0
- package/__tests__/utils/adapter.utils.ts +39 -0
- package/__tests__/utils/cache.utils.ts +20 -0
- package/__tests__/utils/callbacks.utils.ts +48 -0
- package/__tests__/utils/dispatcher.utils.ts +7 -0
- package/__tests__/utils/index.ts +4 -0
- package/__tests__/vitest.setup.ts +15 -0
- package/dist/adapter/adapter.bindings.d.ts +71 -0
- package/dist/adapter/adapter.bindings.d.ts.map +1 -0
- package/dist/adapter/adapter.d.ts +127 -0
- package/dist/adapter/adapter.d.ts.map +1 -0
- package/dist/adapter/adapter.types.d.ts +108 -0
- package/dist/adapter/adapter.types.d.ts.map +1 -0
- package/dist/adapter/adapter.utils.d.ts +23 -0
- package/dist/adapter/adapter.utils.d.ts.map +1 -0
- package/dist/adapter/index.d.ts +5 -0
- package/dist/adapter/index.d.ts.map +1 -0
- package/dist/cache/cache.d.ts +95 -0
- package/dist/cache/cache.d.ts.map +1 -0
- package/dist/cache/cache.events.d.ts +51 -0
- package/dist/cache/cache.events.d.ts.map +1 -0
- package/dist/cache/cache.types.d.ts +44 -0
- package/dist/cache/cache.types.d.ts.map +1 -0
- package/dist/cache/cache.utils.d.ts +11 -0
- package/dist/cache/cache.utils.d.ts.map +1 -0
- package/dist/cache/index.d.ts +5 -0
- package/dist/cache/index.d.ts.map +1 -0
- package/dist/client/client.constants.d.ts +10 -0
- package/dist/client/client.constants.d.ts.map +1 -0
- package/dist/client/client.create.d.ts +8 -0
- package/dist/client/client.create.d.ts.map +1 -0
- package/dist/client/client.d.ts +195 -0
- package/dist/client/client.d.ts.map +1 -0
- package/dist/client/client.types.d.ts +71 -0
- package/dist/client/client.types.d.ts.map +1 -0
- package/dist/client/client.utils.d.ts +11 -0
- package/dist/client/client.utils.d.ts.map +1 -0
- package/dist/client/index.d.ts +6 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/constants/http.constants.d.ts +8 -0
- package/dist/constants/http.constants.d.ts.map +1 -0
- package/dist/constants/time.constants.d.ts +12 -0
- package/dist/constants/time.constants.d.ts.map +1 -0
- package/dist/dispatcher/dispatcher.constants.d.ts +7 -0
- package/dist/dispatcher/dispatcher.constants.d.ts.map +1 -0
- package/dist/dispatcher/dispatcher.d.ts +168 -0
- package/dist/dispatcher/dispatcher.d.ts.map +1 -0
- package/dist/dispatcher/dispatcher.events.d.ts +49 -0
- package/dist/dispatcher/dispatcher.events.d.ts.map +1 -0
- package/dist/dispatcher/dispatcher.types.d.ts +44 -0
- package/dist/dispatcher/dispatcher.types.d.ts.map +1 -0
- package/dist/dispatcher/dispatcher.utils.d.ts +12 -0
- package/dist/dispatcher/dispatcher.utils.d.ts.map +1 -0
- package/dist/dispatcher/index.d.ts +6 -0
- package/dist/dispatcher/index.d.ts.map +1 -0
- package/dist/http-adapter/http-adapter.constants.d.ts +4 -0
- package/dist/http-adapter/http-adapter.constants.d.ts.map +1 -0
- package/dist/http-adapter/http-adapter.d.ts +3 -0
- package/dist/http-adapter/http-adapter.d.ts.map +1 -0
- package/dist/http-adapter/http-adapter.fetch.d.ts +6 -0
- package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -0
- package/dist/http-adapter/http-adapter.types.d.ts +73 -0
- package/dist/http-adapter/http-adapter.types.d.ts.map +1 -0
- package/dist/http-adapter/http-adapter.utils.d.ts +10 -0
- package/dist/http-adapter/http-adapter.utils.d.ts.map +1 -0
- package/dist/http-adapter/index.d.ts +6 -0
- package/dist/http-adapter/index.d.ts.map +1 -0
- package/dist/index.d.ts +15 -2083
- package/dist/index.d.ts.map +1 -0
- package/dist/index.mjs +4084 -0
- package/dist/index.mjs.map +1 -0
- package/dist/managers/app/app.manager.constants.d.ts +10 -0
- package/dist/managers/app/app.manager.constants.d.ts.map +1 -0
- package/dist/managers/app/app.manager.d.ts +35 -0
- package/dist/managers/app/app.manager.d.ts.map +1 -0
- package/dist/managers/app/app.manager.events.d.ts +12 -0
- package/dist/managers/app/app.manager.events.d.ts.map +1 -0
- package/dist/managers/app/app.manager.types.d.ts +7 -0
- package/dist/managers/app/app.manager.types.d.ts.map +1 -0
- package/dist/managers/app/app.manager.utils.d.ts +5 -0
- package/dist/managers/app/app.manager.utils.d.ts.map +1 -0
- package/dist/managers/app/index.d.ts +6 -0
- package/dist/managers/app/index.d.ts.map +1 -0
- package/dist/managers/index.d.ts +4 -0
- package/dist/managers/index.d.ts.map +1 -0
- package/dist/managers/logger/index.d.ts +5 -0
- package/dist/managers/logger/index.d.ts.map +1 -0
- package/dist/managers/logger/logger.manager.constants.d.ts +5 -0
- package/dist/managers/logger/logger.manager.constants.d.ts.map +1 -0
- package/dist/managers/logger/logger.manager.d.ts +22 -0
- package/dist/managers/logger/logger.manager.d.ts.map +1 -0
- package/dist/managers/logger/logger.manager.types.d.ts +43 -0
- package/dist/managers/logger/logger.manager.types.d.ts.map +1 -0
- package/dist/managers/logger/logger.manager.utils.d.ts +4 -0
- package/dist/managers/logger/logger.manager.utils.d.ts.map +1 -0
- package/dist/managers/request/index.d.ts +5 -0
- package/dist/managers/request/index.d.ts.map +1 -0
- package/dist/managers/request/request.manager.d.ts +60 -0
- package/dist/managers/request/request.manager.d.ts.map +1 -0
- package/dist/managers/request/request.manager.events.d.ts +55 -0
- package/dist/managers/request/request.manager.events.d.ts.map +1 -0
- package/dist/managers/request/request.manager.types.d.ts +48 -0
- package/dist/managers/request/request.manager.types.d.ts.map +1 -0
- package/dist/managers/request/request.manager.utils.d.ts +30 -0
- package/dist/managers/request/request.manager.utils.d.ts.map +1 -0
- package/dist/mocker/index.d.ts +3 -0
- package/dist/mocker/index.d.ts.map +1 -0
- package/dist/mocker/mocker.d.ts +3 -0
- package/dist/mocker/mocker.d.ts.map +1 -0
- package/dist/mocker/mocker.types.d.ts +25 -0
- package/dist/mocker/mocker.types.d.ts.map +1 -0
- package/dist/plugin/index.d.ts +3 -0
- package/dist/plugin/index.d.ts.map +1 -0
- package/dist/plugin/plugin.d.ts +55 -0
- package/dist/plugin/plugin.d.ts.map +1 -0
- package/dist/plugin/plugin.types.d.ts +122 -0
- package/dist/plugin/plugin.types.d.ts.map +1 -0
- package/dist/request/index.d.ts +5 -0
- package/dist/request/index.d.ts.map +1 -0
- package/dist/request/request.d.ts +195 -0
- package/dist/request/request.d.ts.map +1 -0
- package/dist/request/request.hooks.d.ts +19 -0
- package/dist/request/request.hooks.d.ts.map +1 -0
- package/dist/request/request.types.d.ts +240 -0
- package/dist/request/request.types.d.ts.map +1 -0
- package/dist/request/request.utils.d.ts +25 -0
- package/dist/request/request.utils.d.ts.map +1 -0
- package/dist/sdk/index.d.ts +2 -0
- package/dist/sdk/index.d.ts.map +1 -0
- package/dist/sdk/sdk.d.ts +69 -0
- package/dist/sdk/sdk.d.ts.map +1 -0
- package/dist/types/adapter.types.d.ts +22 -0
- package/dist/types/adapter.types.d.ts.map +1 -0
- package/dist/types/client.types.d.ts +4 -0
- package/dist/types/client.types.d.ts.map +1 -0
- package/dist/types/helpers.types.d.ts +17 -0
- package/dist/types/helpers.types.d.ts.map +1 -0
- package/dist/types/http.types.d.ts +3 -0
- package/dist/types/http.types.d.ts.map +1 -0
- package/dist/types/hydration.types.d.ts +15 -0
- package/dist/types/hydration.types.d.ts.map +1 -0
- package/dist/types/index.d.ts +7 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/request.types.d.ts +34 -0
- package/dist/types/request.types.d.ts.map +1 -0
- package/dist/utils/emitter.utils.d.ts +13 -0
- package/dist/utils/emitter.utils.d.ts.map +1 -0
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/uuid.utils.d.ts +3 -0
- package/dist/utils/uuid.utils.d.ts.map +1 -0
- package/package.json +10 -25
- package/project.json +4 -0
- package/src/adapter/adapter.bindings.ts +8 -12
- package/src/adapter/adapter.ts +8 -7
- package/src/adapter/adapter.types.ts +10 -6
- package/src/adapter/adapter.utils.ts +1 -1
- package/src/cache/cache.events.ts +4 -11
- package/src/cache/cache.ts +28 -22
- package/src/cache/cache.types.ts +8 -4
- package/src/cache/cache.utils.ts +3 -3
- package/src/client/client.create.ts +4 -3
- package/src/client/client.ts +44 -12
- package/src/client/client.types.ts +25 -3
- package/src/client/client.utils.ts +24 -4
- package/src/dispatcher/dispatcher.events.ts +3 -3
- package/src/dispatcher/dispatcher.ts +59 -28
- package/src/dispatcher/dispatcher.types.ts +19 -2
- package/src/dispatcher/dispatcher.utils.ts +5 -4
- package/src/http-adapter/http-adapter.constants.ts +1 -1
- package/src/http-adapter/http-adapter.fetch.ts +174 -0
- package/src/http-adapter/http-adapter.ts +3 -8
- package/src/http-adapter/http-adapter.types.ts +17 -9
- package/src/http-adapter/http-adapter.utils.ts +6 -9
- package/src/http-adapter/index.ts +1 -0
- package/src/managers/app/app.manager.constants.ts +2 -2
- package/src/managers/app/app.manager.events.ts +1 -1
- package/src/managers/app/app.manager.ts +2 -1
- package/src/managers/logger/logger.manager.constants.ts +1 -1
- package/src/managers/logger/logger.manager.ts +2 -1
- package/src/managers/logger/logger.manager.types.ts +2 -2
- package/src/managers/logger/logger.manager.utils.ts +2 -1
- package/src/managers/request/request.manager.events.ts +13 -11
- package/src/managers/request/request.manager.types.ts +6 -3
- package/src/mocker/mocker.ts +3 -2
- package/src/mocker/mocker.types.ts +1 -1
- package/src/plugin/plugin.ts +2 -2
- package/src/plugin/plugin.types.ts +9 -9
- package/src/request/index.ts +1 -0
- package/src/request/request.hooks.ts +87 -0
- package/src/request/request.ts +155 -77
- package/src/request/request.types.ts +54 -22
- package/src/request/request.utils.ts +86 -23
- package/src/sdk/sdk.ts +153 -8
- package/src/types/adapter.types.ts +1 -1
- package/src/types/client.types.ts +1 -1
- package/src/types/hydration.types.ts +3 -3
- package/src/types/request.types.ts +30 -20
- package/src/utils/uuid.utils.ts +1 -1
- package/tsconfig.base.json +1 -6
- package/tsconfig.json +1 -4
- package/vite.config.ts +45 -0
- package/.eslintrc.json +0 -11
- package/dist/browser/index.js +0 -3751
- package/dist/browser/index.js.map +0 -7
- package/dist/index.js +0 -3991
- package/dist/index.js.map +0 -7
- package/src/http-adapter/http-adapter.browser.ts +0 -102
- package/src/http-adapter/http-adapter.server.ts +0 -135
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,4084 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
13
|
+
get: ((k) => from[k]).bind(null, key),
|
|
14
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
20
|
+
value: mod,
|
|
21
|
+
enumerable: true
|
|
22
|
+
}) : target, mod));
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/plugin/plugin.ts
|
|
25
|
+
var Plugin = class {
|
|
26
|
+
name;
|
|
27
|
+
data;
|
|
28
|
+
client = void 0;
|
|
29
|
+
pluginMethods = {};
|
|
30
|
+
constructor(config) {
|
|
31
|
+
this.config = config;
|
|
32
|
+
this.name = config.name;
|
|
33
|
+
if (config.data) this.data = config.data;
|
|
34
|
+
}
|
|
35
|
+
initialize = (client) => {
|
|
36
|
+
this.client = client;
|
|
37
|
+
return this;
|
|
38
|
+
};
|
|
39
|
+
trigger = (method, data) => {
|
|
40
|
+
const callback = this.pluginMethods[method];
|
|
41
|
+
if (callback) callback(data);
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Callback that will be executed when plugin is mounted
|
|
45
|
+
*/
|
|
46
|
+
onMount = (callback) => {
|
|
47
|
+
this.pluginMethods.onMount = callback;
|
|
48
|
+
return this;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Callback that will be executed when plugin is unmounted
|
|
52
|
+
*/
|
|
53
|
+
onUnmount = (callback) => {
|
|
54
|
+
this.pluginMethods.onUnmount = callback;
|
|
55
|
+
return this;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Callback that will be executed when request is created
|
|
59
|
+
*/
|
|
60
|
+
onRequestCreate = (callback) => {
|
|
61
|
+
this.pluginMethods.onRequestCreate = callback;
|
|
62
|
+
return this;
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Callback that will be executed when request gets triggered
|
|
66
|
+
*/
|
|
67
|
+
onRequestTrigger = (callback) => {
|
|
68
|
+
this.pluginMethods.onRequestTrigger = callback;
|
|
69
|
+
return this;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Callback that will be executed when request starts
|
|
73
|
+
*/
|
|
74
|
+
onRequestStart = (callback) => {
|
|
75
|
+
this.pluginMethods.onRequestStart = callback;
|
|
76
|
+
return this;
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Callback that will be executed when response is successful
|
|
80
|
+
*/
|
|
81
|
+
onRequestSuccess = (callback) => {
|
|
82
|
+
this.pluginMethods.onRequestSuccess = callback;
|
|
83
|
+
return this;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Callback that will be executed when response is failed
|
|
87
|
+
*/
|
|
88
|
+
onRequestError = (callback) => {
|
|
89
|
+
this.pluginMethods.onRequestError = callback;
|
|
90
|
+
return this;
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Callback that will be executed when response is finished
|
|
94
|
+
*/
|
|
95
|
+
onRequestFinished = (callback) => {
|
|
96
|
+
this.pluginMethods.onRequestFinished = callback;
|
|
97
|
+
return this;
|
|
98
|
+
};
|
|
99
|
+
onDispatcherCleared = (callback) => {
|
|
100
|
+
this.pluginMethods.onDispatcherCleared = callback;
|
|
101
|
+
return this;
|
|
102
|
+
};
|
|
103
|
+
onDispatcherQueueDrained = (callback) => {
|
|
104
|
+
this.pluginMethods.onDispatcherQueueDrained = callback;
|
|
105
|
+
return this;
|
|
106
|
+
};
|
|
107
|
+
onDispatcherQueueRunning = (callback) => {
|
|
108
|
+
this.pluginMethods.onDispatcherQueueRunning = callback;
|
|
109
|
+
return this;
|
|
110
|
+
};
|
|
111
|
+
onDispatcherItemAdded = (callback) => {
|
|
112
|
+
this.pluginMethods.onDispatcherItemAdded = callback;
|
|
113
|
+
return this;
|
|
114
|
+
};
|
|
115
|
+
onDispatcherItemDeleted = (callback) => {
|
|
116
|
+
this.pluginMethods.onDispatcherItemDeleted = callback;
|
|
117
|
+
return this;
|
|
118
|
+
};
|
|
119
|
+
onDispatcherQueueCreated = (callback) => {
|
|
120
|
+
this.pluginMethods.onDispatcherQueueCreated = callback;
|
|
121
|
+
return this;
|
|
122
|
+
};
|
|
123
|
+
onDispatcherQueueCleared = (callback) => {
|
|
124
|
+
this.pluginMethods.onDispatcherQueueCleared = callback;
|
|
125
|
+
return this;
|
|
126
|
+
};
|
|
127
|
+
onCacheItemChange = (callback) => {
|
|
128
|
+
this.pluginMethods.onCacheItemChange = callback;
|
|
129
|
+
return this;
|
|
130
|
+
};
|
|
131
|
+
onCacheItemDelete = (callback) => {
|
|
132
|
+
this.pluginMethods.onCacheItemDelete = callback;
|
|
133
|
+
return this;
|
|
134
|
+
};
|
|
135
|
+
onAdapterFetch = (callback) => {
|
|
136
|
+
this.pluginMethods.onAdapterFetch = callback;
|
|
137
|
+
return this;
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
//#endregion
|
|
141
|
+
//#region src/utils/uuid.utils.ts
|
|
142
|
+
var getUniqueRequestId = (request) => {
|
|
143
|
+
return `${request.queryKey}_${Date.now().toString(36)}_${Math.random().toString(36).substring(2)}`;
|
|
144
|
+
};
|
|
145
|
+
//#endregion
|
|
146
|
+
//#region src/utils/emitter.utils.ts
|
|
147
|
+
var import_events = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
148
|
+
var R = typeof Reflect === "object" ? Reflect : null;
|
|
149
|
+
var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply(target, receiver, args) {
|
|
150
|
+
return Function.prototype.apply.call(target, receiver, args);
|
|
151
|
+
};
|
|
152
|
+
var ReflectOwnKeys;
|
|
153
|
+
if (R && typeof R.ownKeys === "function") ReflectOwnKeys = R.ownKeys;
|
|
154
|
+
else if (Object.getOwnPropertySymbols) ReflectOwnKeys = function ReflectOwnKeys(target) {
|
|
155
|
+
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
|
|
156
|
+
};
|
|
157
|
+
else ReflectOwnKeys = function ReflectOwnKeys(target) {
|
|
158
|
+
return Object.getOwnPropertyNames(target);
|
|
159
|
+
};
|
|
160
|
+
function ProcessEmitWarning(warning) {
|
|
161
|
+
if (console && console.warn) console.warn(warning);
|
|
162
|
+
}
|
|
163
|
+
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
|
|
164
|
+
return value !== value;
|
|
165
|
+
};
|
|
166
|
+
function EventEmitter() {
|
|
167
|
+
EventEmitter.init.call(this);
|
|
168
|
+
}
|
|
169
|
+
module.exports = EventEmitter;
|
|
170
|
+
module.exports.once = once;
|
|
171
|
+
EventEmitter.EventEmitter = EventEmitter;
|
|
172
|
+
EventEmitter.prototype._events = void 0;
|
|
173
|
+
EventEmitter.prototype._eventsCount = 0;
|
|
174
|
+
EventEmitter.prototype._maxListeners = void 0;
|
|
175
|
+
var defaultMaxListeners = 10;
|
|
176
|
+
function checkListener(listener) {
|
|
177
|
+
if (typeof listener !== "function") throw new TypeError("The \"listener\" argument must be of type Function. Received type " + typeof listener);
|
|
178
|
+
}
|
|
179
|
+
Object.defineProperty(EventEmitter, "defaultMaxListeners", {
|
|
180
|
+
enumerable: true,
|
|
181
|
+
get: function() {
|
|
182
|
+
return defaultMaxListeners;
|
|
183
|
+
},
|
|
184
|
+
set: function(arg) {
|
|
185
|
+
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) throw new RangeError("The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received " + arg + ".");
|
|
186
|
+
defaultMaxListeners = arg;
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
EventEmitter.init = function() {
|
|
190
|
+
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
|
|
191
|
+
this._events = Object.create(null);
|
|
192
|
+
this._eventsCount = 0;
|
|
193
|
+
}
|
|
194
|
+
this._maxListeners = this._maxListeners || void 0;
|
|
195
|
+
};
|
|
196
|
+
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
|
|
197
|
+
if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) throw new RangeError("The value of \"n\" is out of range. It must be a non-negative number. Received " + n + ".");
|
|
198
|
+
this._maxListeners = n;
|
|
199
|
+
return this;
|
|
200
|
+
};
|
|
201
|
+
function _getMaxListeners(that) {
|
|
202
|
+
if (that._maxListeners === void 0) return EventEmitter.defaultMaxListeners;
|
|
203
|
+
return that._maxListeners;
|
|
204
|
+
}
|
|
205
|
+
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
|
|
206
|
+
return _getMaxListeners(this);
|
|
207
|
+
};
|
|
208
|
+
EventEmitter.prototype.emit = function emit(type) {
|
|
209
|
+
var args = [];
|
|
210
|
+
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
|
|
211
|
+
var doError = type === "error";
|
|
212
|
+
var events = this._events;
|
|
213
|
+
if (events !== void 0) doError = doError && events.error === void 0;
|
|
214
|
+
else if (!doError) return false;
|
|
215
|
+
if (doError) {
|
|
216
|
+
var er;
|
|
217
|
+
if (args.length > 0) er = args[0];
|
|
218
|
+
if (er instanceof Error) throw er;
|
|
219
|
+
var err = /* @__PURE__ */ new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
|
|
220
|
+
err.context = er;
|
|
221
|
+
throw err;
|
|
222
|
+
}
|
|
223
|
+
var handler = events[type];
|
|
224
|
+
if (handler === void 0) return false;
|
|
225
|
+
if (typeof handler === "function") ReflectApply(handler, this, args);
|
|
226
|
+
else {
|
|
227
|
+
var len = handler.length;
|
|
228
|
+
var listeners = arrayClone(handler, len);
|
|
229
|
+
for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args);
|
|
230
|
+
}
|
|
231
|
+
return true;
|
|
232
|
+
};
|
|
233
|
+
function _addListener(target, type, listener, prepend) {
|
|
234
|
+
var m;
|
|
235
|
+
var events;
|
|
236
|
+
var existing;
|
|
237
|
+
checkListener(listener);
|
|
238
|
+
events = target._events;
|
|
239
|
+
if (events === void 0) {
|
|
240
|
+
events = target._events = Object.create(null);
|
|
241
|
+
target._eventsCount = 0;
|
|
242
|
+
} else {
|
|
243
|
+
if (events.newListener !== void 0) {
|
|
244
|
+
target.emit("newListener", type, listener.listener ? listener.listener : listener);
|
|
245
|
+
events = target._events;
|
|
246
|
+
}
|
|
247
|
+
existing = events[type];
|
|
248
|
+
}
|
|
249
|
+
if (existing === void 0) {
|
|
250
|
+
existing = events[type] = listener;
|
|
251
|
+
++target._eventsCount;
|
|
252
|
+
} else {
|
|
253
|
+
if (typeof existing === "function") existing = events[type] = prepend ? [listener, existing] : [existing, listener];
|
|
254
|
+
else if (prepend) existing.unshift(listener);
|
|
255
|
+
else existing.push(listener);
|
|
256
|
+
m = _getMaxListeners(target);
|
|
257
|
+
if (m > 0 && existing.length > m && !existing.warned) {
|
|
258
|
+
existing.warned = true;
|
|
259
|
+
var w = /* @__PURE__ */ new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
|
|
260
|
+
w.name = "MaxListenersExceededWarning";
|
|
261
|
+
w.emitter = target;
|
|
262
|
+
w.type = type;
|
|
263
|
+
w.count = existing.length;
|
|
264
|
+
ProcessEmitWarning(w);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return target;
|
|
268
|
+
}
|
|
269
|
+
EventEmitter.prototype.addListener = function addListener(type, listener) {
|
|
270
|
+
return _addListener(this, type, listener, false);
|
|
271
|
+
};
|
|
272
|
+
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
|
|
273
|
+
EventEmitter.prototype.prependListener = function prependListener(type, listener) {
|
|
274
|
+
return _addListener(this, type, listener, true);
|
|
275
|
+
};
|
|
276
|
+
function onceWrapper() {
|
|
277
|
+
if (!this.fired) {
|
|
278
|
+
this.target.removeListener(this.type, this.wrapFn);
|
|
279
|
+
this.fired = true;
|
|
280
|
+
if (arguments.length === 0) return this.listener.call(this.target);
|
|
281
|
+
return this.listener.apply(this.target, arguments);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function _onceWrap(target, type, listener) {
|
|
285
|
+
var state = {
|
|
286
|
+
fired: false,
|
|
287
|
+
wrapFn: void 0,
|
|
288
|
+
target,
|
|
289
|
+
type,
|
|
290
|
+
listener
|
|
291
|
+
};
|
|
292
|
+
var wrapped = onceWrapper.bind(state);
|
|
293
|
+
wrapped.listener = listener;
|
|
294
|
+
state.wrapFn = wrapped;
|
|
295
|
+
return wrapped;
|
|
296
|
+
}
|
|
297
|
+
EventEmitter.prototype.once = function once(type, listener) {
|
|
298
|
+
checkListener(listener);
|
|
299
|
+
this.on(type, _onceWrap(this, type, listener));
|
|
300
|
+
return this;
|
|
301
|
+
};
|
|
302
|
+
EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) {
|
|
303
|
+
checkListener(listener);
|
|
304
|
+
this.prependListener(type, _onceWrap(this, type, listener));
|
|
305
|
+
return this;
|
|
306
|
+
};
|
|
307
|
+
EventEmitter.prototype.removeListener = function removeListener(type, listener) {
|
|
308
|
+
var list, events, position, i, originalListener;
|
|
309
|
+
checkListener(listener);
|
|
310
|
+
events = this._events;
|
|
311
|
+
if (events === void 0) return this;
|
|
312
|
+
list = events[type];
|
|
313
|
+
if (list === void 0) return this;
|
|
314
|
+
if (list === listener || list.listener === listener) if (--this._eventsCount === 0) this._events = Object.create(null);
|
|
315
|
+
else {
|
|
316
|
+
delete events[type];
|
|
317
|
+
if (events.removeListener) this.emit("removeListener", type, list.listener || listener);
|
|
318
|
+
}
|
|
319
|
+
else if (typeof list !== "function") {
|
|
320
|
+
position = -1;
|
|
321
|
+
for (i = list.length - 1; i >= 0; i--) if (list[i] === listener || list[i].listener === listener) {
|
|
322
|
+
originalListener = list[i].listener;
|
|
323
|
+
position = i;
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
if (position < 0) return this;
|
|
327
|
+
if (position === 0) list.shift();
|
|
328
|
+
else spliceOne(list, position);
|
|
329
|
+
if (list.length === 1) events[type] = list[0];
|
|
330
|
+
if (events.removeListener !== void 0) this.emit("removeListener", type, originalListener || listener);
|
|
331
|
+
}
|
|
332
|
+
return this;
|
|
333
|
+
};
|
|
334
|
+
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
|
|
335
|
+
EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) {
|
|
336
|
+
var listeners, events = this._events, i;
|
|
337
|
+
if (events === void 0) return this;
|
|
338
|
+
if (events.removeListener === void 0) {
|
|
339
|
+
if (arguments.length === 0) {
|
|
340
|
+
this._events = Object.create(null);
|
|
341
|
+
this._eventsCount = 0;
|
|
342
|
+
} else if (events[type] !== void 0) if (--this._eventsCount === 0) this._events = Object.create(null);
|
|
343
|
+
else delete events[type];
|
|
344
|
+
return this;
|
|
345
|
+
}
|
|
346
|
+
if (arguments.length === 0) {
|
|
347
|
+
var keys = Object.keys(events);
|
|
348
|
+
var key;
|
|
349
|
+
for (i = 0; i < keys.length; ++i) {
|
|
350
|
+
key = keys[i];
|
|
351
|
+
if (key === "removeListener") continue;
|
|
352
|
+
this.removeAllListeners(key);
|
|
353
|
+
}
|
|
354
|
+
this.removeAllListeners("removeListener");
|
|
355
|
+
this._events = Object.create(null);
|
|
356
|
+
this._eventsCount = 0;
|
|
357
|
+
return this;
|
|
358
|
+
}
|
|
359
|
+
listeners = events[type];
|
|
360
|
+
if (typeof listeners === "function") this.removeListener(type, listeners);
|
|
361
|
+
else if (listeners !== void 0) for (i = listeners.length - 1; i >= 0; i--) this.removeListener(type, listeners[i]);
|
|
362
|
+
return this;
|
|
363
|
+
};
|
|
364
|
+
function _listeners(target, type, unwrap) {
|
|
365
|
+
var events = target._events;
|
|
366
|
+
if (events === void 0) return [];
|
|
367
|
+
var evlistener = events[type];
|
|
368
|
+
if (evlistener === void 0) return [];
|
|
369
|
+
if (typeof evlistener === "function") return unwrap ? [evlistener.listener || evlistener] : [evlistener];
|
|
370
|
+
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
|
|
371
|
+
}
|
|
372
|
+
EventEmitter.prototype.listeners = function listeners(type) {
|
|
373
|
+
return _listeners(this, type, true);
|
|
374
|
+
};
|
|
375
|
+
EventEmitter.prototype.rawListeners = function rawListeners(type) {
|
|
376
|
+
return _listeners(this, type, false);
|
|
377
|
+
};
|
|
378
|
+
EventEmitter.listenerCount = function(emitter, type) {
|
|
379
|
+
if (typeof emitter.listenerCount === "function") return emitter.listenerCount(type);
|
|
380
|
+
else return listenerCount.call(emitter, type);
|
|
381
|
+
};
|
|
382
|
+
EventEmitter.prototype.listenerCount = listenerCount;
|
|
383
|
+
function listenerCount(type) {
|
|
384
|
+
var events = this._events;
|
|
385
|
+
if (events !== void 0) {
|
|
386
|
+
var evlistener = events[type];
|
|
387
|
+
if (typeof evlistener === "function") return 1;
|
|
388
|
+
else if (evlistener !== void 0) return evlistener.length;
|
|
389
|
+
}
|
|
390
|
+
return 0;
|
|
391
|
+
}
|
|
392
|
+
EventEmitter.prototype.eventNames = function eventNames() {
|
|
393
|
+
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
|
|
394
|
+
};
|
|
395
|
+
function arrayClone(arr, n) {
|
|
396
|
+
var copy = new Array(n);
|
|
397
|
+
for (var i = 0; i < n; ++i) copy[i] = arr[i];
|
|
398
|
+
return copy;
|
|
399
|
+
}
|
|
400
|
+
function spliceOne(list, index) {
|
|
401
|
+
for (; index + 1 < list.length; index++) list[index] = list[index + 1];
|
|
402
|
+
list.pop();
|
|
403
|
+
}
|
|
404
|
+
function unwrapListeners(arr) {
|
|
405
|
+
var ret = new Array(arr.length);
|
|
406
|
+
for (var i = 0; i < ret.length; ++i) ret[i] = arr[i].listener || arr[i];
|
|
407
|
+
return ret;
|
|
408
|
+
}
|
|
409
|
+
function once(emitter, name) {
|
|
410
|
+
return new Promise(function(resolve, reject) {
|
|
411
|
+
function errorListener(err) {
|
|
412
|
+
emitter.removeListener(name, resolver);
|
|
413
|
+
reject(err);
|
|
414
|
+
}
|
|
415
|
+
function resolver() {
|
|
416
|
+
if (typeof emitter.removeListener === "function") emitter.removeListener("error", errorListener);
|
|
417
|
+
resolve([].slice.call(arguments));
|
|
418
|
+
}
|
|
419
|
+
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
|
|
420
|
+
if (name !== "error") addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
|
|
424
|
+
if (typeof emitter.on === "function") eventTargetAgnosticAddListener(emitter, "error", handler, flags);
|
|
425
|
+
}
|
|
426
|
+
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
|
|
427
|
+
if (typeof emitter.on === "function") if (flags.once) emitter.once(name, listener);
|
|
428
|
+
else emitter.on(name, listener);
|
|
429
|
+
else if (typeof emitter.addEventListener === "function") emitter.addEventListener(name, function wrapListener(arg) {
|
|
430
|
+
if (flags.once) emitter.removeEventListener(name, wrapListener);
|
|
431
|
+
listener(arg);
|
|
432
|
+
});
|
|
433
|
+
else throw new TypeError("The \"emitter\" argument must be of type EventEmitter. Received type " + typeof emitter);
|
|
434
|
+
}
|
|
435
|
+
})))());
|
|
436
|
+
var getListenName = (event) => `listen_${String(event)}`;
|
|
437
|
+
var EventEmitter = class extends import_events.default {
|
|
438
|
+
emitCallbacks = [];
|
|
439
|
+
constructor(options) {
|
|
440
|
+
super(options);
|
|
441
|
+
}
|
|
442
|
+
emit(type, data, isTriggeredExternally) {
|
|
443
|
+
const params = [type, data];
|
|
444
|
+
if (isTriggeredExternally) params.push(isTriggeredExternally);
|
|
445
|
+
this.emitCallbacks?.forEach((callback) => callback(...params));
|
|
446
|
+
return super.emit(...params);
|
|
447
|
+
}
|
|
448
|
+
onEmit = (callback) => {
|
|
449
|
+
this.emitCallbacks?.push(callback);
|
|
450
|
+
return () => {
|
|
451
|
+
this.emitCallbacks = this.emitCallbacks?.filter((cb) => cb !== callback);
|
|
452
|
+
};
|
|
453
|
+
};
|
|
454
|
+
onListener = (event, listener) => {
|
|
455
|
+
super.on(getListenName(event), listener);
|
|
456
|
+
return () => {
|
|
457
|
+
super.off(getListenName(event), listener);
|
|
458
|
+
};
|
|
459
|
+
};
|
|
460
|
+
on = (event, listener) => {
|
|
461
|
+
super.on(event, listener);
|
|
462
|
+
super.emit(getListenName(event), super.listeners(event).length);
|
|
463
|
+
return this;
|
|
464
|
+
};
|
|
465
|
+
off = (event, listener) => {
|
|
466
|
+
super.off(event, listener);
|
|
467
|
+
super.emit(getListenName(event), super.listeners(event).length);
|
|
468
|
+
return this;
|
|
469
|
+
};
|
|
470
|
+
addListener = this.on;
|
|
471
|
+
removeListener = this.off;
|
|
472
|
+
};
|
|
473
|
+
//#endregion
|
|
474
|
+
//#region src/managers/app/app.manager.ts
|
|
475
|
+
/**
|
|
476
|
+
* App manager handles main application states - focus and online. Those two values can answer questions:
|
|
477
|
+
* - Is the tab or current view instance focused and visible for user?
|
|
478
|
+
* - Is our application online or offline?
|
|
479
|
+
* With the app manager it is not a problem to get the valid answer for this question.
|
|
480
|
+
*
|
|
481
|
+
* @caution
|
|
482
|
+
* Make sure to apply valid focus/online handlers for different environments like for example for native mobile applications.
|
|
483
|
+
*/
|
|
484
|
+
var AppManager = class {
|
|
485
|
+
emitter = new EventEmitter();
|
|
486
|
+
events = getAppManagerEvents(this.emitter);
|
|
487
|
+
isBrowser;
|
|
488
|
+
isOnline;
|
|
489
|
+
isFocused;
|
|
490
|
+
constructor(options) {
|
|
491
|
+
this.options = options;
|
|
492
|
+
this.emitter?.setMaxListeners(1e3);
|
|
493
|
+
const { initiallyFocused = appManagerInitialOptions.initiallyFocused, initiallyOnline = appManagerInitialOptions.initiallyOnline } = this.options || appManagerInitialOptions;
|
|
494
|
+
this.setInitialFocus(initiallyFocused);
|
|
495
|
+
this.setInitialOnline(initiallyOnline);
|
|
496
|
+
this.isBrowser = hasDocument();
|
|
497
|
+
}
|
|
498
|
+
initialize = () => {
|
|
499
|
+
const { focusEvent = appManagerInitialOptions.focusEvent, onlineEvent = appManagerInitialOptions.onlineEvent } = this.options || appManagerInitialOptions;
|
|
500
|
+
focusEvent(this.setFocused);
|
|
501
|
+
onlineEvent(this.setOnline);
|
|
502
|
+
};
|
|
503
|
+
setInitialFocus = async (initValue) => {
|
|
504
|
+
if (typeof initValue === "function") {
|
|
505
|
+
this.isFocused = false;
|
|
506
|
+
this.isFocused = await initValue();
|
|
507
|
+
} else this.isFocused = initValue;
|
|
508
|
+
};
|
|
509
|
+
setInitialOnline = async (initValue) => {
|
|
510
|
+
if (typeof initValue === "function") {
|
|
511
|
+
this.isOnline = false;
|
|
512
|
+
this.isOnline = await initValue();
|
|
513
|
+
} else this.isOnline = initValue;
|
|
514
|
+
};
|
|
515
|
+
setFocused = (isFocused) => {
|
|
516
|
+
this.isFocused = isFocused;
|
|
517
|
+
if (isFocused) this.events.emitFocus();
|
|
518
|
+
else this.events.emitBlur();
|
|
519
|
+
};
|
|
520
|
+
setOnline = (isOnline) => {
|
|
521
|
+
this.isOnline = isOnline;
|
|
522
|
+
if (isOnline) this.events.emitOnline();
|
|
523
|
+
else this.events.emitOffline();
|
|
524
|
+
};
|
|
525
|
+
};
|
|
526
|
+
//#endregion
|
|
527
|
+
//#region src/managers/app/app.manager.utils.ts
|
|
528
|
+
var hasWindow = () => {
|
|
529
|
+
try {
|
|
530
|
+
return Boolean(window && window.addEventListener);
|
|
531
|
+
} catch (err) {
|
|
532
|
+
/* istanbul ignore next */
|
|
533
|
+
return false;
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
var hasDocument = () => {
|
|
537
|
+
try {
|
|
538
|
+
return Boolean(hasWindow() && window.document && window.document.addEventListener);
|
|
539
|
+
} catch (err) {
|
|
540
|
+
/* istanbul ignore next */
|
|
541
|
+
return false;
|
|
542
|
+
}
|
|
543
|
+
};
|
|
544
|
+
var onWindowEvent = (key, listener, options) => {
|
|
545
|
+
/* istanbul ignore next */
|
|
546
|
+
if (hasWindow()) {
|
|
547
|
+
window.addEventListener(key, listener, options);
|
|
548
|
+
return () => window.removeEventListener(key, listener, options);
|
|
549
|
+
}
|
|
550
|
+
/* istanbul ignore next */
|
|
551
|
+
return () => null;
|
|
552
|
+
};
|
|
553
|
+
var onDocumentEvent = (key, listener, options) => {
|
|
554
|
+
/* istanbul ignore next */
|
|
555
|
+
if (hasDocument()) {
|
|
556
|
+
window.document.addEventListener(key, listener, options);
|
|
557
|
+
return () => window.document.removeEventListener(key, listener, options);
|
|
558
|
+
}
|
|
559
|
+
/* istanbul ignore next */
|
|
560
|
+
return () => null;
|
|
561
|
+
};
|
|
562
|
+
//#endregion
|
|
563
|
+
//#region src/managers/app/app.manager.events.ts
|
|
564
|
+
var getAppManagerEvents = (emitter) => ({
|
|
565
|
+
emitFocus: () => {
|
|
566
|
+
emitter.emit(AppEvents.FOCUS);
|
|
567
|
+
},
|
|
568
|
+
emitBlur: () => {
|
|
569
|
+
emitter.emit(AppEvents.BLUR);
|
|
570
|
+
},
|
|
571
|
+
emitOnline: () => {
|
|
572
|
+
emitter.emit(AppEvents.ONLINE);
|
|
573
|
+
},
|
|
574
|
+
emitOffline: () => {
|
|
575
|
+
emitter.emit(AppEvents.OFFLINE);
|
|
576
|
+
},
|
|
577
|
+
onFocus: (callback) => {
|
|
578
|
+
emitter.on(AppEvents.FOCUS, callback);
|
|
579
|
+
return () => emitter.removeListener(AppEvents.FOCUS, callback);
|
|
580
|
+
},
|
|
581
|
+
onBlur: (callback) => {
|
|
582
|
+
emitter.on(AppEvents.BLUR, callback);
|
|
583
|
+
return () => emitter.removeListener(AppEvents.BLUR, callback);
|
|
584
|
+
},
|
|
585
|
+
onOnline: (callback) => {
|
|
586
|
+
emitter.on(AppEvents.ONLINE, callback);
|
|
587
|
+
return () => emitter.removeListener(AppEvents.ONLINE, callback);
|
|
588
|
+
},
|
|
589
|
+
onOffline: (callback) => {
|
|
590
|
+
emitter.on(AppEvents.OFFLINE, callback);
|
|
591
|
+
return () => emitter.removeListener(AppEvents.OFFLINE, callback);
|
|
592
|
+
}
|
|
593
|
+
});
|
|
594
|
+
//#endregion
|
|
595
|
+
//#region src/managers/app/app.manager.constants.ts
|
|
596
|
+
var AppEvents = /* @__PURE__ */ function(AppEvents) {
|
|
597
|
+
AppEvents["FOCUS"] = "focus";
|
|
598
|
+
AppEvents["BLUR"] = "blur";
|
|
599
|
+
AppEvents["ONLINE"] = "online";
|
|
600
|
+
AppEvents["OFFLINE"] = "offline";
|
|
601
|
+
return AppEvents;
|
|
602
|
+
}({});
|
|
603
|
+
var appManagerInitialOptions = {
|
|
604
|
+
initiallyFocused: true,
|
|
605
|
+
initiallyOnline: true,
|
|
606
|
+
focusEvent: (setFocused) => {
|
|
607
|
+
onDocumentEvent("visibilitychange", () => setFocused(true));
|
|
608
|
+
onWindowEvent("focus", () => setFocused(true));
|
|
609
|
+
onWindowEvent("blur", () => setFocused(false));
|
|
610
|
+
},
|
|
611
|
+
onlineEvent: (setOnline) => {
|
|
612
|
+
onWindowEvent("online", () => setOnline(true));
|
|
613
|
+
onWindowEvent("offline", () => setOnline(false));
|
|
614
|
+
}
|
|
615
|
+
};
|
|
616
|
+
//#endregion
|
|
617
|
+
//#region src/managers/request/request.manager.ts
|
|
618
|
+
/**
|
|
619
|
+
* **Request Manager** is used to emit `request lifecycle events` like - request start, request end, upload and download progress.
|
|
620
|
+
* It is also the place of `request aborting` system, here we store all the keys and controllers that are isolated for each client instance.
|
|
621
|
+
*/
|
|
622
|
+
var RequestManager = class {
|
|
623
|
+
emitter = new EventEmitter();
|
|
624
|
+
events = getRequestManagerEvents(this.emitter);
|
|
625
|
+
constructor() {
|
|
626
|
+
this.emitter?.setMaxListeners(1e3);
|
|
627
|
+
}
|
|
628
|
+
abortControllers = /* @__PURE__ */ new Map();
|
|
629
|
+
addAbortController = (abortKey, requestId) => {
|
|
630
|
+
let abortGroup = this.abortControllers.get(abortKey);
|
|
631
|
+
if (!abortGroup) {
|
|
632
|
+
const newAbortGroup = /* @__PURE__ */ new Map();
|
|
633
|
+
abortGroup = newAbortGroup;
|
|
634
|
+
this.abortControllers.set(abortKey, newAbortGroup);
|
|
635
|
+
}
|
|
636
|
+
const abortController = abortGroup.get(requestId);
|
|
637
|
+
if (!abortController || abortController.signal.aborted) abortGroup.set(requestId, new AbortController());
|
|
638
|
+
};
|
|
639
|
+
getAbortController = (abortKey, requestId) => {
|
|
640
|
+
return this.abortControllers.get(abortKey)?.get(requestId);
|
|
641
|
+
};
|
|
642
|
+
removeAbortController = (abortKey, requestId) => {
|
|
643
|
+
this.abortControllers.get(abortKey)?.delete(requestId);
|
|
644
|
+
};
|
|
645
|
+
useAbortController = (abortKey, requestId) => {
|
|
646
|
+
(this.abortControllers.get(abortKey)?.get(requestId))?.abort();
|
|
647
|
+
};
|
|
648
|
+
abortByKey = (abortKey) => {
|
|
649
|
+
const controllers = this.abortControllers.get(abortKey);
|
|
650
|
+
if (controllers) Array.from(controllers.entries()).forEach(([key]) => {
|
|
651
|
+
this.useAbortController(abortKey, key);
|
|
652
|
+
});
|
|
653
|
+
};
|
|
654
|
+
abortByRequestId = (abortKey, requestId) => {
|
|
655
|
+
this.useAbortController(abortKey, requestId);
|
|
656
|
+
};
|
|
657
|
+
abortAll = () => {
|
|
658
|
+
Array.from(this.abortControllers.entries()).forEach(([abortKey, value]) => {
|
|
659
|
+
Array.from(value.entries()).forEach(([requestId]) => {
|
|
660
|
+
this.useAbortController(abortKey, requestId);
|
|
661
|
+
});
|
|
662
|
+
});
|
|
663
|
+
};
|
|
664
|
+
};
|
|
665
|
+
//#endregion
|
|
666
|
+
//#region src/managers/request/request.manager.utils.ts
|
|
667
|
+
var getLoadingKey = () => `loading-event-any`;
|
|
668
|
+
var getLoadingByQueryKey = (queryKey) => `${queryKey}-loading-event`;
|
|
669
|
+
var getLoadingByCacheKey = (cacheKey) => `${cacheKey}-loading-cache-event`;
|
|
670
|
+
var getLoadingByIdKey = (id) => `${id}-loading-event-by-id`;
|
|
671
|
+
var getRemoveKey = () => `remove-event-any`;
|
|
672
|
+
var getRemoveByQueryKey = (queryKey) => `${queryKey}-remove-event`;
|
|
673
|
+
var getRemoveByIdKey = (id) => `${id}-remove-event-by-id`;
|
|
674
|
+
var getAbortKey = () => `request-abort-any`;
|
|
675
|
+
var getAbortByAbortKey = (abortKey) => `${abortKey}-request-abort`;
|
|
676
|
+
var getAbortByIdKey = (id) => `${id}-request-abort-by-id`;
|
|
677
|
+
var getResponseKey = () => `response-any`;
|
|
678
|
+
var getResponseByCacheKey = (cacheKey) => `${cacheKey}-response`;
|
|
679
|
+
var getResponseByIdKey = (id) => `${id}-response-by-id`;
|
|
680
|
+
var getRequestStartKey = () => `request-start-any`;
|
|
681
|
+
var getRequestStarByQueryKey = (queryKey) => `${queryKey}-request-start`;
|
|
682
|
+
var getRequestStartByIdKey = (id) => `${id}-request-start-by-id`;
|
|
683
|
+
var getResponseStartKey = () => `response-start-any`;
|
|
684
|
+
var getResponseStartByQueryKey = (queryKey) => `${queryKey}-response-start`;
|
|
685
|
+
var getResponseStartByIdKey = (id) => `${id}-response-start-by-id`;
|
|
686
|
+
var getUploadProgressKey = () => `request-progress-any`;
|
|
687
|
+
var getUploadProgressByQueryKey = (queryKey) => `${queryKey}-request-progress`;
|
|
688
|
+
var getUploadProgressByIdKey = (id) => `${id}-request-progress-by-id`;
|
|
689
|
+
var getDownloadProgressKey = () => `response-progress-any`;
|
|
690
|
+
var getDownloadProgressByQueryKey = (queryKey) => `${queryKey}-response-progress`;
|
|
691
|
+
var getDownloadProgressByIdKey = (id) => `${id}-response-progress-by-id`;
|
|
692
|
+
var getRequestDeduplicatedKey = () => `request-deduplicated-any`;
|
|
693
|
+
var getRequestDeduplicatedByQueryKey = (queryKey) => `${queryKey}-query-request-deduplicated`;
|
|
694
|
+
var getRequestDeduplicatedByCacheKey = (cacheKey) => `${cacheKey}-cache-request-deduplicated`;
|
|
695
|
+
var getRequestDeduplicatedByIdKey = (id) => `${id}-request-deduplicated-by-id`;
|
|
696
|
+
//#endregion
|
|
697
|
+
//#region src/managers/request/request.manager.events.ts
|
|
698
|
+
var getRequestManagerEvents = (emitter) => ({
|
|
699
|
+
emitDeduplicated: (data, isTriggeredExternally = false) => {
|
|
700
|
+
emitter.emit(getRequestDeduplicatedKey(), data, isTriggeredExternally);
|
|
701
|
+
emitter.emit(getRequestDeduplicatedByIdKey(data.requestId), data, isTriggeredExternally);
|
|
702
|
+
emitter.emit(getRequestDeduplicatedByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
|
|
703
|
+
emitter.emit(getRequestDeduplicatedByQueryKey(data.request.queryKey), data, isTriggeredExternally);
|
|
704
|
+
},
|
|
705
|
+
emitLoading: (data, isTriggeredExternally = false) => {
|
|
706
|
+
emitter.emit(getLoadingKey(), data, isTriggeredExternally);
|
|
707
|
+
emitter.emit(getLoadingByIdKey(data.requestId), data, isTriggeredExternally);
|
|
708
|
+
emitter.emit(getLoadingByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
|
|
709
|
+
emitter.emit(getLoadingByQueryKey(data.request.queryKey), data, isTriggeredExternally);
|
|
710
|
+
},
|
|
711
|
+
emitRequestStart: (data, isTriggeredExternally = false) => {
|
|
712
|
+
emitter.emit(getRequestStartKey(), data, isTriggeredExternally);
|
|
713
|
+
emitter.emit(getRequestStartByIdKey(data.requestId), data, isTriggeredExternally);
|
|
714
|
+
emitter.emit(getRequestStarByQueryKey(data.request.queryKey), data, isTriggeredExternally);
|
|
715
|
+
},
|
|
716
|
+
emitResponseStart: (data, isTriggeredExternally = false) => {
|
|
717
|
+
emitter.emit(getResponseStartKey(), data, isTriggeredExternally);
|
|
718
|
+
emitter.emit(getResponseStartByIdKey(data.requestId), data, isTriggeredExternally);
|
|
719
|
+
emitter.emit(getResponseStartByQueryKey(data.request.queryKey), data, isTriggeredExternally);
|
|
720
|
+
},
|
|
721
|
+
emitUploadProgress: (data, isTriggeredExternally = false) => {
|
|
722
|
+
emitter.emit(getUploadProgressKey(), data, isTriggeredExternally);
|
|
723
|
+
emitter.emit(getUploadProgressByIdKey(data.requestId), data, isTriggeredExternally);
|
|
724
|
+
emitter.emit(getUploadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);
|
|
725
|
+
},
|
|
726
|
+
emitDownloadProgress: (data, isTriggeredExternally = false) => {
|
|
727
|
+
emitter.emit(getDownloadProgressKey(), data, isTriggeredExternally);
|
|
728
|
+
emitter.emit(getDownloadProgressByIdKey(data.requestId), data, isTriggeredExternally);
|
|
729
|
+
emitter.emit(getDownloadProgressByQueryKey(data.request.queryKey), data, isTriggeredExternally);
|
|
730
|
+
},
|
|
731
|
+
emitResponse: (data, isTriggeredExternally = false) => {
|
|
732
|
+
emitter.emit(getResponseKey(), data, isTriggeredExternally);
|
|
733
|
+
emitter.emit(getResponseByIdKey(data.requestId), data, isTriggeredExternally);
|
|
734
|
+
emitter.emit(getResponseByCacheKey(data.request.cacheKey), data, isTriggeredExternally);
|
|
735
|
+
},
|
|
736
|
+
emitAbort: (data, isTriggeredExternally = false) => {
|
|
737
|
+
emitter.emit(getAbortKey(), data, isTriggeredExternally);
|
|
738
|
+
emitter.emit(getAbortByIdKey(data.requestId), data, isTriggeredExternally);
|
|
739
|
+
emitter.emit(getAbortByAbortKey(data.request.abortKey), data, isTriggeredExternally);
|
|
740
|
+
},
|
|
741
|
+
emitRemove: (data, isTriggeredExternally = false) => {
|
|
742
|
+
emitter.emit(getRemoveKey(), data, isTriggeredExternally);
|
|
743
|
+
emitter.emit(getRemoveByIdKey(data.requestId), data, isTriggeredExternally);
|
|
744
|
+
emitter.emit(getRemoveByQueryKey(data.request.queryKey), data, isTriggeredExternally);
|
|
745
|
+
},
|
|
746
|
+
onDeduplicated: (callback) => {
|
|
747
|
+
emitter.on(getRequestDeduplicatedKey(), callback);
|
|
748
|
+
return () => emitter.removeListener(getRequestDeduplicatedKey(), callback);
|
|
749
|
+
},
|
|
750
|
+
onDeduplicatedByQueue: (queryKey, callback) => {
|
|
751
|
+
emitter.on(getRequestDeduplicatedByQueryKey(queryKey), callback);
|
|
752
|
+
return () => emitter.removeListener(getRequestDeduplicatedByQueryKey(queryKey), callback);
|
|
753
|
+
},
|
|
754
|
+
onDeduplicatedByCache: (cacheKey, callback) => {
|
|
755
|
+
emitter.on(getRequestDeduplicatedByCacheKey(cacheKey), callback);
|
|
756
|
+
return () => emitter.removeListener(getRequestDeduplicatedByCacheKey(cacheKey), callback);
|
|
757
|
+
},
|
|
758
|
+
onDeduplicatedById: (requestId, callback) => {
|
|
759
|
+
emitter.on(getRequestDeduplicatedByIdKey(requestId), callback);
|
|
760
|
+
return () => emitter.removeListener(getRequestDeduplicatedByIdKey(requestId), callback);
|
|
761
|
+
},
|
|
762
|
+
onLoading: (callback) => {
|
|
763
|
+
emitter.on(getLoadingKey(), callback);
|
|
764
|
+
return () => emitter.removeListener(getLoadingKey(), callback);
|
|
765
|
+
},
|
|
766
|
+
onLoadingByQueue: (queryKey, callback) => {
|
|
767
|
+
emitter.on(getLoadingByQueryKey(queryKey), callback);
|
|
768
|
+
return () => emitter.removeListener(getLoadingByQueryKey(queryKey), callback);
|
|
769
|
+
},
|
|
770
|
+
onLoadingByCache: (cacheKey, callback) => {
|
|
771
|
+
emitter.on(getLoadingByCacheKey(cacheKey), callback);
|
|
772
|
+
return () => emitter.removeListener(getLoadingByCacheKey(cacheKey), callback);
|
|
773
|
+
},
|
|
774
|
+
onLoadingById: (requestId, callback) => {
|
|
775
|
+
emitter.on(getLoadingByIdKey(requestId), callback);
|
|
776
|
+
return () => emitter.removeListener(getLoadingByIdKey(requestId), callback);
|
|
777
|
+
},
|
|
778
|
+
onRequestStart: (callback) => {
|
|
779
|
+
emitter.on(getRequestStartKey(), callback);
|
|
780
|
+
return () => emitter.removeListener(getRequestStartKey(), callback);
|
|
781
|
+
},
|
|
782
|
+
onRequestStartByQueue: (queryKey, callback) => {
|
|
783
|
+
emitter.on(getRequestStarByQueryKey(queryKey), callback);
|
|
784
|
+
return () => emitter.removeListener(getRequestStarByQueryKey(queryKey), callback);
|
|
785
|
+
},
|
|
786
|
+
onRequestStartById: (requestId, callback) => {
|
|
787
|
+
emitter.on(getRequestStartByIdKey(requestId), callback);
|
|
788
|
+
return () => emitter.removeListener(getRequestStartByIdKey(requestId), callback);
|
|
789
|
+
},
|
|
790
|
+
onResponseStart: (callback) => {
|
|
791
|
+
emitter.on(getResponseStartKey(), callback);
|
|
792
|
+
return () => emitter.removeListener(getResponseStartKey(), callback);
|
|
793
|
+
},
|
|
794
|
+
onResponseStartByQueue: (queryKey, callback) => {
|
|
795
|
+
emitter.on(getResponseStartByQueryKey(queryKey), callback);
|
|
796
|
+
return () => emitter.removeListener(getResponseStartByQueryKey(queryKey), callback);
|
|
797
|
+
},
|
|
798
|
+
onResponseStartById: (requestId, callback) => {
|
|
799
|
+
emitter.on(getResponseStartByIdKey(requestId), callback);
|
|
800
|
+
return () => emitter.removeListener(getResponseStartByIdKey(requestId), callback);
|
|
801
|
+
},
|
|
802
|
+
onUploadProgress: (callback) => {
|
|
803
|
+
emitter.on(getUploadProgressKey(), callback);
|
|
804
|
+
return () => emitter.removeListener(getUploadProgressKey(), callback);
|
|
805
|
+
},
|
|
806
|
+
onUploadProgressByQueue: (queryKey, callback) => {
|
|
807
|
+
emitter.on(getUploadProgressByQueryKey(queryKey), callback);
|
|
808
|
+
return () => emitter.removeListener(getUploadProgressByQueryKey(queryKey), callback);
|
|
809
|
+
},
|
|
810
|
+
onUploadProgressById: (requestId, callback) => {
|
|
811
|
+
emitter.on(getUploadProgressByIdKey(requestId), callback);
|
|
812
|
+
return () => emitter.removeListener(getUploadProgressByIdKey(requestId), callback);
|
|
813
|
+
},
|
|
814
|
+
onDownloadProgress: (callback) => {
|
|
815
|
+
emitter.on(getDownloadProgressKey(), callback);
|
|
816
|
+
return () => emitter.removeListener(getDownloadProgressKey(), callback);
|
|
817
|
+
},
|
|
818
|
+
onDownloadProgressByQueue: (queryKey, callback) => {
|
|
819
|
+
emitter.on(getDownloadProgressByQueryKey(queryKey), callback);
|
|
820
|
+
return () => emitter.removeListener(getDownloadProgressByQueryKey(queryKey), callback);
|
|
821
|
+
},
|
|
822
|
+
onDownloadProgressById: (requestId, callback) => {
|
|
823
|
+
emitter.on(getDownloadProgressByIdKey(requestId), callback);
|
|
824
|
+
return () => emitter.removeListener(getDownloadProgressByIdKey(requestId), callback);
|
|
825
|
+
},
|
|
826
|
+
onResponse: (callback) => {
|
|
827
|
+
emitter.on(getResponseKey(), callback);
|
|
828
|
+
return () => emitter.removeListener(getResponseKey(), callback);
|
|
829
|
+
},
|
|
830
|
+
onResponseByCache: (cacheKey, callback) => {
|
|
831
|
+
emitter.on(getResponseByCacheKey(cacheKey), callback);
|
|
832
|
+
return () => emitter.removeListener(getResponseByCacheKey(cacheKey), callback);
|
|
833
|
+
},
|
|
834
|
+
onResponseById: (requestId, callback) => {
|
|
835
|
+
emitter.on(getResponseByIdKey(requestId), callback);
|
|
836
|
+
return () => emitter.removeListener(getResponseByIdKey(requestId), callback);
|
|
837
|
+
},
|
|
838
|
+
onAbort: (callback) => {
|
|
839
|
+
emitter.on(getAbortKey(), callback);
|
|
840
|
+
return () => emitter.removeListener(getAbortKey(), callback);
|
|
841
|
+
},
|
|
842
|
+
onAbortByKey: (abortKey, callback) => {
|
|
843
|
+
emitter.on(getAbortByAbortKey(abortKey), callback);
|
|
844
|
+
return () => emitter.removeListener(getAbortByAbortKey(abortKey), callback);
|
|
845
|
+
},
|
|
846
|
+
onAbortById: (requestId, callback) => {
|
|
847
|
+
emitter.on(getAbortByIdKey(requestId), callback);
|
|
848
|
+
return () => emitter.removeListener(getAbortByIdKey(requestId), callback);
|
|
849
|
+
},
|
|
850
|
+
onRemove: (callback) => {
|
|
851
|
+
emitter.on(getRemoveKey(), callback);
|
|
852
|
+
return () => emitter.removeListener(getRemoveKey(), callback);
|
|
853
|
+
},
|
|
854
|
+
onRemoveByQueue: (queryKey, callback) => {
|
|
855
|
+
emitter.on(getRemoveByQueryKey(queryKey), callback);
|
|
856
|
+
return () => emitter.removeListener(getRemoveByQueryKey(queryKey), callback);
|
|
857
|
+
},
|
|
858
|
+
onRemoveById: (requestId, callback) => {
|
|
859
|
+
emitter.on(getRemoveByIdKey(requestId), callback);
|
|
860
|
+
return () => emitter.removeListener(getRemoveByIdKey(requestId), callback);
|
|
861
|
+
}
|
|
862
|
+
});
|
|
863
|
+
//#endregion
|
|
864
|
+
//#region src/managers/logger/logger.manager.ts
|
|
865
|
+
/**
|
|
866
|
+
* This class is used across the Hyper Fetch library to provide unified logging system with necessary setup per each client.
|
|
867
|
+
* We can set up the logging level based on available values. This manager enable to initialize the logging instance per individual module
|
|
868
|
+
* like Client, Request etc. Which can give you better feedback on the logging itself.
|
|
869
|
+
*/
|
|
870
|
+
var LoggerManager = class {
|
|
871
|
+
logger;
|
|
872
|
+
level;
|
|
873
|
+
modules;
|
|
874
|
+
emitter = new import_events.default();
|
|
875
|
+
client;
|
|
876
|
+
constructor(options) {
|
|
877
|
+
this.options = options;
|
|
878
|
+
this.emitter?.setMaxListeners(1e3);
|
|
879
|
+
this.logger = this.options?.logger || logger;
|
|
880
|
+
this.level = this.options?.level || "warning";
|
|
881
|
+
this.modules = this.options?.modules;
|
|
882
|
+
}
|
|
883
|
+
setSeverity = (level) => {
|
|
884
|
+
this.level = level;
|
|
885
|
+
};
|
|
886
|
+
setModules = (modules) => {
|
|
887
|
+
this.modules = modules;
|
|
888
|
+
};
|
|
889
|
+
initialize = (client, module) => {
|
|
890
|
+
this.client = client;
|
|
891
|
+
return {
|
|
892
|
+
error: (data) => this.log({
|
|
893
|
+
...data,
|
|
894
|
+
level: "error",
|
|
895
|
+
module
|
|
896
|
+
}),
|
|
897
|
+
warning: (data) => this.log({
|
|
898
|
+
...data,
|
|
899
|
+
level: "warning",
|
|
900
|
+
module
|
|
901
|
+
}),
|
|
902
|
+
info: (data) => this.log({
|
|
903
|
+
...data,
|
|
904
|
+
level: "info",
|
|
905
|
+
module
|
|
906
|
+
}),
|
|
907
|
+
debug: (data) => this.log({
|
|
908
|
+
...data,
|
|
909
|
+
level: "debug",
|
|
910
|
+
module
|
|
911
|
+
})
|
|
912
|
+
};
|
|
913
|
+
};
|
|
914
|
+
log = (data) => {
|
|
915
|
+
if (!this.client.debug) return;
|
|
916
|
+
if (logLevelOrder.indexOf(this.level) <= logLevelOrder.indexOf(data.level)) return;
|
|
917
|
+
if (this.modules && !this.modules.includes(data.module)) return;
|
|
918
|
+
this.logger(data);
|
|
919
|
+
};
|
|
920
|
+
};
|
|
921
|
+
//#endregion
|
|
922
|
+
//#region src/managers/logger/logger.manager.utils.ts
|
|
923
|
+
var getTime = () => {
|
|
924
|
+
return `${(/* @__PURE__ */ new Date()).toLocaleTimeString()}`;
|
|
925
|
+
};
|
|
926
|
+
var getModuleName = (data) => {
|
|
927
|
+
if (data.type === "request" || data.type === "response") return `${data.extra.request.endpoint}`;
|
|
928
|
+
return `[${data.module}]`;
|
|
929
|
+
};
|
|
930
|
+
var logger = (log) => {
|
|
931
|
+
const styles = loggerStyles[log.level];
|
|
932
|
+
const color = loggerColors[log.level];
|
|
933
|
+
const message = `%c[${getTime()}]%c${log.title}%c${getModuleName(log)}`;
|
|
934
|
+
const style1 = `${styles}${color}font-weight:600;border-radius: 4px 0 0 4px;`;
|
|
935
|
+
const style2 = `${styles}${color}font-weight:600;`;
|
|
936
|
+
const style3 = `${styles}font-weight:normal;border-radius: 0 4px 4px 0;`;
|
|
937
|
+
if (log.extra ? Object.keys(log.extra)?.length : false) {
|
|
938
|
+
console.groupCollapsed(message, style1, style2, style3);
|
|
939
|
+
console.log(log.extra);
|
|
940
|
+
console.groupEnd();
|
|
941
|
+
} else console.log(message, styles);
|
|
942
|
+
};
|
|
943
|
+
//#endregion
|
|
944
|
+
//#region src/managers/logger/logger.manager.constants.ts
|
|
945
|
+
var logLevelOrder = [
|
|
946
|
+
"error",
|
|
947
|
+
"warning",
|
|
948
|
+
"info",
|
|
949
|
+
"debug"
|
|
950
|
+
];
|
|
951
|
+
var defaultStyles = "padding:2px 5px;";
|
|
952
|
+
var loggerStyles = {
|
|
953
|
+
error: `${defaultStyles};background:#db252520;`,
|
|
954
|
+
warning: `${defaultStyles};background:#e1941e20;`,
|
|
955
|
+
info: `${defaultStyles};background:#1e74e120;`,
|
|
956
|
+
debug: `${defaultStyles};background:#00000020;`
|
|
957
|
+
};
|
|
958
|
+
var loggerColors = {
|
|
959
|
+
error: "color:#ff3737;",
|
|
960
|
+
warning: "color:#ffc107;",
|
|
961
|
+
info: "color:#34a8ff;",
|
|
962
|
+
debug: "color:#cccccc;"
|
|
963
|
+
};
|
|
964
|
+
//#endregion
|
|
965
|
+
//#region src/adapter/adapter.utils.ts
|
|
966
|
+
var TimeoutError = class extends Error {
|
|
967
|
+
constructor() {
|
|
968
|
+
super("Request timeout");
|
|
969
|
+
this.name = "TimeoutError";
|
|
970
|
+
}
|
|
971
|
+
};
|
|
972
|
+
var AbortError = class extends Error {
|
|
973
|
+
constructor() {
|
|
974
|
+
super("Request aborted");
|
|
975
|
+
this.name = "AbortError";
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
var DeletedError = class extends Error {
|
|
979
|
+
constructor() {
|
|
980
|
+
super("Request deleted");
|
|
981
|
+
this.name = "DeletedError";
|
|
982
|
+
}
|
|
983
|
+
};
|
|
984
|
+
var RequestProcessingError = class extends Error {
|
|
985
|
+
description;
|
|
986
|
+
constructor(description) {
|
|
987
|
+
super("Request processing error");
|
|
988
|
+
this.description = description;
|
|
989
|
+
this.name = "RequestProcessingError";
|
|
990
|
+
}
|
|
991
|
+
};
|
|
992
|
+
var UnexpectedError = class extends Error {
|
|
993
|
+
description;
|
|
994
|
+
constructor(description) {
|
|
995
|
+
super("Unexpected error");
|
|
996
|
+
this.description = description;
|
|
997
|
+
this.name = "UnexpectedError";
|
|
998
|
+
}
|
|
999
|
+
};
|
|
1000
|
+
var getErrorMessage = (errorCase) => {
|
|
1001
|
+
if (errorCase === "timeout") return new TimeoutError();
|
|
1002
|
+
if (errorCase === "abort") return new AbortError();
|
|
1003
|
+
if (errorCase === "deleted") return new DeletedError();
|
|
1004
|
+
if (errorCase === "processing") return new RequestProcessingError();
|
|
1005
|
+
return new UnexpectedError();
|
|
1006
|
+
};
|
|
1007
|
+
var stringifyValue = (response) => {
|
|
1008
|
+
try {
|
|
1009
|
+
return JSON.stringify(response);
|
|
1010
|
+
} catch (err) {
|
|
1011
|
+
return "";
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
1014
|
+
var getAdapterHeaders = (request) => {
|
|
1015
|
+
const isFormData = hasWindow() && request.payload instanceof FormData;
|
|
1016
|
+
const isObject = typeof request.payload === "object" && request.payload !== null;
|
|
1017
|
+
const headers = {};
|
|
1018
|
+
if (!isFormData && isObject) headers["Content-Type"] = "application/json";
|
|
1019
|
+
Object.assign(headers, request.headers);
|
|
1020
|
+
return headers;
|
|
1021
|
+
};
|
|
1022
|
+
var getAdapterPayload = (data) => {
|
|
1023
|
+
if (hasWindow() && data instanceof FormData) return data;
|
|
1024
|
+
return stringifyValue(data);
|
|
1025
|
+
};
|
|
1026
|
+
//#endregion
|
|
1027
|
+
//#region src/request/request.hooks.ts
|
|
1028
|
+
var HOOK_NAMES = [
|
|
1029
|
+
"onBeforeSent",
|
|
1030
|
+
"onRequestStart",
|
|
1031
|
+
"onResponseStart",
|
|
1032
|
+
"onUploadProgress",
|
|
1033
|
+
"onDownloadProgress",
|
|
1034
|
+
"onResponse",
|
|
1035
|
+
"onRemove"
|
|
1036
|
+
];
|
|
1037
|
+
function createRequestHooks(initial) {
|
|
1038
|
+
const listeners = {
|
|
1039
|
+
onBeforeSent: [],
|
|
1040
|
+
onRequestStart: [],
|
|
1041
|
+
onResponseStart: [],
|
|
1042
|
+
onUploadProgress: [],
|
|
1043
|
+
onDownloadProgress: [],
|
|
1044
|
+
onResponse: [],
|
|
1045
|
+
onRemove: []
|
|
1046
|
+
};
|
|
1047
|
+
if (initial) HOOK_NAMES.forEach((name) => {
|
|
1048
|
+
listeners[name] = [...initial[name]];
|
|
1049
|
+
});
|
|
1050
|
+
const subscribe = (name) => {
|
|
1051
|
+
return (cb) => {
|
|
1052
|
+
listeners[name].push(cb);
|
|
1053
|
+
return () => {
|
|
1054
|
+
const idx = listeners[name].indexOf(cb);
|
|
1055
|
+
if (idx !== -1) listeners[name].splice(idx, 1);
|
|
1056
|
+
};
|
|
1057
|
+
};
|
|
1058
|
+
};
|
|
1059
|
+
return {
|
|
1060
|
+
onBeforeSent: subscribe("onBeforeSent"),
|
|
1061
|
+
onRequestStart: subscribe("onRequestStart"),
|
|
1062
|
+
onResponseStart: subscribe("onResponseStart"),
|
|
1063
|
+
onUploadProgress: subscribe("onUploadProgress"),
|
|
1064
|
+
onDownloadProgress: subscribe("onDownloadProgress"),
|
|
1065
|
+
onResponse: subscribe("onResponse"),
|
|
1066
|
+
onRemove: subscribe("onRemove"),
|
|
1067
|
+
__emit(name, data) {
|
|
1068
|
+
listeners[name].forEach((cb) => {
|
|
1069
|
+
cb(data);
|
|
1070
|
+
});
|
|
1071
|
+
},
|
|
1072
|
+
__snapshot() {
|
|
1073
|
+
const snap = {};
|
|
1074
|
+
HOOK_NAMES.forEach((name) => {
|
|
1075
|
+
snap[name] = [...listeners[name]];
|
|
1076
|
+
});
|
|
1077
|
+
return snap;
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
//#endregion
|
|
1082
|
+
//#region src/constants/http.constants.ts
|
|
1083
|
+
var HttpMethods = /* @__PURE__ */ function(HttpMethods) {
|
|
1084
|
+
HttpMethods["GET"] = "GET";
|
|
1085
|
+
HttpMethods["POST"] = "POST";
|
|
1086
|
+
HttpMethods["PUT"] = "PUT";
|
|
1087
|
+
HttpMethods["PATCH"] = "PATCH";
|
|
1088
|
+
HttpMethods["DELETE"] = "DELETE";
|
|
1089
|
+
return HttpMethods;
|
|
1090
|
+
}({});
|
|
1091
|
+
//#endregion
|
|
1092
|
+
//#region src/request/request.utils.ts
|
|
1093
|
+
var scopeKey = (key, scope) => {
|
|
1094
|
+
return scope ? `${scope}__${key}` : key;
|
|
1095
|
+
};
|
|
1096
|
+
var stringifyKey = (value) => {
|
|
1097
|
+
try {
|
|
1098
|
+
if (typeof value === "string") return value;
|
|
1099
|
+
if (value === void 0 || value === null) return "";
|
|
1100
|
+
const data = JSON.stringify(value);
|
|
1101
|
+
if (typeof data !== "string") throw new Error();
|
|
1102
|
+
return data;
|
|
1103
|
+
} catch (_) {
|
|
1104
|
+
return "";
|
|
1105
|
+
}
|
|
1106
|
+
};
|
|
1107
|
+
var getProgressValue = ({ loaded, total }) => {
|
|
1108
|
+
if (!loaded || !total) return 0;
|
|
1109
|
+
return Number((loaded * 100 / total).toFixed(0));
|
|
1110
|
+
};
|
|
1111
|
+
var getRequestEta = (startDate, progressDate, { total, loaded }) => {
|
|
1112
|
+
const uploadSpeed = loaded / (+progressDate - +startDate || 1);
|
|
1113
|
+
const totalValue = Math.max(total, loaded);
|
|
1114
|
+
const sizeLeft = totalValue - loaded;
|
|
1115
|
+
const estimatedTimeValue = uploadSpeed ? sizeLeft / uploadSpeed : null;
|
|
1116
|
+
return {
|
|
1117
|
+
timeLeft: totalValue === loaded ? 0 : estimatedTimeValue,
|
|
1118
|
+
sizeLeft
|
|
1119
|
+
};
|
|
1120
|
+
};
|
|
1121
|
+
var getProgressData = (requestStartTime, progressDate, progressEvent) => {
|
|
1122
|
+
const { total, loaded } = progressEvent;
|
|
1123
|
+
if (Number.isNaN(total) || Number.isNaN(loaded)) return {
|
|
1124
|
+
progress: 0,
|
|
1125
|
+
timeLeft: 0,
|
|
1126
|
+
sizeLeft: 0,
|
|
1127
|
+
total: 0,
|
|
1128
|
+
loaded: 0,
|
|
1129
|
+
startTimestamp: +requestStartTime
|
|
1130
|
+
};
|
|
1131
|
+
const { timeLeft, sizeLeft } = getRequestEta(requestStartTime, progressDate, progressEvent);
|
|
1132
|
+
return {
|
|
1133
|
+
progress: getProgressValue(progressEvent),
|
|
1134
|
+
timeLeft,
|
|
1135
|
+
sizeLeft,
|
|
1136
|
+
total,
|
|
1137
|
+
loaded,
|
|
1138
|
+
startTimestamp: +requestStartTime
|
|
1139
|
+
};
|
|
1140
|
+
};
|
|
1141
|
+
var getSimpleKey = (request) => {
|
|
1142
|
+
return `${request.method}_${request.requestOptions.endpoint}_${request.cancelable}`;
|
|
1143
|
+
};
|
|
1144
|
+
/**
|
|
1145
|
+
* Cache instance for individual request that collects individual requests responses from
|
|
1146
|
+
* the same endpoint (they may differ base on the custom key, endpoint params etc)
|
|
1147
|
+
* @param request
|
|
1148
|
+
* @param useInitialValues
|
|
1149
|
+
* @returns
|
|
1150
|
+
*/
|
|
1151
|
+
var getRequestKey = (request, useInitialValues) => {
|
|
1152
|
+
return `${stringifyKey(request.method)}_${useInitialValues ? request.requestOptions.endpoint : stringifyKey(request.endpoint)}_${useInitialValues ? "" : stringifyKey(request.queryParams)}`;
|
|
1153
|
+
};
|
|
1154
|
+
var getRequestDispatcher = (request, dispatcherType = "auto") => {
|
|
1155
|
+
const { fetchDispatcher, submitDispatcher } = request.client;
|
|
1156
|
+
const isGet = request.method === HttpMethods.GET;
|
|
1157
|
+
const isFetchDispatcher = dispatcherType === "auto" && isGet || dispatcherType === "fetch";
|
|
1158
|
+
return [isFetchDispatcher ? fetchDispatcher : submitDispatcher, isFetchDispatcher];
|
|
1159
|
+
};
|
|
1160
|
+
var mapResponseForSend = async (request, response) => {
|
|
1161
|
+
const mapping = request.unstable_responseMapper?.(response);
|
|
1162
|
+
if (mapping instanceof Promise) return await mapping;
|
|
1163
|
+
return mapping || response;
|
|
1164
|
+
};
|
|
1165
|
+
var sendRequest = async (request, options) => {
|
|
1166
|
+
const { client } = request;
|
|
1167
|
+
const { requestManager } = client;
|
|
1168
|
+
const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
|
|
1169
|
+
let mutationContext;
|
|
1170
|
+
if (request.optimistic) try {
|
|
1171
|
+
mutationContext = await request.optimistic({
|
|
1172
|
+
request,
|
|
1173
|
+
client: request.client,
|
|
1174
|
+
payload: request.payload
|
|
1175
|
+
});
|
|
1176
|
+
} catch (err) {
|
|
1177
|
+
return {
|
|
1178
|
+
data: null,
|
|
1179
|
+
error: /* @__PURE__ */ new Error(`Optimistic callback failed: ${err instanceof Error ? err.message : err}`),
|
|
1180
|
+
status: null,
|
|
1181
|
+
success: false,
|
|
1182
|
+
extra: client.adapter.defaultExtra,
|
|
1183
|
+
requestTimestamp: +/* @__PURE__ */ new Date(),
|
|
1184
|
+
responseTimestamp: +/* @__PURE__ */ new Date()
|
|
1185
|
+
};
|
|
1186
|
+
}
|
|
1187
|
+
return new Promise((resolve) => {
|
|
1188
|
+
let isResolved = false;
|
|
1189
|
+
const requestId = dispatcher.add(request);
|
|
1190
|
+
const { $hooks } = request;
|
|
1191
|
+
const beforeSentData = {
|
|
1192
|
+
requestId,
|
|
1193
|
+
request,
|
|
1194
|
+
mutationContext
|
|
1195
|
+
};
|
|
1196
|
+
options?.onBeforeSent?.(beforeSentData);
|
|
1197
|
+
$hooks.__emit("onBeforeSent", beforeSentData);
|
|
1198
|
+
const unmountRequestStart = requestManager.events.onRequestStartById(requestId, (data) => {
|
|
1199
|
+
const enriched = {
|
|
1200
|
+
...data,
|
|
1201
|
+
mutationContext
|
|
1202
|
+
};
|
|
1203
|
+
options?.onRequestStart?.(enriched);
|
|
1204
|
+
$hooks.__emit("onRequestStart", enriched);
|
|
1205
|
+
});
|
|
1206
|
+
const unmountResponseStart = requestManager.events.onResponseStartById(requestId, (data) => {
|
|
1207
|
+
const enriched = {
|
|
1208
|
+
...data,
|
|
1209
|
+
mutationContext
|
|
1210
|
+
};
|
|
1211
|
+
options?.onResponseStart?.(enriched);
|
|
1212
|
+
$hooks.__emit("onResponseStart", enriched);
|
|
1213
|
+
});
|
|
1214
|
+
const unmountUpload = requestManager.events.onUploadProgressById(requestId, (data) => {
|
|
1215
|
+
const enriched = {
|
|
1216
|
+
...data,
|
|
1217
|
+
mutationContext
|
|
1218
|
+
};
|
|
1219
|
+
options?.onUploadProgress?.(enriched);
|
|
1220
|
+
$hooks.__emit("onUploadProgress", enriched);
|
|
1221
|
+
});
|
|
1222
|
+
const unmountDownload = requestManager.events.onDownloadProgressById(requestId, (data) => {
|
|
1223
|
+
const enriched = {
|
|
1224
|
+
...data,
|
|
1225
|
+
mutationContext
|
|
1226
|
+
};
|
|
1227
|
+
options?.onDownloadProgress?.(enriched);
|
|
1228
|
+
$hooks.__emit("onDownloadProgress", enriched);
|
|
1229
|
+
});
|
|
1230
|
+
const unmountResponse = requestManager.events.onResponseById(requestId, (values) => {
|
|
1231
|
+
const { details, response } = values;
|
|
1232
|
+
isResolved = true;
|
|
1233
|
+
const enrichedValues = {
|
|
1234
|
+
...values,
|
|
1235
|
+
mutationContext
|
|
1236
|
+
};
|
|
1237
|
+
const mapping = request.unstable_responseMapper?.(response);
|
|
1238
|
+
const isOfflineStatus = request.offline && details.isOffline;
|
|
1239
|
+
const { willRetry } = details;
|
|
1240
|
+
const handleResponse = (success, data) => {
|
|
1241
|
+
if (!success && isOfflineStatus) return;
|
|
1242
|
+
if (!success && willRetry) return;
|
|
1243
|
+
options?.onResponse?.(enrichedValues);
|
|
1244
|
+
$hooks.__emit("onResponse", enrichedValues);
|
|
1245
|
+
resolve(data);
|
|
1246
|
+
umountAll();
|
|
1247
|
+
};
|
|
1248
|
+
if (mapping instanceof Promise) (async () => {
|
|
1249
|
+
const responseData = await mapping;
|
|
1250
|
+
const { success } = responseData;
|
|
1251
|
+
handleResponse(success, responseData);
|
|
1252
|
+
})();
|
|
1253
|
+
else {
|
|
1254
|
+
const data = mapping || response;
|
|
1255
|
+
const { success } = data;
|
|
1256
|
+
handleResponse(success, data);
|
|
1257
|
+
}
|
|
1258
|
+
});
|
|
1259
|
+
const unmountRemoveQueueElement = requestManager.events.onRemoveById(requestId, (data) => {
|
|
1260
|
+
if (!isResolved) {
|
|
1261
|
+
const enriched = {
|
|
1262
|
+
...data,
|
|
1263
|
+
mutationContext
|
|
1264
|
+
};
|
|
1265
|
+
options?.onRemove?.(enriched);
|
|
1266
|
+
$hooks.__emit("onRemove", enriched);
|
|
1267
|
+
resolve({
|
|
1268
|
+
data: null,
|
|
1269
|
+
status: null,
|
|
1270
|
+
success: false,
|
|
1271
|
+
error: getErrorMessage("deleted"),
|
|
1272
|
+
extra: request.client.adapter.defaultExtra,
|
|
1273
|
+
requestTimestamp: +/* @__PURE__ */ new Date(),
|
|
1274
|
+
responseTimestamp: +/* @__PURE__ */ new Date()
|
|
1275
|
+
});
|
|
1276
|
+
umountAll();
|
|
1277
|
+
}
|
|
1278
|
+
});
|
|
1279
|
+
function umountAll() {
|
|
1280
|
+
unmountRequestStart();
|
|
1281
|
+
unmountResponseStart();
|
|
1282
|
+
unmountUpload();
|
|
1283
|
+
unmountDownload();
|
|
1284
|
+
unmountResponse();
|
|
1285
|
+
unmountRemoveQueueElement();
|
|
1286
|
+
}
|
|
1287
|
+
});
|
|
1288
|
+
};
|
|
1289
|
+
//#endregion
|
|
1290
|
+
//#region src/constants/time.constants.ts
|
|
1291
|
+
var Time = /* @__PURE__ */ function(Time) {
|
|
1292
|
+
Time[Time["SEC"] = 1e3] = "SEC";
|
|
1293
|
+
Time[Time["MIN"] = 6e4] = "MIN";
|
|
1294
|
+
Time[Time["HOUR"] = 36e5] = "HOUR";
|
|
1295
|
+
Time[Time["DAY"] = 864e5] = "DAY";
|
|
1296
|
+
Time[Time["WEEK"] = 6048e5] = "WEEK";
|
|
1297
|
+
Time[Time["MONTH_30"] = 2592e6] = "MONTH_30";
|
|
1298
|
+
Time[Time["MONTH_31"] = 26784e5] = "MONTH_31";
|
|
1299
|
+
Time[Time["YEAR"] = 31536e6] = "YEAR";
|
|
1300
|
+
Time[Time["YEAR_LEAP"] = 316224e5] = "YEAR_LEAP";
|
|
1301
|
+
return Time;
|
|
1302
|
+
}({});
|
|
1303
|
+
//#endregion
|
|
1304
|
+
//#region src/request/request.ts
|
|
1305
|
+
/**
|
|
1306
|
+
* Request is a class that represents a request sent to the server. It contains all the necessary information to make a request, like endpoint, method, headers, data, and much more.
|
|
1307
|
+
* It is executed at any time via methods like `send` or `exec`.
|
|
1308
|
+
*
|
|
1309
|
+
* We can set it up with options like endpoint, method, headers and more.
|
|
1310
|
+
* We can choose some of advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.
|
|
1311
|
+
*
|
|
1312
|
+
* @info We should not use this class directly in the standard development flow.
|
|
1313
|
+
* We can initialize it using the `createRequest` method on the **Client** class.
|
|
1314
|
+
*
|
|
1315
|
+
* @attention The most important thing about the request is that it keeps data in the format that can be dumped.
|
|
1316
|
+
* This is necessary for the persistence and different dispatcher storage types.
|
|
1317
|
+
* This class doesn't have any callback methods by design and communicate with dispatcher and cache by events.
|
|
1318
|
+
*
|
|
1319
|
+
* It should be serializable to JSON and deserializable back to the class.
|
|
1320
|
+
* Serialization should not affect the result of the request, so it's methods and functional part should be only syntax sugar for given runtime.
|
|
1321
|
+
*/
|
|
1322
|
+
var Request = class Request {
|
|
1323
|
+
endpoint;
|
|
1324
|
+
headers;
|
|
1325
|
+
auth;
|
|
1326
|
+
method;
|
|
1327
|
+
params;
|
|
1328
|
+
payload;
|
|
1329
|
+
queryParams;
|
|
1330
|
+
options;
|
|
1331
|
+
cancelable;
|
|
1332
|
+
retry;
|
|
1333
|
+
retryTime;
|
|
1334
|
+
cacheTime;
|
|
1335
|
+
cache;
|
|
1336
|
+
staleTime;
|
|
1337
|
+
queued;
|
|
1338
|
+
offline;
|
|
1339
|
+
abortKey;
|
|
1340
|
+
cacheKey;
|
|
1341
|
+
queryKey;
|
|
1342
|
+
used;
|
|
1343
|
+
deduplicate;
|
|
1344
|
+
deduplicateTime;
|
|
1345
|
+
scope;
|
|
1346
|
+
/**
|
|
1347
|
+
* Instance-level lifecycle hooks. These callbacks fire for every `send()` / `exec()` call
|
|
1348
|
+
* made on this request instance (and its clones), without needing to pass them to `send()` each time.
|
|
1349
|
+
* Useful for cross-cutting concerns like logging, analytics, or toast notifications.
|
|
1350
|
+
*
|
|
1351
|
+
* Each method registers a callback and returns an unsubscribe function.
|
|
1352
|
+
* Multiple listeners per hook are supported.
|
|
1353
|
+
*/
|
|
1354
|
+
$hooks = createRequestHooks();
|
|
1355
|
+
isMockerEnabled = false;
|
|
1356
|
+
unstable_mock;
|
|
1357
|
+
/** @internal */
|
|
1358
|
+
unstable_payloadMapper;
|
|
1359
|
+
/** @internal */
|
|
1360
|
+
unstable_requestMapper;
|
|
1361
|
+
/** @internal */
|
|
1362
|
+
unstable_responseMapper;
|
|
1363
|
+
/** @internal */
|
|
1364
|
+
retryOnError;
|
|
1365
|
+
/** @internal */
|
|
1366
|
+
optimistic;
|
|
1367
|
+
unstable_hasParams = false;
|
|
1368
|
+
unstable_hasPayload = false;
|
|
1369
|
+
unstable_hasQuery = false;
|
|
1370
|
+
unstable_hasMutationContext = void 0;
|
|
1371
|
+
updatedAbortKey;
|
|
1372
|
+
updatedCacheKey;
|
|
1373
|
+
updatedQueryKey;
|
|
1374
|
+
constructor(client, requestOptions, initialRequestConfiguration) {
|
|
1375
|
+
this.client = client;
|
|
1376
|
+
this.requestOptions = requestOptions;
|
|
1377
|
+
this.initialRequestConfiguration = initialRequestConfiguration;
|
|
1378
|
+
const { endpoint, headers, auth = true, method = client.adapter.defaultMethod, options, cancelable = false, retry = 0, retryTime = 500, cacheTime = Time.MIN * 5, cache = true, staleTime = Time.MIN * 5, queued = false, offline = true, abortKey, cacheKey, queryKey, deduplicate = false, deduplicateTime = null } = {
|
|
1379
|
+
...this.client.adapter.unstable_getRequestDefaults?.(requestOptions),
|
|
1380
|
+
...requestOptions
|
|
1381
|
+
};
|
|
1382
|
+
this.endpoint = initialRequestConfiguration?.endpoint ?? endpoint;
|
|
1383
|
+
this.headers = initialRequestConfiguration?.headers ?? headers;
|
|
1384
|
+
this.auth = initialRequestConfiguration?.auth ?? auth;
|
|
1385
|
+
this.method = method;
|
|
1386
|
+
this.params = initialRequestConfiguration?.params;
|
|
1387
|
+
this.payload = initialRequestConfiguration?.payload;
|
|
1388
|
+
this.queryParams = initialRequestConfiguration?.queryParams;
|
|
1389
|
+
this.options = initialRequestConfiguration?.options ?? options;
|
|
1390
|
+
this.cancelable = initialRequestConfiguration?.cancelable ?? cancelable;
|
|
1391
|
+
this.retry = initialRequestConfiguration?.retry ?? retry;
|
|
1392
|
+
this.retryTime = initialRequestConfiguration?.retryTime ?? retryTime;
|
|
1393
|
+
this.cacheTime = initialRequestConfiguration?.cacheTime ?? cacheTime;
|
|
1394
|
+
this.cache = initialRequestConfiguration?.cache ?? cache;
|
|
1395
|
+
this.staleTime = initialRequestConfiguration?.staleTime ?? staleTime;
|
|
1396
|
+
this.queued = initialRequestConfiguration?.queued ?? queued;
|
|
1397
|
+
this.offline = initialRequestConfiguration?.offline ?? offline;
|
|
1398
|
+
this.abortKey = initialRequestConfiguration?.abortKey ?? abortKey ?? this.client.unstable_abortKeyMapper(this);
|
|
1399
|
+
this.cacheKey = initialRequestConfiguration?.cacheKey ?? cacheKey ?? this.client.unstable_cacheKeyMapper(this);
|
|
1400
|
+
this.queryKey = initialRequestConfiguration?.queryKey ?? queryKey ?? this.client.unstable_queryKeyMapper(this);
|
|
1401
|
+
this.used = initialRequestConfiguration?.used ?? false;
|
|
1402
|
+
this.deduplicate = initialRequestConfiguration?.deduplicate ?? deduplicate;
|
|
1403
|
+
this.deduplicateTime = initialRequestConfiguration?.deduplicateTime ?? deduplicateTime;
|
|
1404
|
+
this.scope = initialRequestConfiguration?.scope ?? null;
|
|
1405
|
+
this.updatedAbortKey = initialRequestConfiguration?.updatedAbortKey ?? false;
|
|
1406
|
+
this.updatedCacheKey = initialRequestConfiguration?.updatedCacheKey ?? false;
|
|
1407
|
+
this.updatedQueryKey = initialRequestConfiguration?.updatedQueryKey ?? false;
|
|
1408
|
+
}
|
|
1409
|
+
setHeaders = (headers) => {
|
|
1410
|
+
return this.clone({ headers });
|
|
1411
|
+
};
|
|
1412
|
+
setAuth = (auth) => {
|
|
1413
|
+
return this.clone({ auth });
|
|
1414
|
+
};
|
|
1415
|
+
setParams = (params) => {
|
|
1416
|
+
return this.clone({ params });
|
|
1417
|
+
};
|
|
1418
|
+
setPayload = (payload) => {
|
|
1419
|
+
return this.clone({ payload });
|
|
1420
|
+
};
|
|
1421
|
+
setQueryParams = (queryParams) => {
|
|
1422
|
+
return this.clone({ queryParams });
|
|
1423
|
+
};
|
|
1424
|
+
setOptions = (options) => {
|
|
1425
|
+
return this.clone({ options });
|
|
1426
|
+
};
|
|
1427
|
+
/**
|
|
1428
|
+
* Set a scope identifier for this request.
|
|
1429
|
+
* All keys (cache, queue, abort) are prefixed with this scope, isolating
|
|
1430
|
+
* the request from other scopes. In "server" client mode, setting a scope
|
|
1431
|
+
* also enables caching (which is otherwise disabled to prevent cross-request leaks).
|
|
1432
|
+
*/
|
|
1433
|
+
setScope = (scopeId) => {
|
|
1434
|
+
const cloned = this.clone();
|
|
1435
|
+
cloned.scope = scopeId;
|
|
1436
|
+
return cloned;
|
|
1437
|
+
};
|
|
1438
|
+
setCancelable = (cancelable) => {
|
|
1439
|
+
return this.clone({ cancelable });
|
|
1440
|
+
};
|
|
1441
|
+
setRetry = (retry) => {
|
|
1442
|
+
return this.clone({ retry });
|
|
1443
|
+
};
|
|
1444
|
+
setRetryTime = (retryTime) => {
|
|
1445
|
+
return this.clone({ retryTime });
|
|
1446
|
+
};
|
|
1447
|
+
/**
|
|
1448
|
+
* Set a callback that controls whether a failed request should be retried.
|
|
1449
|
+
* Called on each failed attempt before scheduling the next retry.
|
|
1450
|
+
* Return `true` to allow the retry, `false` to stop retrying immediately.
|
|
1451
|
+
*/
|
|
1452
|
+
setRetryOnError = (callback) => {
|
|
1453
|
+
const cloned = this.clone();
|
|
1454
|
+
cloned.retryOnError = callback;
|
|
1455
|
+
return cloned;
|
|
1456
|
+
};
|
|
1457
|
+
/**
|
|
1458
|
+
* Configure optimistic update behavior for this request.
|
|
1459
|
+
* The callback runs before the request is sent (in React's `useSubmit`) and receives
|
|
1460
|
+
* the request, client, and payload. Return `context` (available in submit callbacks),
|
|
1461
|
+
* `rollback` (called automatically on failure/abort), and `invalidate` (cache keys
|
|
1462
|
+
* invalidated on success).
|
|
1463
|
+
*/
|
|
1464
|
+
setOptimistic = (callback) => {
|
|
1465
|
+
const cloned = this.clone();
|
|
1466
|
+
cloned.optimistic = callback;
|
|
1467
|
+
return cloned;
|
|
1468
|
+
};
|
|
1469
|
+
setCacheTime = (cacheTime) => {
|
|
1470
|
+
return this.clone({ cacheTime });
|
|
1471
|
+
};
|
|
1472
|
+
setCache = (cache) => {
|
|
1473
|
+
return this.clone({ cache });
|
|
1474
|
+
};
|
|
1475
|
+
setStaleTime = (staleTime) => {
|
|
1476
|
+
return this.clone({ staleTime });
|
|
1477
|
+
};
|
|
1478
|
+
setQueued = (queued) => {
|
|
1479
|
+
return this.clone({ queued });
|
|
1480
|
+
};
|
|
1481
|
+
setAbortKey = (abortKey) => {
|
|
1482
|
+
this.updatedAbortKey = true;
|
|
1483
|
+
return this.clone({ abortKey });
|
|
1484
|
+
};
|
|
1485
|
+
setCacheKey = (cacheKey) => {
|
|
1486
|
+
this.updatedCacheKey = true;
|
|
1487
|
+
return this.clone({ cacheKey });
|
|
1488
|
+
};
|
|
1489
|
+
setQueryKey = (queryKey) => {
|
|
1490
|
+
this.updatedQueryKey = true;
|
|
1491
|
+
return this.clone({ queryKey });
|
|
1492
|
+
};
|
|
1493
|
+
setDeduplicate = (deduplicate) => {
|
|
1494
|
+
return this.clone({ deduplicate });
|
|
1495
|
+
};
|
|
1496
|
+
setDeduplicateTime = (deduplicateTime) => {
|
|
1497
|
+
return this.clone({ deduplicateTime });
|
|
1498
|
+
};
|
|
1499
|
+
setUsed = (used) => {
|
|
1500
|
+
return this.clone({ used });
|
|
1501
|
+
};
|
|
1502
|
+
setOffline = (offline) => {
|
|
1503
|
+
return this.clone({ offline });
|
|
1504
|
+
};
|
|
1505
|
+
setMock = (fn, config = {}) => {
|
|
1506
|
+
this.unstable_mock = {
|
|
1507
|
+
fn,
|
|
1508
|
+
config
|
|
1509
|
+
};
|
|
1510
|
+
this.isMockerEnabled = true;
|
|
1511
|
+
return this;
|
|
1512
|
+
};
|
|
1513
|
+
clearMock = () => {
|
|
1514
|
+
this.unstable_mock = void 0;
|
|
1515
|
+
this.isMockerEnabled = false;
|
|
1516
|
+
return this;
|
|
1517
|
+
};
|
|
1518
|
+
setMockingEnabled = (isMockerEnabled) => {
|
|
1519
|
+
this.isMockerEnabled = isMockerEnabled;
|
|
1520
|
+
return this;
|
|
1521
|
+
};
|
|
1522
|
+
/**
|
|
1523
|
+
* Map data before it gets send to the server
|
|
1524
|
+
* @param payloadMapper
|
|
1525
|
+
* @returns
|
|
1526
|
+
*/
|
|
1527
|
+
setPayloadMapper = (payloadMapper) => {
|
|
1528
|
+
const cloned = this.clone(void 0);
|
|
1529
|
+
cloned.unstable_payloadMapper = payloadMapper;
|
|
1530
|
+
return cloned;
|
|
1531
|
+
};
|
|
1532
|
+
/**
|
|
1533
|
+
* Map request before it gets send to the server
|
|
1534
|
+
* @param requestMapper mapper of the request
|
|
1535
|
+
* @returns new request
|
|
1536
|
+
*/
|
|
1537
|
+
setRequestMapper = (requestMapper) => {
|
|
1538
|
+
const cloned = this.clone(void 0);
|
|
1539
|
+
cloned.unstable_requestMapper = requestMapper;
|
|
1540
|
+
return cloned;
|
|
1541
|
+
};
|
|
1542
|
+
/**
|
|
1543
|
+
* Map the response to the new interface
|
|
1544
|
+
* @param responseMapper our mapping callback
|
|
1545
|
+
* @returns new response
|
|
1546
|
+
*/
|
|
1547
|
+
setResponseMapper = (responseMapper) => {
|
|
1548
|
+
const cloned = this.clone();
|
|
1549
|
+
cloned.unstable_responseMapper = responseMapper;
|
|
1550
|
+
return cloned;
|
|
1551
|
+
};
|
|
1552
|
+
paramsMapper = (params) => {
|
|
1553
|
+
const { endpoint } = this.requestOptions;
|
|
1554
|
+
let stringEndpoint = String(endpoint);
|
|
1555
|
+
if (params) Object.entries(params).forEach(([key, value]) => {
|
|
1556
|
+
stringEndpoint = stringEndpoint.replace(new RegExp(`:${key}`, "g"), String(value));
|
|
1557
|
+
});
|
|
1558
|
+
return stringEndpoint;
|
|
1559
|
+
};
|
|
1560
|
+
toJSON() {
|
|
1561
|
+
return {
|
|
1562
|
+
requestOptions: this.requestOptions,
|
|
1563
|
+
endpoint: this.endpoint,
|
|
1564
|
+
headers: this.headers,
|
|
1565
|
+
auth: this.auth,
|
|
1566
|
+
method: this.method,
|
|
1567
|
+
params: this.params,
|
|
1568
|
+
payload: this.payload,
|
|
1569
|
+
queryParams: this.queryParams,
|
|
1570
|
+
options: this.options,
|
|
1571
|
+
cancelable: this.cancelable,
|
|
1572
|
+
retry: this.retry,
|
|
1573
|
+
retryTime: this.retryTime,
|
|
1574
|
+
cacheTime: this.cacheTime,
|
|
1575
|
+
cache: this.cache,
|
|
1576
|
+
staleTime: this.staleTime,
|
|
1577
|
+
queued: this.queued,
|
|
1578
|
+
offline: this.offline,
|
|
1579
|
+
abortKey: this.abortKey,
|
|
1580
|
+
cacheKey: this.cacheKey,
|
|
1581
|
+
queryKey: this.queryKey,
|
|
1582
|
+
used: this.used,
|
|
1583
|
+
disableResponseInterceptors: this.requestOptions.disableResponseInterceptors,
|
|
1584
|
+
disableRequestInterceptors: this.requestOptions.disableRequestInterceptors,
|
|
1585
|
+
updatedAbortKey: this.updatedAbortKey,
|
|
1586
|
+
updatedCacheKey: this.updatedCacheKey,
|
|
1587
|
+
updatedQueryKey: this.updatedQueryKey,
|
|
1588
|
+
deduplicate: this.deduplicate,
|
|
1589
|
+
deduplicateTime: this.deduplicateTime,
|
|
1590
|
+
scope: this.scope,
|
|
1591
|
+
isMockerEnabled: this.isMockerEnabled,
|
|
1592
|
+
hasMock: !!this.unstable_mock
|
|
1593
|
+
};
|
|
1594
|
+
}
|
|
1595
|
+
clone(configuration) {
|
|
1596
|
+
const initialRequestConfiguration = {
|
|
1597
|
+
...this.toJSON(),
|
|
1598
|
+
...configuration,
|
|
1599
|
+
options: configuration?.options || this.options,
|
|
1600
|
+
abortKey: this.updatedAbortKey ? configuration?.abortKey || this.abortKey : void 0,
|
|
1601
|
+
cacheKey: this.updatedCacheKey ? configuration?.cacheKey || this.cacheKey : void 0,
|
|
1602
|
+
queryKey: this.updatedQueryKey ? configuration?.queryKey || this.queryKey : void 0,
|
|
1603
|
+
endpoint: this.paramsMapper(configuration?.params || this.params),
|
|
1604
|
+
queryParams: configuration?.queryParams || this.queryParams,
|
|
1605
|
+
payload: configuration?.payload || this.payload,
|
|
1606
|
+
params: configuration?.params || this.params
|
|
1607
|
+
};
|
|
1608
|
+
const cloned = new Request(this.client, this.requestOptions, initialRequestConfiguration);
|
|
1609
|
+
cloned.unstable_payloadMapper = this.unstable_payloadMapper;
|
|
1610
|
+
cloned.unstable_responseMapper = this.unstable_responseMapper;
|
|
1611
|
+
cloned.unstable_requestMapper = this.unstable_requestMapper;
|
|
1612
|
+
cloned.retryOnError = this.retryOnError;
|
|
1613
|
+
cloned.unstable_mock = this.unstable_mock;
|
|
1614
|
+
cloned.isMockerEnabled = this.isMockerEnabled;
|
|
1615
|
+
cloned.optimistic = this.optimistic;
|
|
1616
|
+
cloned.$hooks = createRequestHooks(this.$hooks.__snapshot());
|
|
1617
|
+
return cloned;
|
|
1618
|
+
}
|
|
1619
|
+
abort = () => {
|
|
1620
|
+
const { requestManager } = this.client;
|
|
1621
|
+
requestManager.abortByKey(scopeKey(this.abortKey, this.scope));
|
|
1622
|
+
return this.clone();
|
|
1623
|
+
};
|
|
1624
|
+
dehydrate = (config) => {
|
|
1625
|
+
const { response, override = true } = config || {};
|
|
1626
|
+
if (response) return {
|
|
1627
|
+
override,
|
|
1628
|
+
cacheTime: this.cacheTime,
|
|
1629
|
+
staleTime: this.staleTime,
|
|
1630
|
+
cacheKey: this.cacheKey,
|
|
1631
|
+
scope: this.scope,
|
|
1632
|
+
timestamp: +/* @__PURE__ */ new Date(),
|
|
1633
|
+
hydrated: true,
|
|
1634
|
+
cache: true,
|
|
1635
|
+
response
|
|
1636
|
+
};
|
|
1637
|
+
const cacheData = this.client.cache.get(scopeKey(this.cacheKey, this.scope));
|
|
1638
|
+
if (!cacheData) return;
|
|
1639
|
+
return {
|
|
1640
|
+
override,
|
|
1641
|
+
cacheTime: this.cacheTime,
|
|
1642
|
+
staleTime: this.staleTime,
|
|
1643
|
+
cacheKey: this.cacheKey,
|
|
1644
|
+
scope: this.scope,
|
|
1645
|
+
timestamp: +/* @__PURE__ */ new Date(),
|
|
1646
|
+
hydrated: true,
|
|
1647
|
+
cache: true,
|
|
1648
|
+
response: {
|
|
1649
|
+
data: cacheData.data,
|
|
1650
|
+
error: cacheData.error,
|
|
1651
|
+
status: cacheData.status,
|
|
1652
|
+
success: cacheData.success,
|
|
1653
|
+
extra: cacheData.extra,
|
|
1654
|
+
requestTimestamp: cacheData.requestTimestamp,
|
|
1655
|
+
responseTimestamp: cacheData.responseTimestamp
|
|
1656
|
+
}
|
|
1657
|
+
};
|
|
1658
|
+
};
|
|
1659
|
+
/**
|
|
1660
|
+
* Read the response from cache data
|
|
1661
|
+
*
|
|
1662
|
+
* If it returns error and data at the same time, it means that latest request was failed
|
|
1663
|
+
* and we show previous data from cache together with error received from actual request
|
|
1664
|
+
*/
|
|
1665
|
+
read() {
|
|
1666
|
+
const cacheData = this.client.cache.get(scopeKey(this.cacheKey, this.scope));
|
|
1667
|
+
if (cacheData) return {
|
|
1668
|
+
data: cacheData.data,
|
|
1669
|
+
error: cacheData.error,
|
|
1670
|
+
status: cacheData.status,
|
|
1671
|
+
success: cacheData.success,
|
|
1672
|
+
extra: cacheData.extra,
|
|
1673
|
+
requestTimestamp: cacheData.requestTimestamp,
|
|
1674
|
+
responseTimestamp: cacheData.responseTimestamp
|
|
1675
|
+
};
|
|
1676
|
+
}
|
|
1677
|
+
/**
|
|
1678
|
+
* Method to use the request WITHOUT adding it to cache and queues. This mean it will make simple request without queue side effects.
|
|
1679
|
+
* @param options
|
|
1680
|
+
* @disableReturns
|
|
1681
|
+
* @returns
|
|
1682
|
+
* ```tsx
|
|
1683
|
+
* Promise<[Data | null, Error | null, HttpStatus]>
|
|
1684
|
+
* ```
|
|
1685
|
+
*/
|
|
1686
|
+
exec = async (options) => {
|
|
1687
|
+
const { adapter, requestManager } = this.client;
|
|
1688
|
+
const request = this.clone(options);
|
|
1689
|
+
const requestId = this.client.unstable_requestIdMapper(this);
|
|
1690
|
+
const scopedAbortKey = scopeKey(this.abortKey, this.scope);
|
|
1691
|
+
requestManager.addAbortController(scopedAbortKey, requestId);
|
|
1692
|
+
const response = await adapter.fetch(request, requestId);
|
|
1693
|
+
requestManager.removeAbortController(scopedAbortKey, requestId);
|
|
1694
|
+
if (request.unstable_responseMapper) return request.unstable_responseMapper(response);
|
|
1695
|
+
return response;
|
|
1696
|
+
};
|
|
1697
|
+
/**
|
|
1698
|
+
* Method used to perform requests with usage of cache and queues
|
|
1699
|
+
* @param options
|
|
1700
|
+
* @param requestCallback
|
|
1701
|
+
* @disableReturns
|
|
1702
|
+
* @returns
|
|
1703
|
+
* ```tsx
|
|
1704
|
+
* Promise<{ data: Data | null, error: Error | null, status: HttpStatus, ... }>
|
|
1705
|
+
* ```
|
|
1706
|
+
*/
|
|
1707
|
+
send = async (options) => {
|
|
1708
|
+
const { dispatcherType, cachePolicy = "network-only", ...configuration } = options || {};
|
|
1709
|
+
const request = this.clone(configuration);
|
|
1710
|
+
const sendRequestOptions = options === void 0 ? void 0 : {
|
|
1711
|
+
...options,
|
|
1712
|
+
cachePolicy: void 0
|
|
1713
|
+
};
|
|
1714
|
+
if (cachePolicy === "network-only") return sendRequest(request, sendRequestOptions);
|
|
1715
|
+
const cached = request.read();
|
|
1716
|
+
if (cachePolicy === "cache-first") {
|
|
1717
|
+
if (cached) return mapResponseForSend(request, cached);
|
|
1718
|
+
return sendRequest(request, sendRequestOptions);
|
|
1719
|
+
}
|
|
1720
|
+
if (cached) {
|
|
1721
|
+
const resolved = await mapResponseForSend(request, cached);
|
|
1722
|
+
sendRequest(request, sendRequestOptions);
|
|
1723
|
+
return resolved;
|
|
1724
|
+
}
|
|
1725
|
+
return sendRequest(request, sendRequestOptions);
|
|
1726
|
+
};
|
|
1727
|
+
static fromJSON = (client, json) => {
|
|
1728
|
+
return new Request(client, json.requestOptions, json);
|
|
1729
|
+
};
|
|
1730
|
+
};
|
|
1731
|
+
//#endregion
|
|
1732
|
+
//#region src/adapter/adapter.bindings.ts
|
|
1733
|
+
var getAdapterBindings = async ({ request: baseRequest, requestId, resolve, onStartTime, internalErrorMapping }) => {
|
|
1734
|
+
const { requestManager, loggerManager } = baseRequest.client;
|
|
1735
|
+
const { unstable_payloadMapper } = baseRequest.client.adapter;
|
|
1736
|
+
const logger = loggerManager.initialize(baseRequest.client, "Adapter");
|
|
1737
|
+
let requestStartTimestamp = null;
|
|
1738
|
+
let responseStartTimestamp = null;
|
|
1739
|
+
let request = baseRequest;
|
|
1740
|
+
let requestTotal = 1;
|
|
1741
|
+
let responseTotal = 1;
|
|
1742
|
+
let previousRequestTotal = 0;
|
|
1743
|
+
let previousResponseTotal = 0;
|
|
1744
|
+
logger.debug({
|
|
1745
|
+
title: `Running middleware callbacks`,
|
|
1746
|
+
type: "request",
|
|
1747
|
+
extra: {
|
|
1748
|
+
request,
|
|
1749
|
+
requestId
|
|
1750
|
+
}
|
|
1751
|
+
});
|
|
1752
|
+
request = await request.client.unstable_modifyRequest(request);
|
|
1753
|
+
if (request.auth) request = await request.client.unstable_modifyAuth(request);
|
|
1754
|
+
if (request.unstable_requestMapper) request = await request.unstable_requestMapper(request, requestId);
|
|
1755
|
+
const { client, abortKey } = request;
|
|
1756
|
+
const scopedAbortKey = scopeKey(abortKey, request.scope);
|
|
1757
|
+
let payload = request.payload;
|
|
1758
|
+
if (request.unstable_payloadMapper) payload = await request.unstable_payloadMapper(request.payload);
|
|
1759
|
+
else if (unstable_payloadMapper) payload = await unstable_payloadMapper(payload);
|
|
1760
|
+
const adapterOptions = request.options;
|
|
1761
|
+
const startTime = +/* @__PURE__ */ new Date();
|
|
1762
|
+
onStartTime(startTime);
|
|
1763
|
+
const getRequestStartTimestamp = () => {
|
|
1764
|
+
return requestStartTimestamp;
|
|
1765
|
+
};
|
|
1766
|
+
const getResponseStartTimestamp = () => {
|
|
1767
|
+
return responseStartTimestamp;
|
|
1768
|
+
};
|
|
1769
|
+
const getTotal = (previousTotal, progress) => {
|
|
1770
|
+
if (!progress) return previousTotal;
|
|
1771
|
+
const total = Number(progress.total || 0);
|
|
1772
|
+
const loaded = Number(progress.loaded || 0);
|
|
1773
|
+
return Math.max(total, loaded, previousTotal);
|
|
1774
|
+
};
|
|
1775
|
+
const handleRequestProgress = (startTimestamp, progressTimestamp, progressEvent) => {
|
|
1776
|
+
const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);
|
|
1777
|
+
if (previousRequestTotal !== 100) {
|
|
1778
|
+
previousRequestTotal = progress.total;
|
|
1779
|
+
requestManager.events.emitUploadProgress({
|
|
1780
|
+
...progress,
|
|
1781
|
+
requestId,
|
|
1782
|
+
request
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
};
|
|
1786
|
+
const handleResponseProgress = (startTimestamp, progressTimestamp, progressEvent) => {
|
|
1787
|
+
const progress = getProgressData(new Date(startTimestamp), new Date(progressTimestamp), progressEvent);
|
|
1788
|
+
if (previousResponseTotal !== 100) {
|
|
1789
|
+
previousResponseTotal = progress.total;
|
|
1790
|
+
requestManager.events.emitDownloadProgress({
|
|
1791
|
+
...progress,
|
|
1792
|
+
requestId,
|
|
1793
|
+
request
|
|
1794
|
+
});
|
|
1795
|
+
}
|
|
1796
|
+
};
|
|
1797
|
+
const onBeforeRequest = () => {
|
|
1798
|
+
logger.debug({
|
|
1799
|
+
title: `Request about to be sent`,
|
|
1800
|
+
type: "request",
|
|
1801
|
+
extra: {
|
|
1802
|
+
request,
|
|
1803
|
+
requestId
|
|
1804
|
+
}
|
|
1805
|
+
});
|
|
1806
|
+
client.triggerPlugins("onRequestTrigger", { request });
|
|
1807
|
+
};
|
|
1808
|
+
const onRequestStart = (progress) => {
|
|
1809
|
+
logger.info({
|
|
1810
|
+
title: `Request start`,
|
|
1811
|
+
type: "request",
|
|
1812
|
+
extra: {
|
|
1813
|
+
request,
|
|
1814
|
+
requestId
|
|
1815
|
+
}
|
|
1816
|
+
});
|
|
1817
|
+
client.triggerPlugins("onRequestStart", { request });
|
|
1818
|
+
if (progress?.total) requestTotal = getTotal(requestTotal, progress);
|
|
1819
|
+
const initialPayload = {
|
|
1820
|
+
total: requestTotal,
|
|
1821
|
+
loaded: progress?.loaded || 0
|
|
1822
|
+
};
|
|
1823
|
+
requestStartTimestamp = +/* @__PURE__ */ new Date();
|
|
1824
|
+
handleRequestProgress(requestStartTimestamp, requestStartTimestamp, initialPayload);
|
|
1825
|
+
requestManager.events.emitRequestStart({
|
|
1826
|
+
requestId,
|
|
1827
|
+
request
|
|
1828
|
+
});
|
|
1829
|
+
return requestStartTimestamp;
|
|
1830
|
+
};
|
|
1831
|
+
const onRequestProgress = (progress) => {
|
|
1832
|
+
if (!requestStartTimestamp) requestStartTimestamp = +/* @__PURE__ */ new Date();
|
|
1833
|
+
requestTotal = getTotal(requestTotal, progress);
|
|
1834
|
+
const progressTimestamp = +/* @__PURE__ */ new Date();
|
|
1835
|
+
handleRequestProgress(requestStartTimestamp, progressTimestamp, {
|
|
1836
|
+
total: requestTotal,
|
|
1837
|
+
loaded: progress.loaded || 0
|
|
1838
|
+
});
|
|
1839
|
+
return progressTimestamp;
|
|
1840
|
+
};
|
|
1841
|
+
const onRequestEnd = () => {
|
|
1842
|
+
if (!requestStartTimestamp) requestStartTimestamp = +/* @__PURE__ */ new Date();
|
|
1843
|
+
const progressTimestamp = +/* @__PURE__ */ new Date();
|
|
1844
|
+
handleRequestProgress(requestStartTimestamp, progressTimestamp, {
|
|
1845
|
+
total: requestTotal,
|
|
1846
|
+
loaded: requestTotal
|
|
1847
|
+
});
|
|
1848
|
+
return progressTimestamp;
|
|
1849
|
+
};
|
|
1850
|
+
const onResponseStart = (progress) => {
|
|
1851
|
+
responseStartTimestamp = +/* @__PURE__ */ new Date();
|
|
1852
|
+
responseTotal = getTotal(responseTotal, progress);
|
|
1853
|
+
const initialPayload = {
|
|
1854
|
+
total: responseTotal,
|
|
1855
|
+
loaded: progress?.loaded || 0
|
|
1856
|
+
};
|
|
1857
|
+
handleResponseProgress(responseStartTimestamp, responseStartTimestamp, initialPayload);
|
|
1858
|
+
requestManager.events.emitResponseStart({
|
|
1859
|
+
requestId,
|
|
1860
|
+
request
|
|
1861
|
+
});
|
|
1862
|
+
return responseStartTimestamp;
|
|
1863
|
+
};
|
|
1864
|
+
const onResponseProgress = (progress) => {
|
|
1865
|
+
if (!responseStartTimestamp) responseStartTimestamp = +/* @__PURE__ */ new Date();
|
|
1866
|
+
const progressTimestamp = +/* @__PURE__ */ new Date();
|
|
1867
|
+
responseTotal = getTotal(responseTotal, progress);
|
|
1868
|
+
handleResponseProgress(responseStartTimestamp, progressTimestamp, {
|
|
1869
|
+
total: progress.total || responseTotal,
|
|
1870
|
+
loaded: progress.loaded || 0
|
|
1871
|
+
});
|
|
1872
|
+
return progressTimestamp;
|
|
1873
|
+
};
|
|
1874
|
+
const onResponseEnd = () => {
|
|
1875
|
+
if (!responseStartTimestamp) responseStartTimestamp = +/* @__PURE__ */ new Date();
|
|
1876
|
+
const progressTimestamp = +/* @__PURE__ */ new Date();
|
|
1877
|
+
handleResponseProgress(responseStartTimestamp, progressTimestamp, {
|
|
1878
|
+
total: responseTotal,
|
|
1879
|
+
loaded: responseTotal
|
|
1880
|
+
});
|
|
1881
|
+
return progressTimestamp;
|
|
1882
|
+
};
|
|
1883
|
+
const onSuccess = async ({ data, error, status, extra }) => {
|
|
1884
|
+
let response = {
|
|
1885
|
+
data,
|
|
1886
|
+
error: error ?? null,
|
|
1887
|
+
success: true,
|
|
1888
|
+
status,
|
|
1889
|
+
extra,
|
|
1890
|
+
requestTimestamp: startTime,
|
|
1891
|
+
responseTimestamp: +/* @__PURE__ */ new Date()
|
|
1892
|
+
};
|
|
1893
|
+
response = await request.client.unstable_modifyResponse?.(response, request);
|
|
1894
|
+
response = await request.client.unstable_modifySuccessResponse?.(response, request);
|
|
1895
|
+
client.triggerPlugins("onRequestSuccess", {
|
|
1896
|
+
response,
|
|
1897
|
+
request
|
|
1898
|
+
});
|
|
1899
|
+
client.triggerPlugins("onRequestFinished", {
|
|
1900
|
+
response,
|
|
1901
|
+
request
|
|
1902
|
+
});
|
|
1903
|
+
resolve(response);
|
|
1904
|
+
logger.info({
|
|
1905
|
+
title: `Response success`,
|
|
1906
|
+
type: "response",
|
|
1907
|
+
extra: {
|
|
1908
|
+
request,
|
|
1909
|
+
requestId,
|
|
1910
|
+
response
|
|
1911
|
+
}
|
|
1912
|
+
});
|
|
1913
|
+
return response;
|
|
1914
|
+
};
|
|
1915
|
+
const onError = getAdapterOnError({
|
|
1916
|
+
request,
|
|
1917
|
+
requestId,
|
|
1918
|
+
startTime,
|
|
1919
|
+
logger,
|
|
1920
|
+
resolve
|
|
1921
|
+
});
|
|
1922
|
+
const onAbortError = ({ status, extra }) => {
|
|
1923
|
+
logger.error({
|
|
1924
|
+
title: `Abort error`,
|
|
1925
|
+
type: "request",
|
|
1926
|
+
extra: {
|
|
1927
|
+
request,
|
|
1928
|
+
requestId
|
|
1929
|
+
}
|
|
1930
|
+
});
|
|
1931
|
+
return onError({
|
|
1932
|
+
error: internalErrorMapping(getErrorMessage("abort")),
|
|
1933
|
+
status,
|
|
1934
|
+
extra
|
|
1935
|
+
});
|
|
1936
|
+
};
|
|
1937
|
+
const onTimeoutError = ({ status, extra }) => {
|
|
1938
|
+
logger.error({
|
|
1939
|
+
title: `Timeout error`,
|
|
1940
|
+
type: "request",
|
|
1941
|
+
extra: {
|
|
1942
|
+
request,
|
|
1943
|
+
requestId
|
|
1944
|
+
}
|
|
1945
|
+
});
|
|
1946
|
+
return onError({
|
|
1947
|
+
error: getErrorMessage("timeout"),
|
|
1948
|
+
status,
|
|
1949
|
+
extra
|
|
1950
|
+
});
|
|
1951
|
+
};
|
|
1952
|
+
const onUnexpectedError = ({ status, extra }) => {
|
|
1953
|
+
logger.error({
|
|
1954
|
+
title: `Unexpected error`,
|
|
1955
|
+
type: "request",
|
|
1956
|
+
extra: {
|
|
1957
|
+
request,
|
|
1958
|
+
requestId
|
|
1959
|
+
}
|
|
1960
|
+
});
|
|
1961
|
+
return onError({
|
|
1962
|
+
error: getErrorMessage(),
|
|
1963
|
+
status,
|
|
1964
|
+
extra
|
|
1965
|
+
});
|
|
1966
|
+
};
|
|
1967
|
+
const getAbortController = () => {
|
|
1968
|
+
return requestManager.getAbortController(scopedAbortKey, requestId);
|
|
1969
|
+
};
|
|
1970
|
+
const createAbortListener = ({ status, extra, onAbort = () => {} }) => {
|
|
1971
|
+
const controller = getAbortController();
|
|
1972
|
+
if (!controller) throw new RequestProcessingError("Controller is not found");
|
|
1973
|
+
const abort = () => {
|
|
1974
|
+
onAbortError({
|
|
1975
|
+
status,
|
|
1976
|
+
extra
|
|
1977
|
+
});
|
|
1978
|
+
onAbort();
|
|
1979
|
+
requestManager.events.emitAbort({
|
|
1980
|
+
requestId,
|
|
1981
|
+
request
|
|
1982
|
+
});
|
|
1983
|
+
};
|
|
1984
|
+
if (controller.signal.aborted) abort();
|
|
1985
|
+
controller.signal.addEventListener("abort", abort);
|
|
1986
|
+
return () => controller.signal.removeEventListener("abort", abort);
|
|
1987
|
+
};
|
|
1988
|
+
logger.debug({
|
|
1989
|
+
title: `Mounted adapter bindings`,
|
|
1990
|
+
type: "request",
|
|
1991
|
+
extra: {
|
|
1992
|
+
request,
|
|
1993
|
+
requestId,
|
|
1994
|
+
payload,
|
|
1995
|
+
adapterOptions
|
|
1996
|
+
}
|
|
1997
|
+
});
|
|
1998
|
+
const queryParams = baseRequest.client.adapter.unstable_queryParamsMapper(request.queryParams);
|
|
1999
|
+
const endpoint = baseRequest.client.adapter.unstable_endpointMapper(request.endpoint);
|
|
2000
|
+
const headers = baseRequest.client.adapter.unstable_headerMapper(request);
|
|
2001
|
+
const { url } = baseRequest.client;
|
|
2002
|
+
return {
|
|
2003
|
+
request,
|
|
2004
|
+
requestId,
|
|
2005
|
+
url,
|
|
2006
|
+
endpoint,
|
|
2007
|
+
queryParams,
|
|
2008
|
+
payload,
|
|
2009
|
+
headers,
|
|
2010
|
+
adapter: baseRequest.client.adapter,
|
|
2011
|
+
adapterOptions,
|
|
2012
|
+
getAbortController,
|
|
2013
|
+
getRequestStartTimestamp,
|
|
2014
|
+
getResponseStartTimestamp,
|
|
2015
|
+
createAbortListener,
|
|
2016
|
+
onBeforeRequest,
|
|
2017
|
+
onRequestStart,
|
|
2018
|
+
onRequestProgress,
|
|
2019
|
+
onRequestEnd,
|
|
2020
|
+
onResponseStart,
|
|
2021
|
+
onResponseProgress,
|
|
2022
|
+
onResponseEnd,
|
|
2023
|
+
onSuccess,
|
|
2024
|
+
onAbortError,
|
|
2025
|
+
onTimeoutError,
|
|
2026
|
+
onUnexpectedError,
|
|
2027
|
+
onError
|
|
2028
|
+
};
|
|
2029
|
+
};
|
|
2030
|
+
function getAdapterOnError({ request, requestId, startTime, resolve, logger }) {
|
|
2031
|
+
const { client } = request;
|
|
2032
|
+
return async ({ error, status, extra }) => {
|
|
2033
|
+
let response = {
|
|
2034
|
+
data: null,
|
|
2035
|
+
status,
|
|
2036
|
+
error,
|
|
2037
|
+
success: false,
|
|
2038
|
+
extra,
|
|
2039
|
+
requestTimestamp: startTime,
|
|
2040
|
+
responseTimestamp: +/* @__PURE__ */ new Date()
|
|
2041
|
+
};
|
|
2042
|
+
response = await client.unstable_modifyResponse(response, request);
|
|
2043
|
+
response = await client.unstable_modifyErrorResponse(response, request);
|
|
2044
|
+
client.triggerPlugins("onRequestError", {
|
|
2045
|
+
response,
|
|
2046
|
+
request
|
|
2047
|
+
});
|
|
2048
|
+
client.triggerPlugins("onRequestFinished", {
|
|
2049
|
+
response,
|
|
2050
|
+
request
|
|
2051
|
+
});
|
|
2052
|
+
resolve(response);
|
|
2053
|
+
logger.error({
|
|
2054
|
+
title: `Request error`,
|
|
2055
|
+
type: "request",
|
|
2056
|
+
extra: {
|
|
2057
|
+
request,
|
|
2058
|
+
requestId,
|
|
2059
|
+
response
|
|
2060
|
+
}
|
|
2061
|
+
});
|
|
2062
|
+
return response;
|
|
2063
|
+
};
|
|
2064
|
+
}
|
|
2065
|
+
//#endregion
|
|
2066
|
+
//#region src/mocker/mocker.ts
|
|
2067
|
+
var mocker = async ({ request, requestId, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, onResponseProgress, onRequestProgress, onResponseStart, onBeforeRequest, onRequestStart, onSuccess, onAbortError, adapter }) => {
|
|
2068
|
+
if (!request.unstable_mock) throw new RequestProcessingError("Mock should be defined when calling mocker");
|
|
2069
|
+
let thrown = false;
|
|
2070
|
+
const { requestTime = 20, responseTime = 20, totalUploaded = 1e3, totalDownloaded = 1e3, timeout } = request.unstable_mock.config;
|
|
2071
|
+
const { data, error, status, success = true, extra = request.client.adapter.defaultExtra } = await request.unstable_mock.fn({
|
|
2072
|
+
request,
|
|
2073
|
+
requestId
|
|
2074
|
+
});
|
|
2075
|
+
createAbortListener({
|
|
2076
|
+
status: adapter.systemErrorStatus,
|
|
2077
|
+
extra: adapter.systemErrorExtra,
|
|
2078
|
+
onAbort: () => {
|
|
2079
|
+
thrown = true;
|
|
2080
|
+
}
|
|
2081
|
+
});
|
|
2082
|
+
onBeforeRequest();
|
|
2083
|
+
onRequestStart();
|
|
2084
|
+
const progress = (totalTime, totalSize, progressFunction) => new Promise((resolveProgress) => {
|
|
2085
|
+
if (thrown) {
|
|
2086
|
+
resolveProgress(true);
|
|
2087
|
+
return;
|
|
2088
|
+
}
|
|
2089
|
+
const interval = 20;
|
|
2090
|
+
const dataStart = +/* @__PURE__ */ new Date();
|
|
2091
|
+
const intervals = Math.ceil(totalTime / interval);
|
|
2092
|
+
const chunkSize = Math.ceil(totalSize / intervals);
|
|
2093
|
+
let currentlyLoaded = 0;
|
|
2094
|
+
const timer = setInterval(function handleProgressInterval() {
|
|
2095
|
+
if (thrown) {
|
|
2096
|
+
resolveProgress(true);
|
|
2097
|
+
clearInterval(timer);
|
|
2098
|
+
}
|
|
2099
|
+
const currentTime = Math.min(totalTime, +/* @__PURE__ */ new Date() - dataStart);
|
|
2100
|
+
currentlyLoaded += currentlyLoaded + chunkSize >= totalSize ? totalSize - currentlyLoaded : chunkSize;
|
|
2101
|
+
progressFunction({
|
|
2102
|
+
total: totalSize,
|
|
2103
|
+
loaded: currentTime >= totalTime ? totalSize : currentlyLoaded
|
|
2104
|
+
});
|
|
2105
|
+
if (currentTime >= totalTime) {
|
|
2106
|
+
resolveProgress(true);
|
|
2107
|
+
clearInterval(timer);
|
|
2108
|
+
}
|
|
2109
|
+
}, interval);
|
|
2110
|
+
});
|
|
2111
|
+
if (typeof timeout === "number") setTimeout(() => {
|
|
2112
|
+
thrown = true;
|
|
2113
|
+
onTimeoutError({
|
|
2114
|
+
status: 0,
|
|
2115
|
+
extra
|
|
2116
|
+
});
|
|
2117
|
+
}, timeout);
|
|
2118
|
+
if (!thrown) await progress(requestTime, totalUploaded, onRequestProgress);
|
|
2119
|
+
if (!thrown) {
|
|
2120
|
+
onRequestEnd();
|
|
2121
|
+
onResponseStart();
|
|
2122
|
+
}
|
|
2123
|
+
if (!thrown) await progress(responseTime, totalDownloaded, onResponseProgress);
|
|
2124
|
+
if (thrown) onAbortError({
|
|
2125
|
+
status: adapter.systemErrorStatus,
|
|
2126
|
+
extra: adapter.systemErrorExtra
|
|
2127
|
+
});
|
|
2128
|
+
else if (success || error && data) onSuccess({
|
|
2129
|
+
data,
|
|
2130
|
+
error,
|
|
2131
|
+
status,
|
|
2132
|
+
extra
|
|
2133
|
+
});
|
|
2134
|
+
else onError({
|
|
2135
|
+
error,
|
|
2136
|
+
status,
|
|
2137
|
+
extra
|
|
2138
|
+
});
|
|
2139
|
+
if (!thrown) onResponseEnd();
|
|
2140
|
+
};
|
|
2141
|
+
//#endregion
|
|
2142
|
+
//#region src/adapter/adapter.ts
|
|
2143
|
+
var defaultMapper = (value) => value;
|
|
2144
|
+
var Adapter = class {
|
|
2145
|
+
/** Fetching function */
|
|
2146
|
+
unstable_fetcher;
|
|
2147
|
+
/**
|
|
2148
|
+
* ********************
|
|
2149
|
+
* Defaults
|
|
2150
|
+
* ********************
|
|
2151
|
+
*/
|
|
2152
|
+
name;
|
|
2153
|
+
defaultMethod;
|
|
2154
|
+
defaultExtra;
|
|
2155
|
+
systemErrorStatus;
|
|
2156
|
+
systemErrorExtra;
|
|
2157
|
+
defaultRequestOptions;
|
|
2158
|
+
logger;
|
|
2159
|
+
initialized = false;
|
|
2160
|
+
client;
|
|
2161
|
+
unstable_onInitializeCallback;
|
|
2162
|
+
unstable_queryParamsMapperConfig;
|
|
2163
|
+
unstable_headerMapperConfig;
|
|
2164
|
+
unstable_payloadMapperConfig;
|
|
2165
|
+
unstable_endpointMapperConfig;
|
|
2166
|
+
constructor(options) {
|
|
2167
|
+
this.options = options;
|
|
2168
|
+
this.name = options.name;
|
|
2169
|
+
this.defaultMethod = options.defaultMethod;
|
|
2170
|
+
this.defaultExtra = options.defaultExtra;
|
|
2171
|
+
this.systemErrorStatus = options.systemErrorStatus;
|
|
2172
|
+
this.systemErrorExtra = options.systemErrorExtra;
|
|
2173
|
+
this.defaultRequestOptions = options.defaultRequestOptions;
|
|
2174
|
+
}
|
|
2175
|
+
initialize = (client) => {
|
|
2176
|
+
this.logger = client.loggerManager.initialize(client, "Adapter");
|
|
2177
|
+
this.initialized = true;
|
|
2178
|
+
this.client = client;
|
|
2179
|
+
this.unstable_onInitializeCallback?.({ client });
|
|
2180
|
+
return this;
|
|
2181
|
+
};
|
|
2182
|
+
onInitialize = (callback) => {
|
|
2183
|
+
this.unstable_onInitializeCallback = callback;
|
|
2184
|
+
return this;
|
|
2185
|
+
};
|
|
2186
|
+
/**
|
|
2187
|
+
* ********************
|
|
2188
|
+
* Options Setters
|
|
2189
|
+
* ********************
|
|
2190
|
+
*/
|
|
2191
|
+
unstable_internalErrorMapping = (error) => error;
|
|
2192
|
+
/** Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats. */
|
|
2193
|
+
unstable_headerMapper = getAdapterHeaders;
|
|
2194
|
+
/** Method to get request data and transform them to the required format. It handles FormData and JSON by default. */
|
|
2195
|
+
unstable_payloadMapper = getAdapterPayload;
|
|
2196
|
+
/** Method to get the endpoint for the adapter request. */
|
|
2197
|
+
unstable_endpointMapper = defaultMapper;
|
|
2198
|
+
/** Method to get request data and transform them to the required format. */
|
|
2199
|
+
unstable_queryParamsMapper = defaultMapper;
|
|
2200
|
+
/** Get default adapter options for the request. */
|
|
2201
|
+
unstable_getAdapterDefaults;
|
|
2202
|
+
/** Get default request options for the request. */
|
|
2203
|
+
unstable_getRequestDefaults;
|
|
2204
|
+
/**
|
|
2205
|
+
* Get formatted endpoint name of the request.
|
|
2206
|
+
* Helpful in displaying long endpoints like in case of graphql schemas etc.
|
|
2207
|
+
*/
|
|
2208
|
+
unstable_devtoolsEndpointGetter = (endpoint) => endpoint;
|
|
2209
|
+
/**
|
|
2210
|
+
* ********************
|
|
2211
|
+
* Methods
|
|
2212
|
+
* ********************
|
|
2213
|
+
*/
|
|
2214
|
+
setDefaultMethod = (method) => {
|
|
2215
|
+
this.defaultMethod = method;
|
|
2216
|
+
return this;
|
|
2217
|
+
};
|
|
2218
|
+
setDefaultExtra = (extra) => {
|
|
2219
|
+
this.defaultExtra = extra;
|
|
2220
|
+
return this;
|
|
2221
|
+
};
|
|
2222
|
+
setDevtoolsEndpointGetter = (callback) => {
|
|
2223
|
+
this.unstable_devtoolsEndpointGetter = callback;
|
|
2224
|
+
return this;
|
|
2225
|
+
};
|
|
2226
|
+
/**
|
|
2227
|
+
* This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.
|
|
2228
|
+
*/
|
|
2229
|
+
setRequestDefaults = (callback) => {
|
|
2230
|
+
this.unstable_getRequestDefaults = callback;
|
|
2231
|
+
return this;
|
|
2232
|
+
};
|
|
2233
|
+
/**
|
|
2234
|
+
* Set the adapter default options added to every sent request
|
|
2235
|
+
*/
|
|
2236
|
+
setAdapterDefaults = (callback) => {
|
|
2237
|
+
this.unstable_getAdapterDefaults = callback;
|
|
2238
|
+
return this;
|
|
2239
|
+
};
|
|
2240
|
+
setInternalErrorMapping = (callback) => {
|
|
2241
|
+
this.unstable_internalErrorMapping = callback;
|
|
2242
|
+
return this;
|
|
2243
|
+
};
|
|
2244
|
+
/**
|
|
2245
|
+
* Set the custom header mapping function
|
|
2246
|
+
*/
|
|
2247
|
+
setHeaderMapper = (headerMapper) => {
|
|
2248
|
+
this.unstable_headerMapper = ((req) => headerMapper(req, this.unstable_headerMapperConfig));
|
|
2249
|
+
return this;
|
|
2250
|
+
};
|
|
2251
|
+
/**
|
|
2252
|
+
* Set the request payload mapping function which gets triggered before request is send
|
|
2253
|
+
*/
|
|
2254
|
+
setPayloadMapper = (payloadMapper) => {
|
|
2255
|
+
this.unstable_payloadMapper = ((req) => payloadMapper(req, this.unstable_payloadMapperConfig));
|
|
2256
|
+
return this;
|
|
2257
|
+
};
|
|
2258
|
+
/**
|
|
2259
|
+
* Set the request payload mapping function which get triggered before request get sent
|
|
2260
|
+
*/
|
|
2261
|
+
setEndpointMapper = (endpointMapper) => {
|
|
2262
|
+
this.unstable_endpointMapper = ((endpoint) => endpointMapper(endpoint, this.unstable_endpointMapperConfig));
|
|
2263
|
+
return this;
|
|
2264
|
+
};
|
|
2265
|
+
/**
|
|
2266
|
+
* Set the query params mapping function which get triggered before request get sent
|
|
2267
|
+
*/
|
|
2268
|
+
setQueryParamsMapper = (queryParamsMapper) => {
|
|
2269
|
+
this.unstable_queryParamsMapper = ((queryParams) => queryParamsMapper(queryParams, this.unstable_queryParamsMapperConfig));
|
|
2270
|
+
return this;
|
|
2271
|
+
};
|
|
2272
|
+
setQueryParamsMapperConfig = (config) => {
|
|
2273
|
+
this.unstable_queryParamsMapperConfig = config;
|
|
2274
|
+
return this;
|
|
2275
|
+
};
|
|
2276
|
+
setHeaderMapperConfig = (config) => {
|
|
2277
|
+
this.unstable_headerMapperConfig = config;
|
|
2278
|
+
return this;
|
|
2279
|
+
};
|
|
2280
|
+
setEndpointMapperConfig = (config) => {
|
|
2281
|
+
this.unstable_endpointMapperConfig = config;
|
|
2282
|
+
return this;
|
|
2283
|
+
};
|
|
2284
|
+
setPayloadMapperConfig = (config) => {
|
|
2285
|
+
this.unstable_payloadMapperConfig = config;
|
|
2286
|
+
return this;
|
|
2287
|
+
};
|
|
2288
|
+
/**
|
|
2289
|
+
* ********************
|
|
2290
|
+
* Fetching
|
|
2291
|
+
* ********************
|
|
2292
|
+
*/
|
|
2293
|
+
setFetcher(fetcher) {
|
|
2294
|
+
this.unstable_fetcher = fetcher.bind(this);
|
|
2295
|
+
return this;
|
|
2296
|
+
}
|
|
2297
|
+
async fetch(request, requestId) {
|
|
2298
|
+
let startTime;
|
|
2299
|
+
const execute = async (resolve) => {
|
|
2300
|
+
try {
|
|
2301
|
+
if (!this.initialized) throw new RequestProcessingError(`Adapter ${this.options.name} is not initialized`);
|
|
2302
|
+
if (!this.unstable_fetcher) throw new RequestProcessingError(`Fetcher for ${this.options.name} adapter is not set`);
|
|
2303
|
+
this.client.triggerPlugins("onAdapterFetch", {
|
|
2304
|
+
adapter: this,
|
|
2305
|
+
request,
|
|
2306
|
+
requestId
|
|
2307
|
+
});
|
|
2308
|
+
const bindings = await getAdapterBindings({
|
|
2309
|
+
request,
|
|
2310
|
+
requestId,
|
|
2311
|
+
resolve,
|
|
2312
|
+
internalErrorMapping: this.unstable_internalErrorMapping,
|
|
2313
|
+
onStartTime: (time) => {
|
|
2314
|
+
startTime = time;
|
|
2315
|
+
}
|
|
2316
|
+
});
|
|
2317
|
+
if (request.unstable_mock && request.isMockerEnabled && request.client.isMockerEnabled) return await mocker(bindings);
|
|
2318
|
+
return this.unstable_fetcher(bindings);
|
|
2319
|
+
} catch (error) {
|
|
2320
|
+
return getAdapterOnError({
|
|
2321
|
+
request,
|
|
2322
|
+
requestId,
|
|
2323
|
+
startTime: startTime || Date.now(),
|
|
2324
|
+
logger: this.logger,
|
|
2325
|
+
resolve
|
|
2326
|
+
})({
|
|
2327
|
+
error: this.unstable_internalErrorMapping(error),
|
|
2328
|
+
status: this.options.systemErrorStatus,
|
|
2329
|
+
extra: this.options.systemErrorExtra
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
};
|
|
2333
|
+
return new Promise((resolve) => {
|
|
2334
|
+
execute(resolve);
|
|
2335
|
+
});
|
|
2336
|
+
}
|
|
2337
|
+
};
|
|
2338
|
+
//#endregion
|
|
2339
|
+
//#region src/http-adapter/http-adapter.utils.ts
|
|
2340
|
+
var getResponseHeaders = (headersString) => {
|
|
2341
|
+
const arr = headersString.trim().split(/[\r\n]+/);
|
|
2342
|
+
const headers = {};
|
|
2343
|
+
arr.forEach((line) => {
|
|
2344
|
+
const parts = line.split(": ");
|
|
2345
|
+
const header = parts.shift();
|
|
2346
|
+
const value = parts.join(": ");
|
|
2347
|
+
if (header) headers[header] = value;
|
|
2348
|
+
});
|
|
2349
|
+
return headers;
|
|
2350
|
+
};
|
|
2351
|
+
var parseResponse = (response) => {
|
|
2352
|
+
try {
|
|
2353
|
+
return JSON.parse(response);
|
|
2354
|
+
} catch (err) {
|
|
2355
|
+
return response;
|
|
2356
|
+
}
|
|
2357
|
+
};
|
|
2358
|
+
var handleResponse = (responseChunks, responseType, responseEncoding) => {
|
|
2359
|
+
const bufferedResponse = Buffer.concat(responseChunks);
|
|
2360
|
+
switch (responseType) {
|
|
2361
|
+
case "arraybuffer": return bufferedResponse;
|
|
2362
|
+
case "json": return parseResponse(bufferedResponse.toString(responseEncoding));
|
|
2363
|
+
default: return bufferedResponse.toString(responseEncoding);
|
|
2364
|
+
}
|
|
2365
|
+
};
|
|
2366
|
+
var parseErrorResponse = (response) => {
|
|
2367
|
+
return response ? parseResponse(response) : getErrorMessage();
|
|
2368
|
+
};
|
|
2369
|
+
var isValidValue = (options) => {
|
|
2370
|
+
return (value) => {
|
|
2371
|
+
const { skipNull, skipEmptyString } = options;
|
|
2372
|
+
if (skipEmptyString && value === void 0) return false;
|
|
2373
|
+
if (skipEmptyString && value === "") return false;
|
|
2374
|
+
if (skipNull && value === null) return false;
|
|
2375
|
+
return true;
|
|
2376
|
+
};
|
|
2377
|
+
};
|
|
2378
|
+
var encodeValue = (value, { encode, strict }) => {
|
|
2379
|
+
if (encode && strict) return encodeURIComponent(value).replace(/[!'()*]/g, (s) => `%${s.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
2380
|
+
if (encode) return encodeURIComponent(value);
|
|
2381
|
+
return value;
|
|
2382
|
+
};
|
|
2383
|
+
var encodeParams = (key, value, options) => {
|
|
2384
|
+
const shouldSkip = !isValidValue(options)(value);
|
|
2385
|
+
if (!key || shouldSkip) return "";
|
|
2386
|
+
const parsedValue = () => {
|
|
2387
|
+
if (value instanceof Date) return options.dateParser?.(value) || value.toISOString();
|
|
2388
|
+
if (typeof value === "object" && !Array.isArray(value)) return options.objectParser?.(value) || JSON.stringify(value);
|
|
2389
|
+
return String(value);
|
|
2390
|
+
};
|
|
2391
|
+
return `${encodeValue(key, options)}=${encodeValue(parsedValue(), options)}`;
|
|
2392
|
+
};
|
|
2393
|
+
var encodeArray = (key, array, options) => {
|
|
2394
|
+
const { arrayFormat, arraySeparator } = options;
|
|
2395
|
+
return array.filter(isValidValue(options)).reduce((acc, value, index) => {
|
|
2396
|
+
switch (arrayFormat) {
|
|
2397
|
+
case "index": {
|
|
2398
|
+
const keyValue = `${encodeValue(key, options)}[${encodeValue(String(index), options)}]=`;
|
|
2399
|
+
acc.push(`${keyValue}${encodeValue(String(value), options)}`);
|
|
2400
|
+
break;
|
|
2401
|
+
}
|
|
2402
|
+
case "bracket": {
|
|
2403
|
+
const keyValue = `${encodeValue(key, options)}[]=`;
|
|
2404
|
+
acc.push(`${keyValue}${encodeValue(String(value), options)}`);
|
|
2405
|
+
break;
|
|
2406
|
+
}
|
|
2407
|
+
case "comma": {
|
|
2408
|
+
const keyValue = !acc.length && `${encodeValue(key, options)}=` || "";
|
|
2409
|
+
return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(",")];
|
|
2410
|
+
}
|
|
2411
|
+
case "separator": {
|
|
2412
|
+
const keyValue = !acc.length && `${encodeValue(key, options)}=` || "";
|
|
2413
|
+
return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
|
|
2414
|
+
}
|
|
2415
|
+
case "bracket-separator": {
|
|
2416
|
+
const keyValue = !acc.length && `${encodeValue(key, options)}[]=` || "";
|
|
2417
|
+
return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
|
|
2418
|
+
}
|
|
2419
|
+
default: {
|
|
2420
|
+
const keyValue = `${encodeValue(key, options)}=`;
|
|
2421
|
+
acc.push(`${keyValue}${encodeValue(String(value), options)}`);
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
return acc;
|
|
2425
|
+
}, []).join("&");
|
|
2426
|
+
};
|
|
2427
|
+
var stringifyQueryParams = (queryParams, options = stringifyDefaultOptions) => {
|
|
2428
|
+
if (!queryParams || !Object.keys(queryParams).length) return "";
|
|
2429
|
+
if (typeof queryParams === "string") return queryParams[0] === "?" ? queryParams : `?${queryParams}`;
|
|
2430
|
+
const stringified = Object.entries(queryParams).map(([key, value]) => {
|
|
2431
|
+
if (Array.isArray(value)) return encodeArray(key, value, options);
|
|
2432
|
+
return encodeParams(key, value, options);
|
|
2433
|
+
}).filter(Boolean).join("&");
|
|
2434
|
+
if (stringified) return `?${stringified}`;
|
|
2435
|
+
return "";
|
|
2436
|
+
};
|
|
2437
|
+
//#endregion
|
|
2438
|
+
//#region src/http-adapter/http-adapter.constants.ts
|
|
2439
|
+
var defaultTimeout = Time.SEC * 5;
|
|
2440
|
+
var xhrExtra = { headers: {} };
|
|
2441
|
+
//#endregion
|
|
2442
|
+
//#region src/http-adapter/http-adapter.fetch.ts
|
|
2443
|
+
var defaultExtra = xhrExtra;
|
|
2444
|
+
var getAdapter = () => new Adapter({
|
|
2445
|
+
name: "http",
|
|
2446
|
+
defaultMethod: HttpMethods.GET,
|
|
2447
|
+
defaultExtra,
|
|
2448
|
+
systemErrorStatus: 0,
|
|
2449
|
+
systemErrorExtra: defaultExtra
|
|
2450
|
+
}).setQueryParamsMapper(stringifyQueryParams).setFetcher(async ({ request, adapterOptions, headers, payload, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, getAbortController, onResponseProgress, onResponseStart, onBeforeRequest, onRequestStart, onRequestProgress, onSuccess }) => {
|
|
2451
|
+
const { method, client, endpoint, queryParams } = request;
|
|
2452
|
+
const queryString = queryParams ? stringifyQueryParams(queryParams) : "";
|
|
2453
|
+
const fullUrl = `${client.url}${endpoint}${queryString}`;
|
|
2454
|
+
const controller = getAbortController();
|
|
2455
|
+
const { timeout: timeoutMs = defaultTimeout, streaming = false, ...restOptions } = adapterOptions || {};
|
|
2456
|
+
let timedOut = false;
|
|
2457
|
+
let timeoutId;
|
|
2458
|
+
const unmountListener = createAbortListener({
|
|
2459
|
+
status: 0,
|
|
2460
|
+
extra: defaultExtra
|
|
2461
|
+
});
|
|
2462
|
+
if (timeoutMs > 0 && controller) timeoutId = setTimeout(() => {
|
|
2463
|
+
timedOut = true;
|
|
2464
|
+
unmountListener();
|
|
2465
|
+
controller.abort();
|
|
2466
|
+
}, timeoutMs);
|
|
2467
|
+
onBeforeRequest();
|
|
2468
|
+
onRequestStart();
|
|
2469
|
+
try {
|
|
2470
|
+
const init = {
|
|
2471
|
+
method,
|
|
2472
|
+
headers,
|
|
2473
|
+
signal: controller?.signal,
|
|
2474
|
+
...restOptions
|
|
2475
|
+
};
|
|
2476
|
+
if (payload && method !== "GET" && method !== "HEAD") {
|
|
2477
|
+
init.body = payload;
|
|
2478
|
+
if (typeof payload === "string") {
|
|
2479
|
+
const total = new Blob([payload]).size;
|
|
2480
|
+
onRequestProgress({
|
|
2481
|
+
total,
|
|
2482
|
+
loaded: total
|
|
2483
|
+
});
|
|
2484
|
+
}
|
|
2485
|
+
}
|
|
2486
|
+
onRequestEnd();
|
|
2487
|
+
const response = await fetch(fullUrl, init);
|
|
2488
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
2489
|
+
onResponseStart();
|
|
2490
|
+
const responseHeaders = {};
|
|
2491
|
+
response.headers.forEach((value, key) => {
|
|
2492
|
+
responseHeaders[key] = value;
|
|
2493
|
+
});
|
|
2494
|
+
const extra = { headers: responseHeaders };
|
|
2495
|
+
const { status } = response;
|
|
2496
|
+
if (streaming && response.body) {
|
|
2497
|
+
onResponseEnd();
|
|
2498
|
+
unmountListener();
|
|
2499
|
+
if (response.ok) onSuccess({
|
|
2500
|
+
data: response.body,
|
|
2501
|
+
status,
|
|
2502
|
+
extra
|
|
2503
|
+
});
|
|
2504
|
+
else onError({
|
|
2505
|
+
error: parseErrorResponse(await response.text()),
|
|
2506
|
+
status,
|
|
2507
|
+
extra
|
|
2508
|
+
});
|
|
2509
|
+
} else {
|
|
2510
|
+
let body;
|
|
2511
|
+
if (response.body && typeof response.body.getReader === "function") {
|
|
2512
|
+
const reader = response.body.getReader();
|
|
2513
|
+
const contentLength = parseInt(response.headers.get("content-length") || "0", 10);
|
|
2514
|
+
let receivedLength = 0;
|
|
2515
|
+
const chunks = [];
|
|
2516
|
+
while (true) {
|
|
2517
|
+
const { done, value } = await reader.read();
|
|
2518
|
+
if (done) break;
|
|
2519
|
+
chunks.push(value);
|
|
2520
|
+
receivedLength += value.length;
|
|
2521
|
+
onResponseProgress({
|
|
2522
|
+
total: contentLength || receivedLength,
|
|
2523
|
+
loaded: receivedLength
|
|
2524
|
+
});
|
|
2525
|
+
}
|
|
2526
|
+
const allChunks = new Uint8Array(receivedLength);
|
|
2527
|
+
let position = 0;
|
|
2528
|
+
for (const chunk of chunks) {
|
|
2529
|
+
allChunks.set(chunk, position);
|
|
2530
|
+
position += chunk.length;
|
|
2531
|
+
}
|
|
2532
|
+
body = new TextDecoder().decode(allChunks);
|
|
2533
|
+
} else body = await response.text();
|
|
2534
|
+
onResponseEnd();
|
|
2535
|
+
unmountListener();
|
|
2536
|
+
if (response.ok) onSuccess({
|
|
2537
|
+
data: parseResponse(body),
|
|
2538
|
+
status,
|
|
2539
|
+
extra
|
|
2540
|
+
});
|
|
2541
|
+
else onError({
|
|
2542
|
+
error: parseErrorResponse(body),
|
|
2543
|
+
status,
|
|
2544
|
+
extra
|
|
2545
|
+
});
|
|
2546
|
+
}
|
|
2547
|
+
} catch (err) {
|
|
2548
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
2549
|
+
unmountListener();
|
|
2550
|
+
if (controller?.signal?.aborted) {
|
|
2551
|
+
if (timedOut) onTimeoutError({
|
|
2552
|
+
status: 0,
|
|
2553
|
+
extra: defaultExtra
|
|
2554
|
+
});
|
|
2555
|
+
return;
|
|
2556
|
+
}
|
|
2557
|
+
onError({
|
|
2558
|
+
error: err,
|
|
2559
|
+
status: 0,
|
|
2560
|
+
extra: defaultExtra
|
|
2561
|
+
});
|
|
2562
|
+
}
|
|
2563
|
+
});
|
|
2564
|
+
//#endregion
|
|
2565
|
+
//#region src/http-adapter/http-adapter.ts
|
|
2566
|
+
var HttpAdapter = () => {
|
|
2567
|
+
return getAdapter();
|
|
2568
|
+
};
|
|
2569
|
+
//#endregion
|
|
2570
|
+
//#region src/cache/cache.ts
|
|
2571
|
+
/**
|
|
2572
|
+
* Cache class handles the data exchange with the dispatchers.
|
|
2573
|
+
*
|
|
2574
|
+
* @note
|
|
2575
|
+
* Keys used to save the values are created dynamically on the Request class
|
|
2576
|
+
*
|
|
2577
|
+
*/
|
|
2578
|
+
var Cache = class {
|
|
2579
|
+
emitter = new EventEmitter();
|
|
2580
|
+
events;
|
|
2581
|
+
storage;
|
|
2582
|
+
lazyStorage;
|
|
2583
|
+
version;
|
|
2584
|
+
garbageCollectors = /* @__PURE__ */ new Map();
|
|
2585
|
+
logger;
|
|
2586
|
+
client;
|
|
2587
|
+
constructor(options) {
|
|
2588
|
+
this.options = options;
|
|
2589
|
+
const { storage = /* @__PURE__ */ new Map(), lazyStorage, version = "0.0.1" } = options ?? {};
|
|
2590
|
+
this.emitter?.setMaxListeners(1e3);
|
|
2591
|
+
this.events = getCacheEvents(this.emitter);
|
|
2592
|
+
this.storage = storage;
|
|
2593
|
+
this.version = version;
|
|
2594
|
+
this.lazyStorage = lazyStorage;
|
|
2595
|
+
}
|
|
2596
|
+
initialize = (client) => {
|
|
2597
|
+
this.client = client;
|
|
2598
|
+
this.logger = client.loggerManager.initialize(client, "Cache");
|
|
2599
|
+
client.appManager.events.onOnline(() => {
|
|
2600
|
+
[...this.storage.keys()].forEach(this.scheduleGarbageCollector);
|
|
2601
|
+
});
|
|
2602
|
+
[...this.storage.keys()].forEach(this.scheduleGarbageCollector);
|
|
2603
|
+
return this;
|
|
2604
|
+
};
|
|
2605
|
+
/**
|
|
2606
|
+
* Set the cache data to the storage
|
|
2607
|
+
* @param request
|
|
2608
|
+
* @param response
|
|
2609
|
+
* @returns
|
|
2610
|
+
*/
|
|
2611
|
+
set = (request, response) => {
|
|
2612
|
+
this.logger.debug({
|
|
2613
|
+
title: "Processing cache response",
|
|
2614
|
+
type: "system",
|
|
2615
|
+
extra: {
|
|
2616
|
+
request,
|
|
2617
|
+
response
|
|
2618
|
+
}
|
|
2619
|
+
});
|
|
2620
|
+
const { cacheKey, cache, staleTime, cacheTime, scope } = request;
|
|
2621
|
+
const storageKey = scopeKey(cacheKey, scope);
|
|
2622
|
+
const previousCacheData = this.storage.get(storageKey);
|
|
2623
|
+
const processedResponse = typeof response === "function" ? response(previousCacheData || null) : response;
|
|
2624
|
+
const data = getCacheData(previousCacheData, processedResponse);
|
|
2625
|
+
const newCacheData = {
|
|
2626
|
+
...data,
|
|
2627
|
+
scope,
|
|
2628
|
+
staleTime,
|
|
2629
|
+
version: this.version,
|
|
2630
|
+
cacheKey,
|
|
2631
|
+
cacheTime,
|
|
2632
|
+
cached: !!request.cache
|
|
2633
|
+
};
|
|
2634
|
+
const isServerMode = this.client.mode === "server";
|
|
2635
|
+
const isCachingAllowed = cache && (!isServerMode || !!request.scope);
|
|
2636
|
+
if (processedResponse.success && isCachingAllowed) {
|
|
2637
|
+
this.logger.debug({
|
|
2638
|
+
title: "Saving response to cache storage",
|
|
2639
|
+
type: "system",
|
|
2640
|
+
extra: {
|
|
2641
|
+
request,
|
|
2642
|
+
data
|
|
2643
|
+
}
|
|
2644
|
+
});
|
|
2645
|
+
this.storage.set(storageKey, newCacheData);
|
|
2646
|
+
this.lazyStorage?.set(storageKey, newCacheData);
|
|
2647
|
+
this.client.triggerPlugins("onCacheItemChange", {
|
|
2648
|
+
cache: this,
|
|
2649
|
+
cacheKey,
|
|
2650
|
+
prevData: previousCacheData || null,
|
|
2651
|
+
newData: newCacheData
|
|
2652
|
+
});
|
|
2653
|
+
this.scheduleGarbageCollector(storageKey);
|
|
2654
|
+
} else this.logger.debug({
|
|
2655
|
+
title: "Prevented saving response to cache",
|
|
2656
|
+
type: "system",
|
|
2657
|
+
extra: {
|
|
2658
|
+
request,
|
|
2659
|
+
data
|
|
2660
|
+
}
|
|
2661
|
+
});
|
|
2662
|
+
this.logger.debug({
|
|
2663
|
+
title: "Emitting cache response",
|
|
2664
|
+
type: "system",
|
|
2665
|
+
extra: {
|
|
2666
|
+
request,
|
|
2667
|
+
data
|
|
2668
|
+
}
|
|
2669
|
+
});
|
|
2670
|
+
this.events.emitCacheData(newCacheData);
|
|
2671
|
+
};
|
|
2672
|
+
/**
|
|
2673
|
+
* Update the cache data with partial response data
|
|
2674
|
+
* @param request
|
|
2675
|
+
* @param partialResponse
|
|
2676
|
+
* @param isTriggeredExtrenally - informs whether an update was triggered due to internal logic or externally, e.g.
|
|
2677
|
+
* via plugin.
|
|
2678
|
+
* @returns
|
|
2679
|
+
*/
|
|
2680
|
+
update = (request, partialResponse) => {
|
|
2681
|
+
this.logger.debug({
|
|
2682
|
+
title: "Processing cache update",
|
|
2683
|
+
type: "system",
|
|
2684
|
+
extra: {
|
|
2685
|
+
request,
|
|
2686
|
+
partialResponse
|
|
2687
|
+
}
|
|
2688
|
+
});
|
|
2689
|
+
const { cacheKey, scope } = request;
|
|
2690
|
+
const storageKey = scopeKey(cacheKey, scope);
|
|
2691
|
+
const cachedData = this.storage.get(storageKey);
|
|
2692
|
+
const processedResponse = typeof partialResponse === "function" ? partialResponse(cachedData || null) : partialResponse;
|
|
2693
|
+
if (cachedData) this.set(request, {
|
|
2694
|
+
...cachedData,
|
|
2695
|
+
...processedResponse
|
|
2696
|
+
});
|
|
2697
|
+
};
|
|
2698
|
+
/**
|
|
2699
|
+
* Get particular record from storage by cacheKey. It will trigger lazyStorage to emit lazy load event for reading it's data.
|
|
2700
|
+
* @param cacheKey
|
|
2701
|
+
* @returns
|
|
2702
|
+
*/
|
|
2703
|
+
get = (cacheKey) => {
|
|
2704
|
+
this.getLazyResource(cacheKey);
|
|
2705
|
+
return this.storage.get(cacheKey);
|
|
2706
|
+
};
|
|
2707
|
+
/**
|
|
2708
|
+
* Get sync storage keys, lazyStorage keys will not be included
|
|
2709
|
+
* @returns
|
|
2710
|
+
*/
|
|
2711
|
+
keys = () => {
|
|
2712
|
+
const values = this.storage.keys();
|
|
2713
|
+
return Array.from(values);
|
|
2714
|
+
};
|
|
2715
|
+
/**
|
|
2716
|
+
* Delete record from storages and trigger invalidation event
|
|
2717
|
+
* @param cacheKey
|
|
2718
|
+
*/
|
|
2719
|
+
delete = (cacheKey) => {
|
|
2720
|
+
this.logger.debug({
|
|
2721
|
+
title: "Deleting cache element",
|
|
2722
|
+
type: "system",
|
|
2723
|
+
extra: { cacheKey }
|
|
2724
|
+
});
|
|
2725
|
+
this.storage.delete(cacheKey);
|
|
2726
|
+
this.lazyStorage?.delete(cacheKey);
|
|
2727
|
+
this.client.triggerPlugins("onCacheItemDelete", {
|
|
2728
|
+
cache: this,
|
|
2729
|
+
cacheKey
|
|
2730
|
+
});
|
|
2731
|
+
this.events.emitDelete(cacheKey);
|
|
2732
|
+
};
|
|
2733
|
+
/**
|
|
2734
|
+
* Invalidate cache by cacheKey or partial matching with RegExp
|
|
2735
|
+
* It emits invalidation event for each matching cacheKey and sets staleTime to 0 to indicate out of time cache
|
|
2736
|
+
* @param key - cacheKey or Request instance or RegExp for partial matching
|
|
2737
|
+
*/
|
|
2738
|
+
invalidate = (cacheKeys) => {
|
|
2739
|
+
this.logger.debug({
|
|
2740
|
+
title: "Revalidating cache element",
|
|
2741
|
+
type: "system",
|
|
2742
|
+
extra: { cacheKeys }
|
|
2743
|
+
});
|
|
2744
|
+
const onInvalidate = (key) => {
|
|
2745
|
+
const keys = Array.from(this.storage.keys());
|
|
2746
|
+
const handleInvalidation = (invalidateStorageKey, notifyCacheKey = invalidateStorageKey) => {
|
|
2747
|
+
const value = this.storage.get(invalidateStorageKey);
|
|
2748
|
+
if (value) this.storage.set(invalidateStorageKey, {
|
|
2749
|
+
...value,
|
|
2750
|
+
staleTime: 0
|
|
2751
|
+
});
|
|
2752
|
+
this.client.triggerPlugins("onCacheItemInvalidate", {
|
|
2753
|
+
cache: this,
|
|
2754
|
+
cacheKey: notifyCacheKey
|
|
2755
|
+
});
|
|
2756
|
+
this.events.emitInvalidation(notifyCacheKey);
|
|
2757
|
+
};
|
|
2758
|
+
if (key instanceof Request) handleInvalidation(scopeKey(key.cacheKey, key.scope), key.cacheKey);
|
|
2759
|
+
else if (typeof key === "string") handleInvalidation(key);
|
|
2760
|
+
else if (keys.length) keys.forEach((entityKey) => {
|
|
2761
|
+
if (key.test(entityKey)) handleInvalidation(entityKey);
|
|
2762
|
+
});
|
|
2763
|
+
};
|
|
2764
|
+
if (Array.isArray(cacheKeys)) cacheKeys.forEach(onInvalidate.bind(this));
|
|
2765
|
+
else onInvalidate.bind(this)(cacheKeys);
|
|
2766
|
+
};
|
|
2767
|
+
/**
|
|
2768
|
+
* Used to receive data from lazy storage
|
|
2769
|
+
* @param cacheKey
|
|
2770
|
+
*/
|
|
2771
|
+
getLazyResource = async (cacheKey) => {
|
|
2772
|
+
const data = await this.lazyStorage?.get(cacheKey);
|
|
2773
|
+
const syncData = this.storage.get(cacheKey);
|
|
2774
|
+
if (this.lazyStorage && data) {
|
|
2775
|
+
const now = +/* @__PURE__ */ new Date();
|
|
2776
|
+
const isNewestData = syncData ? syncData.responseTimestamp < data.responseTimestamp : true;
|
|
2777
|
+
const isStaleData = data.staleTime <= now - data.responseTimestamp;
|
|
2778
|
+
const isValidLazyData = data.version === this.version;
|
|
2779
|
+
if (!isValidLazyData) this.lazyStorage?.delete(cacheKey);
|
|
2780
|
+
if (isNewestData && !isStaleData && isValidLazyData) {
|
|
2781
|
+
this.storage.set(cacheKey, data);
|
|
2782
|
+
this.events.emitCacheData({
|
|
2783
|
+
...data,
|
|
2784
|
+
cacheKey,
|
|
2785
|
+
cached: true
|
|
2786
|
+
});
|
|
2787
|
+
return data;
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
const isValidData = syncData?.version === this.version;
|
|
2791
|
+
if (syncData && !isValidData) this.delete(cacheKey);
|
|
2792
|
+
return syncData;
|
|
2793
|
+
};
|
|
2794
|
+
/**
|
|
2795
|
+
* Used to receive keys from sync storage and lazy storage
|
|
2796
|
+
* @param cacheKey
|
|
2797
|
+
*/
|
|
2798
|
+
getLazyKeys = async () => {
|
|
2799
|
+
const keys = await this.lazyStorage?.keys() || [];
|
|
2800
|
+
return [...new Set(keys)];
|
|
2801
|
+
};
|
|
2802
|
+
/**
|
|
2803
|
+
* Used to receive keys from sync storage and lazy storage
|
|
2804
|
+
* @param cacheKey
|
|
2805
|
+
*/
|
|
2806
|
+
getAllKeys = async () => {
|
|
2807
|
+
const keys = await this.lazyStorage?.keys();
|
|
2808
|
+
const asyncKeys = Array.from(keys || []);
|
|
2809
|
+
const syncKeys = Array.from(this.storage.keys());
|
|
2810
|
+
return [...new Set([...asyncKeys, ...syncKeys])];
|
|
2811
|
+
};
|
|
2812
|
+
/**
|
|
2813
|
+
* Schedule garbage collection for given key
|
|
2814
|
+
* @param cacheKey
|
|
2815
|
+
* @returns
|
|
2816
|
+
*/
|
|
2817
|
+
scheduleGarbageCollector = (cacheKey) => {
|
|
2818
|
+
const cacheData = this.storage.get(cacheKey);
|
|
2819
|
+
clearTimeout(this.garbageCollectors.get(cacheKey));
|
|
2820
|
+
if (cacheData) {
|
|
2821
|
+
const timeLeft = cacheData.cacheTime + cacheData.responseTimestamp - +/* @__PURE__ */ new Date();
|
|
2822
|
+
if (cacheData.cacheTime === null) this.logger.debug({
|
|
2823
|
+
title: "Cache time is null",
|
|
2824
|
+
type: "system",
|
|
2825
|
+
extra: { cacheKey }
|
|
2826
|
+
});
|
|
2827
|
+
else if (cacheData.cacheTime !== null && JSON.stringify(cacheData.cacheTime) === "null" || cacheData.cacheTime === Infinity) this.logger.debug({
|
|
2828
|
+
title: "Cache time is Infinite",
|
|
2829
|
+
type: "system",
|
|
2830
|
+
extra: { cacheKey }
|
|
2831
|
+
});
|
|
2832
|
+
else if (timeLeft >= 0) this.garbageCollectors.set(cacheKey, setTimeout(() => {
|
|
2833
|
+
if (this.client.appManager.isOnline) {
|
|
2834
|
+
this.logger.info({
|
|
2835
|
+
title: "Garbage collecting cache data",
|
|
2836
|
+
type: "system",
|
|
2837
|
+
extra: { cacheKey }
|
|
2838
|
+
});
|
|
2839
|
+
this.delete(cacheKey);
|
|
2840
|
+
}
|
|
2841
|
+
}, timeLeft));
|
|
2842
|
+
else if (this.client.appManager.isOnline) {
|
|
2843
|
+
this.logger.info({
|
|
2844
|
+
title: "Garbage collecting cache data",
|
|
2845
|
+
type: "system",
|
|
2846
|
+
extra: { cacheKey }
|
|
2847
|
+
});
|
|
2848
|
+
this.delete(cacheKey);
|
|
2849
|
+
}
|
|
2850
|
+
}
|
|
2851
|
+
};
|
|
2852
|
+
/**
|
|
2853
|
+
* Clear cache storages
|
|
2854
|
+
*/
|
|
2855
|
+
clear = async () => {
|
|
2856
|
+
this.garbageCollectors.forEach((timeout) => clearTimeout(timeout));
|
|
2857
|
+
this.storage.clear();
|
|
2858
|
+
};
|
|
2859
|
+
};
|
|
2860
|
+
//#endregion
|
|
2861
|
+
//#region src/cache/cache.utils.ts
|
|
2862
|
+
var getCacheData = (previousResponse, response) => {
|
|
2863
|
+
const { data, success } = response;
|
|
2864
|
+
const previousData = !success && previousResponse ? previousResponse.data : null;
|
|
2865
|
+
const computedData = data || previousData;
|
|
2866
|
+
return {
|
|
2867
|
+
...response,
|
|
2868
|
+
data: computedData
|
|
2869
|
+
};
|
|
2870
|
+
};
|
|
2871
|
+
var getInvalidateKey = () => {
|
|
2872
|
+
return `invalidate`;
|
|
2873
|
+
};
|
|
2874
|
+
var getInvalidateByKey = (key) => {
|
|
2875
|
+
return `${key}_invalidate`;
|
|
2876
|
+
};
|
|
2877
|
+
var getDeleteKey = () => {
|
|
2878
|
+
return `delete`;
|
|
2879
|
+
};
|
|
2880
|
+
var getDeleteByKey = (key) => {
|
|
2881
|
+
return `${key}_delete`;
|
|
2882
|
+
};
|
|
2883
|
+
var getCacheByKey = (key) => {
|
|
2884
|
+
return `${key}_cache`;
|
|
2885
|
+
};
|
|
2886
|
+
var getCacheKey = () => {
|
|
2887
|
+
return `cache`;
|
|
2888
|
+
};
|
|
2889
|
+
//#endregion
|
|
2890
|
+
//#region src/cache/cache.events.ts
|
|
2891
|
+
var getCacheEvents = (emitter) => ({
|
|
2892
|
+
emitCacheData: (data, isTriggeredExternally = false) => {
|
|
2893
|
+
emitter.emit(getCacheKey(), data, isTriggeredExternally);
|
|
2894
|
+
emitter.emit(getCacheByKey(data.cacheKey), data, isTriggeredExternally);
|
|
2895
|
+
},
|
|
2896
|
+
emitInvalidation: (cacheKey, isTriggeredExternally = false) => {
|
|
2897
|
+
emitter.emit(getInvalidateKey(), cacheKey, isTriggeredExternally);
|
|
2898
|
+
emitter.emit(getInvalidateByKey(cacheKey), isTriggeredExternally);
|
|
2899
|
+
},
|
|
2900
|
+
emitDelete: (cacheKey, isTriggeredExternally = false) => {
|
|
2901
|
+
emitter.emit(getDeleteKey(), cacheKey, isTriggeredExternally);
|
|
2902
|
+
emitter.emit(getDeleteByKey(cacheKey), isTriggeredExternally);
|
|
2903
|
+
},
|
|
2904
|
+
onData: (callback) => {
|
|
2905
|
+
emitter.on(getCacheKey(), callback);
|
|
2906
|
+
return () => emitter.removeListener(getCacheKey(), callback);
|
|
2907
|
+
},
|
|
2908
|
+
onDataByKey: (cacheKey, callback) => {
|
|
2909
|
+
emitter.on(getCacheByKey(cacheKey), callback);
|
|
2910
|
+
return () => emitter.removeListener(getCacheByKey(cacheKey), callback);
|
|
2911
|
+
},
|
|
2912
|
+
onInvalidate: (callback) => {
|
|
2913
|
+
emitter.on(getInvalidateKey(), callback);
|
|
2914
|
+
return () => emitter.removeListener(getInvalidateKey(), callback);
|
|
2915
|
+
},
|
|
2916
|
+
onInvalidateByKey: (cacheKey, callback) => {
|
|
2917
|
+
emitter.on(getInvalidateByKey(cacheKey), callback);
|
|
2918
|
+
return () => emitter.removeListener(getInvalidateByKey(cacheKey), callback);
|
|
2919
|
+
},
|
|
2920
|
+
onDelete: (callback) => {
|
|
2921
|
+
emitter.on(getDeleteKey(), callback);
|
|
2922
|
+
return () => emitter.removeListener(getDeleteKey(), callback);
|
|
2923
|
+
},
|
|
2924
|
+
onDeleteByKey: (cacheKey, callback) => {
|
|
2925
|
+
emitter.on(getDeleteByKey(cacheKey), callback);
|
|
2926
|
+
return () => emitter.removeListener(getDeleteByKey(cacheKey), callback);
|
|
2927
|
+
}
|
|
2928
|
+
});
|
|
2929
|
+
//#endregion
|
|
2930
|
+
//#region src/dispatcher/dispatcher.constants.ts
|
|
2931
|
+
var DispatcherMode = /* @__PURE__ */ function(DispatcherMode) {
|
|
2932
|
+
DispatcherMode["ONE_BY_ONE"] = "one-by-one";
|
|
2933
|
+
DispatcherMode["ALL_AT_ONCE"] = "all-at-once";
|
|
2934
|
+
DispatcherMode["PREVIOUS_CANCELED"] = "previous-canceled";
|
|
2935
|
+
DispatcherMode["DEDUPLICATED"] = "deduplicated";
|
|
2936
|
+
return DispatcherMode;
|
|
2937
|
+
}({});
|
|
2938
|
+
//#endregion
|
|
2939
|
+
//#region src/dispatcher/dispatcher.events.ts
|
|
2940
|
+
var getDispatcherEvents = (emitter) => ({
|
|
2941
|
+
emitDrained: (values, isTriggeredExternally) => {
|
|
2942
|
+
emitter.emit(getDispatcherDrainedKey(), values, isTriggeredExternally);
|
|
2943
|
+
emitter.emit(getDispatcherDrainedByKey(values.queryKey), values, isTriggeredExternally);
|
|
2944
|
+
},
|
|
2945
|
+
emitQueueStatusChanged: (values, isTriggeredExternally) => {
|
|
2946
|
+
emitter.emit(getDispatcherStatusKey(), values, isTriggeredExternally);
|
|
2947
|
+
emitter.emit(getDispatcherStatusByKey(values.queryKey), values, isTriggeredExternally);
|
|
2948
|
+
},
|
|
2949
|
+
emitQueueChanged: (values, isTriggeredExternally) => {
|
|
2950
|
+
emitter.emit(getDispatcherChangeKey(), values, isTriggeredExternally);
|
|
2951
|
+
emitter.emit(getDispatcherChangeByKey(values.queryKey), values, isTriggeredExternally);
|
|
2952
|
+
},
|
|
2953
|
+
onDrained: (callback) => {
|
|
2954
|
+
emitter.on(getDispatcherDrainedKey(), callback);
|
|
2955
|
+
return () => emitter.removeListener(getDispatcherDrainedKey(), callback);
|
|
2956
|
+
},
|
|
2957
|
+
onDrainedByKey: (queryKey, callback) => {
|
|
2958
|
+
emitter.on(getDispatcherDrainedByKey(queryKey), callback);
|
|
2959
|
+
return () => emitter.removeListener(getDispatcherDrainedByKey(queryKey), callback);
|
|
2960
|
+
},
|
|
2961
|
+
onQueueStatusChange: (callback) => {
|
|
2962
|
+
emitter.on(getDispatcherStatusKey(), callback);
|
|
2963
|
+
return () => emitter.removeListener(getDispatcherStatusKey(), callback);
|
|
2964
|
+
},
|
|
2965
|
+
onQueueStatusChangeByKey: (queryKey, callback) => {
|
|
2966
|
+
emitter.on(getDispatcherStatusByKey(queryKey), callback);
|
|
2967
|
+
return () => emitter.removeListener(getDispatcherStatusByKey(queryKey), callback);
|
|
2968
|
+
},
|
|
2969
|
+
onQueueChange: (callback) => {
|
|
2970
|
+
emitter.on(getDispatcherChangeKey(), callback);
|
|
2971
|
+
return () => emitter.removeListener(getDispatcherChangeKey(), callback);
|
|
2972
|
+
},
|
|
2973
|
+
onQueueChangeByKey: (queryKey, callback) => {
|
|
2974
|
+
emitter.on(getDispatcherChangeByKey(queryKey), callback);
|
|
2975
|
+
return () => emitter.removeListener(getDispatcherChangeByKey(queryKey), callback);
|
|
2976
|
+
}
|
|
2977
|
+
});
|
|
2978
|
+
//#endregion
|
|
2979
|
+
//#region src/dispatcher/dispatcher.ts
|
|
2980
|
+
/**
|
|
2981
|
+
* Dispatcher controls and manages the requests that are going to be executed with adapter. It manages them based on the options provided with request.
|
|
2982
|
+
* This class can also run them with different modes like deduplication, cancelation, queueing or run-all-at-once mode. With it's help we can pause,
|
|
2983
|
+
* stop, start and cancel requests.
|
|
2984
|
+
*/
|
|
2985
|
+
var Dispatcher = class {
|
|
2986
|
+
emitter = new EventEmitter();
|
|
2987
|
+
events = getDispatcherEvents(this.emitter);
|
|
2988
|
+
storage = /* @__PURE__ */ new Map();
|
|
2989
|
+
requestCount = /* @__PURE__ */ new Map();
|
|
2990
|
+
runningRequests = /* @__PURE__ */ new Map();
|
|
2991
|
+
logger;
|
|
2992
|
+
client;
|
|
2993
|
+
constructor(options) {
|
|
2994
|
+
this.options = options;
|
|
2995
|
+
this.emitter?.setMaxListeners(1e3);
|
|
2996
|
+
if (this.options?.storage) this.storage = this.options.storage;
|
|
2997
|
+
}
|
|
2998
|
+
isRequestJSON = (request) => {
|
|
2999
|
+
return !(request instanceof Request);
|
|
3000
|
+
};
|
|
3001
|
+
initialize = (client) => {
|
|
3002
|
+
this.client = client;
|
|
3003
|
+
this.logger = client.loggerManager.initialize(client, "Dispatcher");
|
|
3004
|
+
this.client.appManager.events.onOnline(() => {
|
|
3005
|
+
this.flush();
|
|
3006
|
+
});
|
|
3007
|
+
return this;
|
|
3008
|
+
};
|
|
3009
|
+
/**
|
|
3010
|
+
* Start request handling by queryKey
|
|
3011
|
+
*/
|
|
3012
|
+
start = (queryKey) => {
|
|
3013
|
+
const queue = this.getQueue(queryKey);
|
|
3014
|
+
queue.stopped = false;
|
|
3015
|
+
this.setQueue(queryKey, queue);
|
|
3016
|
+
this.flushQueue(queryKey);
|
|
3017
|
+
this.client.triggerPlugins("onDispatcherQueueRunning", {
|
|
3018
|
+
dispatcher: this,
|
|
3019
|
+
queue,
|
|
3020
|
+
status: "running"
|
|
3021
|
+
});
|
|
3022
|
+
this.events.emitQueueStatusChanged(queue);
|
|
3023
|
+
};
|
|
3024
|
+
/**
|
|
3025
|
+
* Pause request queue, but do not cancel already started requests
|
|
3026
|
+
*/
|
|
3027
|
+
pause = (queryKey) => {
|
|
3028
|
+
const queue = this.getQueue(queryKey);
|
|
3029
|
+
queue.stopped = true;
|
|
3030
|
+
this.setQueue(queryKey, queue);
|
|
3031
|
+
this.client.triggerPlugins("onDispatcherQueueRunning", {
|
|
3032
|
+
dispatcher: this,
|
|
3033
|
+
queue,
|
|
3034
|
+
status: "paused"
|
|
3035
|
+
});
|
|
3036
|
+
this.events.emitQueueStatusChanged(queue);
|
|
3037
|
+
};
|
|
3038
|
+
/**
|
|
3039
|
+
* Stop request queue and cancel all started requests - those will be treated like not started
|
|
3040
|
+
*/
|
|
3041
|
+
stop = (queryKey) => {
|
|
3042
|
+
const queue = this.getQueue(queryKey);
|
|
3043
|
+
queue.stopped = true;
|
|
3044
|
+
this.setQueue(queryKey, queue);
|
|
3045
|
+
this.cancelRunningRequests(queryKey);
|
|
3046
|
+
this.client.triggerPlugins("onDispatcherQueueRunning", {
|
|
3047
|
+
dispatcher: this,
|
|
3048
|
+
queue,
|
|
3049
|
+
status: "stopped"
|
|
3050
|
+
});
|
|
3051
|
+
this.events.emitQueueStatusChanged(queue);
|
|
3052
|
+
};
|
|
3053
|
+
/**
|
|
3054
|
+
* Return all
|
|
3055
|
+
*/
|
|
3056
|
+
getQueuesKeys = () => {
|
|
3057
|
+
return Array.from(this.storage.keys());
|
|
3058
|
+
};
|
|
3059
|
+
/**
|
|
3060
|
+
* Return queue state object.
|
|
3061
|
+
* Automatically reconstructs any serialized (JSON) requests back into
|
|
3062
|
+
* proper Request class instances so the rest of the pipeline can rely on
|
|
3063
|
+
* having a real `RequestInstance`.
|
|
3064
|
+
*/
|
|
3065
|
+
getQueue = (queryKey) => {
|
|
3066
|
+
const initialQueueState = {
|
|
3067
|
+
queryKey,
|
|
3068
|
+
requests: [],
|
|
3069
|
+
stopped: false
|
|
3070
|
+
};
|
|
3071
|
+
const storedEntity = this.storage.get(queryKey);
|
|
3072
|
+
if (!storedEntity) return initialQueueState;
|
|
3073
|
+
const resolvedRequests = storedEntity.requests.map((item) => {
|
|
3074
|
+
if (this.isRequestJSON(item.request)) return {
|
|
3075
|
+
...item,
|
|
3076
|
+
request: this.client.fromJSON(item.request)
|
|
3077
|
+
};
|
|
3078
|
+
return item;
|
|
3079
|
+
});
|
|
3080
|
+
return {
|
|
3081
|
+
...storedEntity,
|
|
3082
|
+
requests: resolvedRequests
|
|
3083
|
+
};
|
|
3084
|
+
};
|
|
3085
|
+
/**
|
|
3086
|
+
* Return request from queue state
|
|
3087
|
+
*/
|
|
3088
|
+
getRequest = (queryKey, requestId) => {
|
|
3089
|
+
const initialQueueState = {
|
|
3090
|
+
queryKey,
|
|
3091
|
+
requests: [],
|
|
3092
|
+
stopped: false
|
|
3093
|
+
};
|
|
3094
|
+
return (this.storage.get(queryKey) || initialQueueState).requests.find((req) => req.requestId === requestId);
|
|
3095
|
+
};
|
|
3096
|
+
/**
|
|
3097
|
+
* Get value of the active queue status based on the stopped status
|
|
3098
|
+
*/
|
|
3099
|
+
getIsActiveQueue = (queryKey) => {
|
|
3100
|
+
const queue = this.getQueue(queryKey);
|
|
3101
|
+
const hasAvailableRequests = queue.requests.some((req) => !req.stopped);
|
|
3102
|
+
const isRunningQueue = !queue.stopped;
|
|
3103
|
+
return hasAvailableRequests && isRunningQueue;
|
|
3104
|
+
};
|
|
3105
|
+
/**
|
|
3106
|
+
* Add new element to storage
|
|
3107
|
+
*/
|
|
3108
|
+
addQueueItem = (queryKey, element) => {
|
|
3109
|
+
const queue = this.getQueue(queryKey);
|
|
3110
|
+
queue.requests.push(element);
|
|
3111
|
+
this.client.triggerPlugins("onDispatcherItemAdded", {
|
|
3112
|
+
dispatcher: this,
|
|
3113
|
+
queue,
|
|
3114
|
+
queueItem: element
|
|
3115
|
+
});
|
|
3116
|
+
this.setQueue(queryKey, queue);
|
|
3117
|
+
};
|
|
3118
|
+
/**
|
|
3119
|
+
* Set new queue storage value
|
|
3120
|
+
*/
|
|
3121
|
+
setQueue = (queryKey, queue) => {
|
|
3122
|
+
this.storage.set(queryKey, queue);
|
|
3123
|
+
this.client.triggerPlugins("onDispatcherQueueCreated", {
|
|
3124
|
+
dispatcher: this,
|
|
3125
|
+
queue
|
|
3126
|
+
});
|
|
3127
|
+
this.events.emitQueueChanged(queue);
|
|
3128
|
+
return queue;
|
|
3129
|
+
};
|
|
3130
|
+
/**
|
|
3131
|
+
* Clear requests from queue cache
|
|
3132
|
+
*/
|
|
3133
|
+
clearQueue = (queryKey) => {
|
|
3134
|
+
const newQueue = {
|
|
3135
|
+
queryKey,
|
|
3136
|
+
requests: [],
|
|
3137
|
+
stopped: this.getQueue(queryKey).stopped
|
|
3138
|
+
};
|
|
3139
|
+
this.storage.set(queryKey, newQueue);
|
|
3140
|
+
this.client.triggerPlugins("onDispatcherQueueCleared", {
|
|
3141
|
+
dispatcher: this,
|
|
3142
|
+
queue: newQueue
|
|
3143
|
+
});
|
|
3144
|
+
this.events.emitQueueChanged(newQueue);
|
|
3145
|
+
this.events.emitDrained(newQueue);
|
|
3146
|
+
return newQueue;
|
|
3147
|
+
};
|
|
3148
|
+
/**
|
|
3149
|
+
* Method used to flush the queue requests
|
|
3150
|
+
*/
|
|
3151
|
+
flushQueue = async (queryKey) => {
|
|
3152
|
+
const queue = this.getQueue(queryKey);
|
|
3153
|
+
const runningRequests = this.getRunningRequests(queryKey);
|
|
3154
|
+
const queueItem = queue.requests.find((request) => !request.stopped);
|
|
3155
|
+
const isStopped = queue && queue.stopped;
|
|
3156
|
+
const isOffline = !this.client.appManager.isOnline;
|
|
3157
|
+
const isConcurrent = !queueItem?.request.queued;
|
|
3158
|
+
const isInactive = !runningRequests.length;
|
|
3159
|
+
const isEmpty = !queueItem;
|
|
3160
|
+
if (isStopped || isOffline || isEmpty) this.logger.debug({
|
|
3161
|
+
title: "Skipping queue trigger",
|
|
3162
|
+
type: "system",
|
|
3163
|
+
extra: {
|
|
3164
|
+
isStopped,
|
|
3165
|
+
isOffline,
|
|
3166
|
+
isEmpty
|
|
3167
|
+
}
|
|
3168
|
+
});
|
|
3169
|
+
else if (isConcurrent) queue.requests.forEach((element) => {
|
|
3170
|
+
if (!this.hasRunningRequest(queryKey, element.requestId)) this.performRequest(element);
|
|
3171
|
+
});
|
|
3172
|
+
else if (isInactive) {
|
|
3173
|
+
await this.performRequest(queueItem);
|
|
3174
|
+
this.flushQueue(queryKey);
|
|
3175
|
+
}
|
|
3176
|
+
};
|
|
3177
|
+
/**
|
|
3178
|
+
* Flush all available requests from all queues
|
|
3179
|
+
*/
|
|
3180
|
+
flush = async () => {
|
|
3181
|
+
const keys = this.getQueuesKeys();
|
|
3182
|
+
for (const key of keys) if (this.getQueue(key)) this.flushQueue(key);
|
|
3183
|
+
};
|
|
3184
|
+
/**
|
|
3185
|
+
* Clear all running requests and storage
|
|
3186
|
+
*/
|
|
3187
|
+
clear = () => {
|
|
3188
|
+
this.getQueuesKeys().forEach((queryKey) => this.cancelRunningRequests(queryKey));
|
|
3189
|
+
this.runningRequests.clear();
|
|
3190
|
+
this.storage.clear();
|
|
3191
|
+
this.client.triggerPlugins("onDispatcherCleared", { dispatcher: this });
|
|
3192
|
+
};
|
|
3193
|
+
/**
|
|
3194
|
+
* Start particular request
|
|
3195
|
+
*/
|
|
3196
|
+
startRequest = (queryKey, requestId) => {
|
|
3197
|
+
const queue = this.getQueue(queryKey);
|
|
3198
|
+
const request = queue.requests.find((element) => element.requestId === requestId);
|
|
3199
|
+
if (request) {
|
|
3200
|
+
request.stopped = false;
|
|
3201
|
+
this.setQueue(queryKey, queue);
|
|
3202
|
+
this.flushQueue(queryKey);
|
|
3203
|
+
this.events.emitQueueStatusChanged(queue);
|
|
3204
|
+
}
|
|
3205
|
+
};
|
|
3206
|
+
/**
|
|
3207
|
+
* Stop particular request
|
|
3208
|
+
*/
|
|
3209
|
+
stopRequest = (queryKey, requestId) => {
|
|
3210
|
+
const queue = this.getQueue(queryKey);
|
|
3211
|
+
const request = queue.requests.find((element) => element.requestId === requestId);
|
|
3212
|
+
if (request) {
|
|
3213
|
+
request.stopped = true;
|
|
3214
|
+
this.setQueue(queryKey, queue);
|
|
3215
|
+
this.cancelRunningRequest(queryKey, requestId);
|
|
3216
|
+
this.events.emitQueueStatusChanged(queue);
|
|
3217
|
+
}
|
|
3218
|
+
};
|
|
3219
|
+
/**
|
|
3220
|
+
* Get currently running requests from all queryKeys
|
|
3221
|
+
*/
|
|
3222
|
+
getAllRunningRequests = () => {
|
|
3223
|
+
return Array.from(this.runningRequests.values()).flat();
|
|
3224
|
+
};
|
|
3225
|
+
/**
|
|
3226
|
+
* Get currently running requests
|
|
3227
|
+
*/
|
|
3228
|
+
getRunningRequests = (queryKey) => {
|
|
3229
|
+
return this.runningRequests.get(queryKey) || [];
|
|
3230
|
+
};
|
|
3231
|
+
/**
|
|
3232
|
+
* Get running request by id
|
|
3233
|
+
*/
|
|
3234
|
+
getRunningRequest = (queryKey, requestId) => {
|
|
3235
|
+
return this.getRunningRequests(queryKey).find((req) => req.requestId === requestId);
|
|
3236
|
+
};
|
|
3237
|
+
/**
|
|
3238
|
+
* Add request to the running requests list
|
|
3239
|
+
*/
|
|
3240
|
+
addRunningRequest = (queryKey, requestId, request) => {
|
|
3241
|
+
const newRunningRequest = {
|
|
3242
|
+
requestId,
|
|
3243
|
+
request,
|
|
3244
|
+
timestamp: Date.now()
|
|
3245
|
+
};
|
|
3246
|
+
const runningRequests = this.getRunningRequests(queryKey);
|
|
3247
|
+
runningRequests.push(newRunningRequest);
|
|
3248
|
+
this.runningRequests.set(queryKey, runningRequests);
|
|
3249
|
+
return newRunningRequest;
|
|
3250
|
+
};
|
|
3251
|
+
/**
|
|
3252
|
+
* Get the value based on the currently running requests
|
|
3253
|
+
*/
|
|
3254
|
+
hasRunningRequests = (queryKey) => {
|
|
3255
|
+
return !!this.getRunningRequests(queryKey).length;
|
|
3256
|
+
};
|
|
3257
|
+
/**
|
|
3258
|
+
* Check if request is currently processing
|
|
3259
|
+
*/
|
|
3260
|
+
hasRunningRequest = (queryKey, requestId) => {
|
|
3261
|
+
return !!this.getRunningRequests(queryKey).find((req) => req.requestId === requestId);
|
|
3262
|
+
};
|
|
3263
|
+
/**
|
|
3264
|
+
* Cancel all started requests, but do NOT remove it from main storage
|
|
3265
|
+
*/
|
|
3266
|
+
cancelRunningRequests = (queryKey) => {
|
|
3267
|
+
this.runningRequests.get(queryKey)?.forEach((req) => {
|
|
3268
|
+
const ak = scopeKey(req.request.abortKey, req.request.scope);
|
|
3269
|
+
this.client.requestManager.abortByRequestId(ak, req.requestId);
|
|
3270
|
+
});
|
|
3271
|
+
this.deleteRunningRequests(queryKey);
|
|
3272
|
+
};
|
|
3273
|
+
/**
|
|
3274
|
+
* Cancel started request, but do NOT remove it from main storage
|
|
3275
|
+
*/
|
|
3276
|
+
cancelRunningRequest = (queryKey, requestId) => {
|
|
3277
|
+
const requests = this.getRunningRequests(queryKey).filter((request) => {
|
|
3278
|
+
if (request.requestId === requestId) {
|
|
3279
|
+
const ak = scopeKey(request.request.abortKey, request.request.scope);
|
|
3280
|
+
this.client.requestManager.abortByRequestId(ak, request.requestId);
|
|
3281
|
+
return false;
|
|
3282
|
+
}
|
|
3283
|
+
return true;
|
|
3284
|
+
});
|
|
3285
|
+
this.runningRequests.set(queryKey, requests);
|
|
3286
|
+
};
|
|
3287
|
+
/**
|
|
3288
|
+
* Delete all started requests, but do NOT clear it from queue and do NOT cancel them
|
|
3289
|
+
*/
|
|
3290
|
+
deleteRunningRequests = (queryKey) => {
|
|
3291
|
+
this.runningRequests.set(queryKey, []);
|
|
3292
|
+
};
|
|
3293
|
+
/**
|
|
3294
|
+
* Delete request by id, but do NOT clear it from queue and do NOT cancel them
|
|
3295
|
+
*/
|
|
3296
|
+
deleteRunningRequest = (queryKey, requestId) => {
|
|
3297
|
+
const runningRequests = this.getRunningRequests(queryKey);
|
|
3298
|
+
this.runningRequests.set(queryKey, runningRequests.filter((req) => req.requestId !== requestId));
|
|
3299
|
+
};
|
|
3300
|
+
/**
|
|
3301
|
+
* Get count of requests from the same queryKey
|
|
3302
|
+
*/
|
|
3303
|
+
getQueueRequestCount = (queryKey) => {
|
|
3304
|
+
return this.requestCount.get(queryKey) || 0;
|
|
3305
|
+
};
|
|
3306
|
+
/**
|
|
3307
|
+
* Add request count to the queryKey
|
|
3308
|
+
*/
|
|
3309
|
+
incrementQueueRequestCount = (queryKey) => {
|
|
3310
|
+
const count = this.requestCount.get(queryKey) || 0;
|
|
3311
|
+
this.requestCount.set(queryKey, count + 1);
|
|
3312
|
+
};
|
|
3313
|
+
/**
|
|
3314
|
+
* Create storage element from request
|
|
3315
|
+
*/
|
|
3316
|
+
createStorageItem = (request) => {
|
|
3317
|
+
return {
|
|
3318
|
+
requestId: this.client.unstable_requestIdMapper(request),
|
|
3319
|
+
timestamp: +/* @__PURE__ */ new Date(),
|
|
3320
|
+
request,
|
|
3321
|
+
retries: 0,
|
|
3322
|
+
stopped: false,
|
|
3323
|
+
resolved: false
|
|
3324
|
+
};
|
|
3325
|
+
};
|
|
3326
|
+
/**
|
|
3327
|
+
* Add request to the dispatcher handler
|
|
3328
|
+
*/
|
|
3329
|
+
add = (request) => {
|
|
3330
|
+
const queryKey = scopeKey(request.queryKey, request.scope);
|
|
3331
|
+
const storageItem = this.createStorageItem(request);
|
|
3332
|
+
const { requestId } = storageItem;
|
|
3333
|
+
const [latestRequest] = this.getQueue(queryKey).requests.slice(-1);
|
|
3334
|
+
const requestType = getRequestType(request, latestRequest);
|
|
3335
|
+
this.logger.debug({
|
|
3336
|
+
title: "Adding request to queue",
|
|
3337
|
+
type: "system",
|
|
3338
|
+
extra: {
|
|
3339
|
+
requestType,
|
|
3340
|
+
request,
|
|
3341
|
+
requestId
|
|
3342
|
+
}
|
|
3343
|
+
});
|
|
3344
|
+
switch (requestType) {
|
|
3345
|
+
case DispatcherMode.ONE_BY_ONE:
|
|
3346
|
+
this.addQueueItem(queryKey, storageItem);
|
|
3347
|
+
this.flushQueue(queryKey);
|
|
3348
|
+
return requestId;
|
|
3349
|
+
case DispatcherMode.PREVIOUS_CANCELED:
|
|
3350
|
+
this.cancelRunningRequests(queryKey);
|
|
3351
|
+
this.clearQueue(queryKey);
|
|
3352
|
+
this.addQueueItem(queryKey, storageItem);
|
|
3353
|
+
this.flushQueue(queryKey);
|
|
3354
|
+
return requestId;
|
|
3355
|
+
case DispatcherMode.DEDUPLICATED:
|
|
3356
|
+
this.client.requestManager.events.emitDeduplicated({
|
|
3357
|
+
request: latestRequest.request,
|
|
3358
|
+
requestId,
|
|
3359
|
+
deduplicatedRequest: request
|
|
3360
|
+
});
|
|
3361
|
+
return latestRequest.requestId;
|
|
3362
|
+
default:
|
|
3363
|
+
this.addQueueItem(queryKey, storageItem);
|
|
3364
|
+
this.flushQueue(queryKey);
|
|
3365
|
+
return requestId;
|
|
3366
|
+
}
|
|
3367
|
+
};
|
|
3368
|
+
/**
|
|
3369
|
+
* Delete from the storage and cancel request
|
|
3370
|
+
*/
|
|
3371
|
+
delete = (queryKey, requestId, abortKey) => {
|
|
3372
|
+
this.logger.debug({
|
|
3373
|
+
title: "Deleting request",
|
|
3374
|
+
type: "system",
|
|
3375
|
+
extra: {
|
|
3376
|
+
queryKey,
|
|
3377
|
+
requestId,
|
|
3378
|
+
abortKey
|
|
3379
|
+
}
|
|
3380
|
+
});
|
|
3381
|
+
const queue = this.getQueue(queryKey);
|
|
3382
|
+
const queueItem = queue.requests.find((req) => req.requestId === requestId);
|
|
3383
|
+
if (!queueItem) return;
|
|
3384
|
+
queue.requests = queue.requests.filter((req) => req.requestId !== requestId);
|
|
3385
|
+
this.storage.set(queryKey, queue);
|
|
3386
|
+
if (this.hasRunningRequest(queryKey, requestId)) {
|
|
3387
|
+
this.deleteRunningRequest(queryKey, requestId);
|
|
3388
|
+
this.client.requestManager.abortByRequestId(abortKey, requestId);
|
|
3389
|
+
}
|
|
3390
|
+
this.client.triggerPlugins("onDispatcherItemDeleted", {
|
|
3391
|
+
queue,
|
|
3392
|
+
dispatcher: this,
|
|
3393
|
+
queueItem
|
|
3394
|
+
});
|
|
3395
|
+
this.events.emitQueueChanged(queue);
|
|
3396
|
+
this.client.requestManager.events.emitRemove({
|
|
3397
|
+
requestId,
|
|
3398
|
+
request: queueItem.request,
|
|
3399
|
+
resolved: queueItem.resolved
|
|
3400
|
+
});
|
|
3401
|
+
if (!queue.requests.length) {
|
|
3402
|
+
this.client.triggerPlugins("onDispatcherQueueDrained", {
|
|
3403
|
+
queue,
|
|
3404
|
+
dispatcher: this
|
|
3405
|
+
});
|
|
3406
|
+
this.events.emitDrained(queue);
|
|
3407
|
+
}
|
|
3408
|
+
return queue;
|
|
3409
|
+
};
|
|
3410
|
+
/**
|
|
3411
|
+
* Request can run for some time, once it's done, we have to check if it's successful or if it was aborted
|
|
3412
|
+
* It can be different once the previous call was set as cancelled and removed from queue before this request got resolved
|
|
3413
|
+
*/
|
|
3414
|
+
performRequest = async (storageItem) => {
|
|
3415
|
+
const { request, requestId } = storageItem;
|
|
3416
|
+
this.logger.debug({
|
|
3417
|
+
title: "Performing request",
|
|
3418
|
+
type: "system",
|
|
3419
|
+
extra: {
|
|
3420
|
+
request,
|
|
3421
|
+
requestId
|
|
3422
|
+
}
|
|
3423
|
+
});
|
|
3424
|
+
const { retry, retryTime, queryKey: rawQueryKey, abortKey: rawAbortKey, offline, scope } = request;
|
|
3425
|
+
const queryKey = scopeKey(rawQueryKey, scope);
|
|
3426
|
+
const abortKey = scopeKey(rawAbortKey, scope);
|
|
3427
|
+
const { adapter, requestManager, cache, appManager } = this.client;
|
|
3428
|
+
const canRetry = canRetryRequest(storageItem.retries, retry);
|
|
3429
|
+
const isOffline = !appManager.isOnline && offline;
|
|
3430
|
+
const isAlreadyRunning = this.hasRunningRequest(queryKey, requestId);
|
|
3431
|
+
const isStopped = storageItem.stopped;
|
|
3432
|
+
if (isOffline || isAlreadyRunning || isStopped) return this.logger.warning({
|
|
3433
|
+
title: "Unable to perform request",
|
|
3434
|
+
type: "system",
|
|
3435
|
+
extra: {
|
|
3436
|
+
isOffline,
|
|
3437
|
+
isAlreadyRunning,
|
|
3438
|
+
isStopped
|
|
3439
|
+
}
|
|
3440
|
+
});
|
|
3441
|
+
const runningRequest = this.addRunningRequest(queryKey, requestId, request);
|
|
3442
|
+
requestManager.events.emitLoading({
|
|
3443
|
+
request,
|
|
3444
|
+
requestId,
|
|
3445
|
+
loading: true,
|
|
3446
|
+
isRetry: !!storageItem.retries,
|
|
3447
|
+
isOffline
|
|
3448
|
+
});
|
|
3449
|
+
this.incrementQueueRequestCount(queryKey);
|
|
3450
|
+
requestManager.addAbortController(abortKey, requestId);
|
|
3451
|
+
const response = await adapter.fetch(request, requestId);
|
|
3452
|
+
storageItem.resolved = true;
|
|
3453
|
+
requestManager.removeAbortController(abortKey, requestId);
|
|
3454
|
+
const isOfflineResponseStatus = !appManager.isOnline;
|
|
3455
|
+
const isCancelMessage = getErrorMessage("abort").message === response.error?.message;
|
|
3456
|
+
const isCanceled = !this.hasRunningRequest(queryKey, requestId) || isCancelMessage;
|
|
3457
|
+
this.deleteRunningRequest(queryKey, requestId);
|
|
3458
|
+
const shouldRetryOnError = response.success || !canRetry || !request.retryOnError || request.retryOnError(response);
|
|
3459
|
+
const willRetry = !response.success && canRetry && shouldRetryOnError && !isCanceled && !isOfflineResponseStatus;
|
|
3460
|
+
const requestDetails = {
|
|
3461
|
+
isCanceled,
|
|
3462
|
+
isOffline: isOfflineResponseStatus,
|
|
3463
|
+
retries: storageItem.retries,
|
|
3464
|
+
willRetry,
|
|
3465
|
+
addedTimestamp: storageItem.timestamp,
|
|
3466
|
+
triggerTimestamp: runningRequest.timestamp,
|
|
3467
|
+
requestTimestamp: response.requestTimestamp,
|
|
3468
|
+
responseTimestamp: response.responseTimestamp
|
|
3469
|
+
};
|
|
3470
|
+
requestManager.events.emitResponse({
|
|
3471
|
+
request,
|
|
3472
|
+
requestId,
|
|
3473
|
+
response,
|
|
3474
|
+
details: requestDetails
|
|
3475
|
+
});
|
|
3476
|
+
requestManager.events.emitLoading({
|
|
3477
|
+
request,
|
|
3478
|
+
requestId,
|
|
3479
|
+
loading: false,
|
|
3480
|
+
isRetry: !!storageItem.retries,
|
|
3481
|
+
isOffline
|
|
3482
|
+
});
|
|
3483
|
+
cache.set(request, {
|
|
3484
|
+
...response,
|
|
3485
|
+
...requestDetails
|
|
3486
|
+
});
|
|
3487
|
+
this.logger.debug({
|
|
3488
|
+
title: "Dispatcher processing response",
|
|
3489
|
+
type: "system",
|
|
3490
|
+
extra: {
|
|
3491
|
+
requestId,
|
|
3492
|
+
request,
|
|
3493
|
+
response,
|
|
3494
|
+
details: requestDetails
|
|
3495
|
+
}
|
|
3496
|
+
});
|
|
3497
|
+
if (isCanceled) {
|
|
3498
|
+
const queue = this.getQueue(queryKey);
|
|
3499
|
+
const queueItem = queue.requests.find((req) => req.requestId === requestId);
|
|
3500
|
+
if (!queue.stopped && !queueItem?.stopped) {
|
|
3501
|
+
this.logger.debug({
|
|
3502
|
+
title: "Request paused",
|
|
3503
|
+
type: "system",
|
|
3504
|
+
extra: {
|
|
3505
|
+
response,
|
|
3506
|
+
requestDetails,
|
|
3507
|
+
request
|
|
3508
|
+
}
|
|
3509
|
+
});
|
|
3510
|
+
return this.delete(queryKey, requestId, abortKey);
|
|
3511
|
+
}
|
|
3512
|
+
return this.logger.debug({
|
|
3513
|
+
title: "Request canceled",
|
|
3514
|
+
type: "system",
|
|
3515
|
+
extra: {
|
|
3516
|
+
response,
|
|
3517
|
+
requestDetails,
|
|
3518
|
+
request
|
|
3519
|
+
}
|
|
3520
|
+
});
|
|
3521
|
+
}
|
|
3522
|
+
if (!response.success && isOfflineResponseStatus) {
|
|
3523
|
+
if (!offline) {
|
|
3524
|
+
this.logger.warning({
|
|
3525
|
+
title: "Removing non-offline request",
|
|
3526
|
+
type: "system",
|
|
3527
|
+
extra: {
|
|
3528
|
+
response,
|
|
3529
|
+
requestDetails,
|
|
3530
|
+
request
|
|
3531
|
+
}
|
|
3532
|
+
});
|
|
3533
|
+
return this.delete(queryKey, requestId, abortKey);
|
|
3534
|
+
}
|
|
3535
|
+
return this.logger.debug({
|
|
3536
|
+
title: "Awaiting for network restoration",
|
|
3537
|
+
type: "system",
|
|
3538
|
+
extra: {
|
|
3539
|
+
response,
|
|
3540
|
+
requestDetails,
|
|
3541
|
+
request
|
|
3542
|
+
}
|
|
3543
|
+
});
|
|
3544
|
+
}
|
|
3545
|
+
if (response.success) {
|
|
3546
|
+
this.delete(queryKey, requestId, abortKey);
|
|
3547
|
+
return this.logger.debug({
|
|
3548
|
+
title: "Successful response, removing request from queue.",
|
|
3549
|
+
type: "system",
|
|
3550
|
+
extra: {
|
|
3551
|
+
response,
|
|
3552
|
+
requestDetails,
|
|
3553
|
+
request
|
|
3554
|
+
}
|
|
3555
|
+
});
|
|
3556
|
+
}
|
|
3557
|
+
if (willRetry) {
|
|
3558
|
+
this.logger.debug({
|
|
3559
|
+
title: "Waiting for retry",
|
|
3560
|
+
type: "system",
|
|
3561
|
+
extra: {
|
|
3562
|
+
response,
|
|
3563
|
+
requestDetails,
|
|
3564
|
+
request
|
|
3565
|
+
}
|
|
3566
|
+
});
|
|
3567
|
+
setTimeout(() => {
|
|
3568
|
+
this.logger.warning({
|
|
3569
|
+
title: "Error response, performing retry",
|
|
3570
|
+
type: "request",
|
|
3571
|
+
extra: {
|
|
3572
|
+
response,
|
|
3573
|
+
requestDetails,
|
|
3574
|
+
request,
|
|
3575
|
+
requestId
|
|
3576
|
+
}
|
|
3577
|
+
});
|
|
3578
|
+
this.performRequest({
|
|
3579
|
+
...storageItem,
|
|
3580
|
+
retries: storageItem.retries + 1
|
|
3581
|
+
});
|
|
3582
|
+
}, retryTime || 0);
|
|
3583
|
+
} else {
|
|
3584
|
+
if (request.retry) this.logger.error({
|
|
3585
|
+
title: "All retries have been used. Removing request from queue.",
|
|
3586
|
+
type: "request",
|
|
3587
|
+
extra: {
|
|
3588
|
+
response,
|
|
3589
|
+
requestDetails,
|
|
3590
|
+
request,
|
|
3591
|
+
requestId
|
|
3592
|
+
}
|
|
3593
|
+
});
|
|
3594
|
+
this.delete(queryKey, requestId, abortKey);
|
|
3595
|
+
}
|
|
3596
|
+
};
|
|
3597
|
+
};
|
|
3598
|
+
//#endregion
|
|
3599
|
+
//#region src/dispatcher/dispatcher.utils.ts
|
|
3600
|
+
var getDispatcherDrainedKey = () => {
|
|
3601
|
+
return `drained-event`;
|
|
3602
|
+
};
|
|
3603
|
+
var getDispatcherDrainedByKey = (key) => {
|
|
3604
|
+
return `${key}-drained-event`;
|
|
3605
|
+
};
|
|
3606
|
+
var getDispatcherStatusKey = () => {
|
|
3607
|
+
return `status-event`;
|
|
3608
|
+
};
|
|
3609
|
+
var getDispatcherStatusByKey = (key) => {
|
|
3610
|
+
return `${key}-status-event`;
|
|
3611
|
+
};
|
|
3612
|
+
var getDispatcherChangeKey = () => {
|
|
3613
|
+
return `change-event`;
|
|
3614
|
+
};
|
|
3615
|
+
var getDispatcherChangeByKey = (key) => {
|
|
3616
|
+
return `${key}-change-event`;
|
|
3617
|
+
};
|
|
3618
|
+
var getIsEqualTimestamp = (currentTimestamp, threshold, queueTimestamp) => {
|
|
3619
|
+
if (!queueTimestamp) return false;
|
|
3620
|
+
return queueTimestamp - currentTimestamp <= threshold;
|
|
3621
|
+
};
|
|
3622
|
+
var canRetryRequest = (currentRetries, retry) => {
|
|
3623
|
+
if (retry && currentRetries < retry) return true;
|
|
3624
|
+
return false;
|
|
3625
|
+
};
|
|
3626
|
+
var isInDeduplicateRange = (request, latestRequest) => {
|
|
3627
|
+
if (request.deduplicateTime) return +/* @__PURE__ */ new Date() - latestRequest.timestamp <= request.deduplicateTime;
|
|
3628
|
+
return true;
|
|
3629
|
+
};
|
|
3630
|
+
var getRequestType = (request, latestRequest) => {
|
|
3631
|
+
const { queued, cancelable, deduplicate } = request;
|
|
3632
|
+
const canDeduplicate = latestRequest ? isInDeduplicateRange(request, latestRequest) : false;
|
|
3633
|
+
if (queued) return DispatcherMode.ONE_BY_ONE;
|
|
3634
|
+
if (cancelable) return DispatcherMode.PREVIOUS_CANCELED;
|
|
3635
|
+
if (canDeduplicate && deduplicate) return DispatcherMode.DEDUPLICATED;
|
|
3636
|
+
return DispatcherMode.ALL_AT_ONCE;
|
|
3637
|
+
};
|
|
3638
|
+
//#endregion
|
|
3639
|
+
//#region src/client/client.utils.ts
|
|
3640
|
+
/** Picks effective {@link ClientMode}: explicit override, else environment detection. */
|
|
3641
|
+
function resolveClientMode(modeOption) {
|
|
3642
|
+
if (modeOption === "client" || modeOption === "server") return modeOption;
|
|
3643
|
+
if (typeof window !== "undefined" && typeof document !== "undefined") return "client";
|
|
3644
|
+
return "server";
|
|
3645
|
+
}
|
|
3646
|
+
var interceptRequest = async (interceptors, request) => {
|
|
3647
|
+
let newRequest = request;
|
|
3648
|
+
if (!request.requestOptions.disableRequestInterceptors) for (const interceptor of interceptors) {
|
|
3649
|
+
newRequest = await interceptor(request);
|
|
3650
|
+
if (!newRequest) throw new Error("Request modifier must return request");
|
|
3651
|
+
}
|
|
3652
|
+
return newRequest;
|
|
3653
|
+
};
|
|
3654
|
+
var interceptResponse = async (interceptors, response, request) => {
|
|
3655
|
+
let newResponse = response;
|
|
3656
|
+
if (!request.requestOptions.disableResponseInterceptors) for (const interceptor of interceptors) {
|
|
3657
|
+
newResponse = await interceptor(response, request);
|
|
3658
|
+
if (!newResponse) throw new Error("Response modifier must return data");
|
|
3659
|
+
}
|
|
3660
|
+
return newResponse;
|
|
3661
|
+
};
|
|
3662
|
+
//#endregion
|
|
3663
|
+
//#region src/client/client.ts
|
|
3664
|
+
/**
|
|
3665
|
+
* **Client** is a class that allows you to configure the connection with the server and then use it to create
|
|
3666
|
+
* requests. It allows you to set global defaults for the requests configuration, query params configuration.
|
|
3667
|
+
* It is also orchestrator for all of the HyperFetch modules like Cache, Dispatcher, AppManager, LoggerManager,
|
|
3668
|
+
* RequestManager and more.
|
|
3669
|
+
*/
|
|
3670
|
+
var Client = class {
|
|
3671
|
+
url;
|
|
3672
|
+
mode;
|
|
3673
|
+
debug;
|
|
3674
|
+
unstable_onErrorCallbacks = [];
|
|
3675
|
+
unstable_onSuccessCallbacks = [];
|
|
3676
|
+
unstable_onResponseCallbacks = [];
|
|
3677
|
+
unstable_onAuthCallbacks = [];
|
|
3678
|
+
unstable_onRequestCallbacks = [];
|
|
3679
|
+
loggerManager = new LoggerManager();
|
|
3680
|
+
requestManager = new RequestManager();
|
|
3681
|
+
appManager;
|
|
3682
|
+
adapter;
|
|
3683
|
+
cache;
|
|
3684
|
+
fetchDispatcher;
|
|
3685
|
+
submitDispatcher;
|
|
3686
|
+
isMockerEnabled = true;
|
|
3687
|
+
plugins = [];
|
|
3688
|
+
/** @internal */
|
|
3689
|
+
unstable_abortKeyMapper = getSimpleKey;
|
|
3690
|
+
/** @internal */
|
|
3691
|
+
unstable_cacheKeyMapper = getRequestKey;
|
|
3692
|
+
/** @internal */
|
|
3693
|
+
unstable_queryKeyMapper = getRequestKey;
|
|
3694
|
+
/** @internal */
|
|
3695
|
+
unstable_requestIdMapper = getUniqueRequestId;
|
|
3696
|
+
logger = this.loggerManager.initialize(this, "Client");
|
|
3697
|
+
constructor(options) {
|
|
3698
|
+
this.options = options;
|
|
3699
|
+
const { url, appManager, cache, fetchDispatcher, submitDispatcher, mode: modeOption } = this.options;
|
|
3700
|
+
this.url = url;
|
|
3701
|
+
this.mode = resolveClientMode(modeOption);
|
|
3702
|
+
this.adapter = HttpAdapter();
|
|
3703
|
+
this.appManager = appManager?.() || new AppManager();
|
|
3704
|
+
this.cache = cache?.() || new Cache();
|
|
3705
|
+
this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();
|
|
3706
|
+
this.submitDispatcher = submitDispatcher?.() || new Dispatcher();
|
|
3707
|
+
this.adapter.initialize(this);
|
|
3708
|
+
this.appManager.initialize();
|
|
3709
|
+
this.cache.initialize(this);
|
|
3710
|
+
this.fetchDispatcher.initialize(this);
|
|
3711
|
+
this.submitDispatcher.initialize(this);
|
|
3712
|
+
}
|
|
3713
|
+
/**
|
|
3714
|
+
* This method enables the logger usage and display the logs in console
|
|
3715
|
+
*/
|
|
3716
|
+
setDebug = (enabled) => {
|
|
3717
|
+
this.debug = enabled;
|
|
3718
|
+
return this;
|
|
3719
|
+
};
|
|
3720
|
+
/**
|
|
3721
|
+
* Set the logger severity of the messages displayed to the console
|
|
3722
|
+
*/
|
|
3723
|
+
setLogLevel = (severity) => {
|
|
3724
|
+
this.loggerManager.setSeverity(severity);
|
|
3725
|
+
return this;
|
|
3726
|
+
};
|
|
3727
|
+
/**
|
|
3728
|
+
* Set the new logger instance to the Client
|
|
3729
|
+
*/
|
|
3730
|
+
setLogger = (callback) => {
|
|
3731
|
+
this.loggerManager = callback(this);
|
|
3732
|
+
this.loggerManager.initialize(this, "Client");
|
|
3733
|
+
return this;
|
|
3734
|
+
};
|
|
3735
|
+
/**
|
|
3736
|
+
* Set globally if mocking should be enabled or disabled for all client requests.
|
|
3737
|
+
* @param isMockerEnabled
|
|
3738
|
+
*/
|
|
3739
|
+
setEnableGlobalMocking = (isMockerEnabled) => {
|
|
3740
|
+
this.isMockerEnabled = isMockerEnabled;
|
|
3741
|
+
return this;
|
|
3742
|
+
};
|
|
3743
|
+
/**
|
|
3744
|
+
* Set custom http adapter to handle graphql, rest, firebase or others
|
|
3745
|
+
*/
|
|
3746
|
+
setAdapter = (adapter) => {
|
|
3747
|
+
this.adapter = adapter;
|
|
3748
|
+
this.adapter.initialize(this);
|
|
3749
|
+
return this;
|
|
3750
|
+
};
|
|
3751
|
+
/**
|
|
3752
|
+
* Method of manipulating requests before sending the request. We can for example add custom header with token to the request which request had the auth set to true.
|
|
3753
|
+
*/
|
|
3754
|
+
onAuth = (callback) => {
|
|
3755
|
+
this.unstable_onAuthCallbacks.push(callback);
|
|
3756
|
+
return this;
|
|
3757
|
+
};
|
|
3758
|
+
/**
|
|
3759
|
+
* Method for removing listeners on auth.
|
|
3760
|
+
* */
|
|
3761
|
+
removeOnAuthInterceptors = (callbacks) => {
|
|
3762
|
+
this.unstable_onAuthCallbacks = this.unstable_onAuthCallbacks.filter((callback) => !callbacks.includes(callback));
|
|
3763
|
+
return this;
|
|
3764
|
+
};
|
|
3765
|
+
/**
|
|
3766
|
+
* Method for intercepting error responses. It can be used for example to refresh tokens.
|
|
3767
|
+
*/
|
|
3768
|
+
onError = (callback) => {
|
|
3769
|
+
this.unstable_onErrorCallbacks.push(callback);
|
|
3770
|
+
return this;
|
|
3771
|
+
};
|
|
3772
|
+
/**
|
|
3773
|
+
* Method for removing listeners on error.
|
|
3774
|
+
* */
|
|
3775
|
+
removeOnErrorInterceptors = (callbacks) => {
|
|
3776
|
+
this.unstable_onErrorCallbacks = this.unstable_onErrorCallbacks.filter((callback) => !callbacks.includes(callback));
|
|
3777
|
+
return this;
|
|
3778
|
+
};
|
|
3779
|
+
/**
|
|
3780
|
+
* Method for intercepting success responses.
|
|
3781
|
+
*/
|
|
3782
|
+
onSuccess = (callback) => {
|
|
3783
|
+
this.unstable_onSuccessCallbacks.push(callback);
|
|
3784
|
+
return this;
|
|
3785
|
+
};
|
|
3786
|
+
/**
|
|
3787
|
+
* Method for removing listeners on success.
|
|
3788
|
+
* */
|
|
3789
|
+
removeOnSuccessInterceptors = (callbacks) => {
|
|
3790
|
+
this.unstable_onSuccessCallbacks = this.unstable_onSuccessCallbacks.filter((callback) => !callbacks.includes(callback));
|
|
3791
|
+
return this;
|
|
3792
|
+
};
|
|
3793
|
+
/**
|
|
3794
|
+
* Method of manipulating requests before sending the request.
|
|
3795
|
+
*/
|
|
3796
|
+
onRequest = (callback) => {
|
|
3797
|
+
this.unstable_onRequestCallbacks.push(callback);
|
|
3798
|
+
return this;
|
|
3799
|
+
};
|
|
3800
|
+
/**
|
|
3801
|
+
* Method for removing listeners on request.
|
|
3802
|
+
* */
|
|
3803
|
+
removeOnRequestInterceptors = (callbacks) => {
|
|
3804
|
+
this.unstable_onRequestCallbacks = this.unstable_onRequestCallbacks.filter((callback) => !callbacks.includes(callback));
|
|
3805
|
+
return this;
|
|
3806
|
+
};
|
|
3807
|
+
/**
|
|
3808
|
+
* Method for intercepting any responses.
|
|
3809
|
+
*/
|
|
3810
|
+
onResponse = (callback) => {
|
|
3811
|
+
this.unstable_onResponseCallbacks.push(callback);
|
|
3812
|
+
return this;
|
|
3813
|
+
};
|
|
3814
|
+
/**
|
|
3815
|
+
* Method for removing listeners on request.
|
|
3816
|
+
* */
|
|
3817
|
+
removeOnResponseInterceptors = (callbacks) => {
|
|
3818
|
+
this.unstable_onResponseCallbacks = this.unstable_onResponseCallbacks.filter((callback) => !callbacks.includes(callback));
|
|
3819
|
+
return this;
|
|
3820
|
+
};
|
|
3821
|
+
/**
|
|
3822
|
+
* Add persistent plugins which trigger on the request lifecycle
|
|
3823
|
+
*/
|
|
3824
|
+
addPlugin = (plugin) => {
|
|
3825
|
+
this.plugins.push(plugin);
|
|
3826
|
+
plugin.initialize(this);
|
|
3827
|
+
plugin.trigger("onMount", { client: this });
|
|
3828
|
+
return this;
|
|
3829
|
+
};
|
|
3830
|
+
/**
|
|
3831
|
+
* Remove plugins from Client
|
|
3832
|
+
*/
|
|
3833
|
+
removePlugin = (plugin) => {
|
|
3834
|
+
const pluginCount = this.plugins.length;
|
|
3835
|
+
this.plugins = this.plugins.filter((p) => p !== plugin);
|
|
3836
|
+
if (this.plugins.length !== pluginCount) plugin.trigger("onUnmount", { client: this });
|
|
3837
|
+
return this;
|
|
3838
|
+
};
|
|
3839
|
+
triggerPlugins = (key, data) => {
|
|
3840
|
+
if (!this.plugins.length) return this;
|
|
3841
|
+
this.plugins.forEach((plugin) => {
|
|
3842
|
+
plugin.trigger(key, data);
|
|
3843
|
+
});
|
|
3844
|
+
return this;
|
|
3845
|
+
};
|
|
3846
|
+
/**
|
|
3847
|
+
* Key setters
|
|
3848
|
+
*/
|
|
3849
|
+
setAbortKeyMapper = (callback) => {
|
|
3850
|
+
this.unstable_abortKeyMapper = callback;
|
|
3851
|
+
return this;
|
|
3852
|
+
};
|
|
3853
|
+
setCacheKeyMapper = (callback) => {
|
|
3854
|
+
this.unstable_cacheKeyMapper = callback;
|
|
3855
|
+
return this;
|
|
3856
|
+
};
|
|
3857
|
+
setQueryKeyMapper = (callback) => {
|
|
3858
|
+
this.unstable_queryKeyMapper = callback;
|
|
3859
|
+
return this;
|
|
3860
|
+
};
|
|
3861
|
+
setRequestIdMapper = (callback) => {
|
|
3862
|
+
this.unstable_requestIdMapper = callback;
|
|
3863
|
+
return this;
|
|
3864
|
+
};
|
|
3865
|
+
/**
|
|
3866
|
+
* Helper used by http adapter to apply the modifications on response error
|
|
3867
|
+
* @private
|
|
3868
|
+
*/
|
|
3869
|
+
unstable_modifyAuth = async (request) => interceptRequest(this.unstable_onAuthCallbacks, request);
|
|
3870
|
+
/**
|
|
3871
|
+
* Private helper to run async pre-request processing
|
|
3872
|
+
* @private
|
|
3873
|
+
*/
|
|
3874
|
+
unstable_modifyRequest = async (request) => interceptRequest(this.unstable_onRequestCallbacks, request);
|
|
3875
|
+
/**
|
|
3876
|
+
* Private helper to run async on-error response processing
|
|
3877
|
+
* @private
|
|
3878
|
+
*/
|
|
3879
|
+
unstable_modifyErrorResponse = async (response, request) => interceptResponse(this.unstable_onErrorCallbacks, response, request);
|
|
3880
|
+
/**
|
|
3881
|
+
* Private helper to run async on-success response processing
|
|
3882
|
+
* @private
|
|
3883
|
+
*/
|
|
3884
|
+
unstable_modifySuccessResponse = async (response, request) => interceptResponse(this.unstable_onSuccessCallbacks, response, request);
|
|
3885
|
+
/**
|
|
3886
|
+
* Private helper to run async response processing
|
|
3887
|
+
* @private
|
|
3888
|
+
*/
|
|
3889
|
+
unstable_modifyResponse = async (response, request) => interceptResponse(this.unstable_onResponseCallbacks, response, request);
|
|
3890
|
+
/**
|
|
3891
|
+
* Reconstruct a Request class instance from its serialized JSON form.
|
|
3892
|
+
* Useful when dispatcher storage serializes queue data (e.g. MMKV, AsyncStorage)
|
|
3893
|
+
* and the deserialized request loses its class identity.
|
|
3894
|
+
*/
|
|
3895
|
+
fromJSON = (json) => {
|
|
3896
|
+
return Request.fromJSON(this, json);
|
|
3897
|
+
};
|
|
3898
|
+
/**
|
|
3899
|
+
* Clears the Client instance and remove all listeners on it's dependencies
|
|
3900
|
+
*/
|
|
3901
|
+
clear = () => {
|
|
3902
|
+
const { appManager, cache, fetchDispatcher, submitDispatcher } = this.options;
|
|
3903
|
+
this.requestManager.abortControllers.clear();
|
|
3904
|
+
this.fetchDispatcher.clear();
|
|
3905
|
+
this.submitDispatcher.clear();
|
|
3906
|
+
this.cache.clear();
|
|
3907
|
+
this.requestManager.emitter.removeAllListeners();
|
|
3908
|
+
this.fetchDispatcher.emitter.removeAllListeners();
|
|
3909
|
+
this.submitDispatcher.emitter.removeAllListeners();
|
|
3910
|
+
this.cache.emitter.removeAllListeners();
|
|
3911
|
+
this.cache = cache?.() || new Cache();
|
|
3912
|
+
this.appManager = appManager?.() || new AppManager();
|
|
3913
|
+
this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();
|
|
3914
|
+
this.submitDispatcher = submitDispatcher?.() || new Dispatcher();
|
|
3915
|
+
this.appManager.initialize();
|
|
3916
|
+
this.cache.initialize(this);
|
|
3917
|
+
this.fetchDispatcher.initialize(this);
|
|
3918
|
+
this.submitDispatcher.initialize(this);
|
|
3919
|
+
};
|
|
3920
|
+
/**
|
|
3921
|
+
* Hydrate your SSR cache data
|
|
3922
|
+
* @param hydrationData
|
|
3923
|
+
* @param options
|
|
3924
|
+
*/
|
|
3925
|
+
hydrate = (hydrationData, options) => {
|
|
3926
|
+
hydrationData?.forEach((item) => {
|
|
3927
|
+
if (!item) return;
|
|
3928
|
+
const { cacheKey, scope, response, ...fallbackOptions } = item;
|
|
3929
|
+
const defaults = {
|
|
3930
|
+
cache: true,
|
|
3931
|
+
override: true
|
|
3932
|
+
};
|
|
3933
|
+
const config = typeof options === "function" ? {
|
|
3934
|
+
...defaults,
|
|
3935
|
+
...fallbackOptions,
|
|
3936
|
+
...options(item)
|
|
3937
|
+
} : {
|
|
3938
|
+
...defaults,
|
|
3939
|
+
...fallbackOptions,
|
|
3940
|
+
...options
|
|
3941
|
+
};
|
|
3942
|
+
if (!config.override) {
|
|
3943
|
+
if (this.cache.get(scopeKey(cacheKey, scope))) return;
|
|
3944
|
+
}
|
|
3945
|
+
const parsedData = parseResponse(response);
|
|
3946
|
+
this.cache.set({
|
|
3947
|
+
...config,
|
|
3948
|
+
cacheKey,
|
|
3949
|
+
scope
|
|
3950
|
+
}, parsedData);
|
|
3951
|
+
});
|
|
3952
|
+
};
|
|
3953
|
+
/**
|
|
3954
|
+
* Create requests based on the Client setup
|
|
3955
|
+
*
|
|
3956
|
+
* @template Response Your response
|
|
3957
|
+
*/
|
|
3958
|
+
createRequest = (_USE_DOUBLE_INITIALIZATION) => {
|
|
3959
|
+
return (params) => {
|
|
3960
|
+
const endpoint = this.adapter.unstable_endpointMapper(params.endpoint);
|
|
3961
|
+
const mappedParams = {
|
|
3962
|
+
...params,
|
|
3963
|
+
endpoint: String(endpoint)
|
|
3964
|
+
};
|
|
3965
|
+
const request = new Request(this, mappedParams);
|
|
3966
|
+
this.plugins.forEach((plugin) => plugin.trigger("onRequestCreate", { request }));
|
|
3967
|
+
return request;
|
|
3968
|
+
};
|
|
3969
|
+
};
|
|
3970
|
+
};
|
|
3971
|
+
//#endregion
|
|
3972
|
+
//#region src/client/client.constants.ts
|
|
3973
|
+
var stringifyDefaultOptions = {
|
|
3974
|
+
strict: true,
|
|
3975
|
+
encode: true,
|
|
3976
|
+
arrayFormat: "bracket",
|
|
3977
|
+
arraySeparator: "bracket",
|
|
3978
|
+
sort: false,
|
|
3979
|
+
skipNull: true,
|
|
3980
|
+
skipEmptyString: true
|
|
3981
|
+
};
|
|
3982
|
+
//#endregion
|
|
3983
|
+
//#region src/client/client.create.ts
|
|
3984
|
+
function createClient(options) {
|
|
3985
|
+
return new Client(options);
|
|
3986
|
+
}
|
|
3987
|
+
//#endregion
|
|
3988
|
+
//#region src/sdk/sdk.ts
|
|
3989
|
+
var getMethod = (key, options) => {
|
|
3990
|
+
const { methodTransform = (method) => method.toUpperCase() } = options ?? {};
|
|
3991
|
+
return methodTransform(key);
|
|
3992
|
+
};
|
|
3993
|
+
var endpointMatchesPattern = (endpoint, pattern) => {
|
|
3994
|
+
if (pattern === "*") return true;
|
|
3995
|
+
if (pattern === endpoint) return true;
|
|
3996
|
+
if (pattern.endsWith("/*")) {
|
|
3997
|
+
const prefix = pattern.slice(0, -1);
|
|
3998
|
+
return endpoint.startsWith(prefix) || endpoint === prefix.slice(0, -1);
|
|
3999
|
+
}
|
|
4000
|
+
return false;
|
|
4001
|
+
};
|
|
4002
|
+
var applyDefaults = (request, endpoint, defaults) => {
|
|
4003
|
+
if (!defaults) return request;
|
|
4004
|
+
let result = request;
|
|
4005
|
+
const entries = Object.entries(defaults);
|
|
4006
|
+
for (let i = 0; i < entries.length; i += 1) {
|
|
4007
|
+
const [pattern, config] = entries[i];
|
|
4008
|
+
if (endpointMatchesPattern(endpoint, pattern)) {
|
|
4009
|
+
if (config.headers) result = result.setHeaders(config.headers);
|
|
4010
|
+
if (config.auth !== void 0) result = result.setAuth(config.auth);
|
|
4011
|
+
if (config.cache !== void 0) result = result.setCache(config.cache);
|
|
4012
|
+
if (config.cacheTime !== void 0) result = result.setCacheTime(config.cacheTime);
|
|
4013
|
+
if (config.staleTime !== void 0) result = result.setStaleTime(config.staleTime);
|
|
4014
|
+
if (config.retry !== void 0) result = result.setRetry(config.retry);
|
|
4015
|
+
if (config.retryTime !== void 0) result = result.setRetryTime(config.retryTime);
|
|
4016
|
+
if (config.cancelable !== void 0) result = result.setCancelable(config.cancelable);
|
|
4017
|
+
if (config.queued !== void 0) result = result.setQueued(config.queued);
|
|
4018
|
+
if (config.offline !== void 0) result = result.setOffline(config.offline);
|
|
4019
|
+
if (config.deduplicate !== void 0) result = result.setDeduplicate(config.deduplicate);
|
|
4020
|
+
if (config.deduplicateTime !== void 0 && config.deduplicateTime !== null) result = result.setDeduplicateTime(config.deduplicateTime);
|
|
4021
|
+
}
|
|
4022
|
+
}
|
|
4023
|
+
return result;
|
|
4024
|
+
};
|
|
4025
|
+
var createRecursiveProxy = (client, path, options) => {
|
|
4026
|
+
return new Proxy(() => {}, { get: (_target, key) => {
|
|
4027
|
+
if (typeof key === "symbol" || key === "inspect") return;
|
|
4028
|
+
let isMethod = false;
|
|
4029
|
+
let methodName = key;
|
|
4030
|
+
let pathSegment = key;
|
|
4031
|
+
if (key.startsWith("$")) {
|
|
4032
|
+
isMethod = true;
|
|
4033
|
+
methodName = key.slice(1);
|
|
4034
|
+
pathSegment = `:${key.slice(1)}`;
|
|
4035
|
+
} else if (options?.camelCaseToKebabCase) pathSegment = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
4036
|
+
const endpoint = `/${path.join("/")}`;
|
|
4037
|
+
const method = getMethod(isMethod ? methodName : key, options);
|
|
4038
|
+
let request = client.createRequest()({
|
|
4039
|
+
endpoint,
|
|
4040
|
+
method
|
|
4041
|
+
});
|
|
4042
|
+
request = applyDefaults(request, endpoint, options?.defaults);
|
|
4043
|
+
const deeperProxy = createRecursiveProxy(client, [...path, pathSegment], options);
|
|
4044
|
+
return new Proxy(request, { get: (reqTarget, reqKey) => {
|
|
4045
|
+
if (reqKey in reqTarget) return reqTarget[reqKey];
|
|
4046
|
+
return deeperProxy[reqKey];
|
|
4047
|
+
} });
|
|
4048
|
+
} });
|
|
4049
|
+
};
|
|
4050
|
+
var createSdk = (client, options) => {
|
|
4051
|
+
const { camelCaseToKebabCase = true, methodTransform = (method) => method.toUpperCase(), ...rest } = options ?? {};
|
|
4052
|
+
const mergedOptions = {
|
|
4053
|
+
camelCaseToKebabCase,
|
|
4054
|
+
methodTransform,
|
|
4055
|
+
...rest
|
|
4056
|
+
};
|
|
4057
|
+
const proxy = createRecursiveProxy(client, [], mergedOptions);
|
|
4058
|
+
return new Proxy(proxy, { get: (target, key) => {
|
|
4059
|
+
if (key === "$configure") return (defaults) => {
|
|
4060
|
+
const existingDefaults = mergedOptions.defaults || {};
|
|
4061
|
+
return createSdk(client, {
|
|
4062
|
+
...mergedOptions,
|
|
4063
|
+
defaults: {
|
|
4064
|
+
...existingDefaults,
|
|
4065
|
+
...defaults
|
|
4066
|
+
}
|
|
4067
|
+
});
|
|
4068
|
+
};
|
|
4069
|
+
return target[key];
|
|
4070
|
+
} });
|
|
4071
|
+
};
|
|
4072
|
+
/**
|
|
4073
|
+
* Type-safe factory for creating SDK configuration maps.
|
|
4074
|
+
*
|
|
4075
|
+
* @example
|
|
4076
|
+
* const config = createConfiguration<MySdkSchema>()({ "*": { retry: 3 } })
|
|
4077
|
+
*/
|
|
4078
|
+
var createConfiguration = () => {
|
|
4079
|
+
return (defaults) => defaults;
|
|
4080
|
+
};
|
|
4081
|
+
//#endregion
|
|
4082
|
+
export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, Plugin, Request, RequestManager, RequestProcessingError, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, interceptRequest, interceptResponse, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, parseErrorResponse, parseResponse, resolveClientMode, scopeKey, sendRequest, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, xhrExtra };
|
|
4083
|
+
|
|
4084
|
+
//# sourceMappingURL=index.mjs.map
|