@hyper-fetch/core 9.6.1 → 9.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/__tests__/features/adapter/adapter.bindings.progress.spec.ts +120 -0
  2. package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
  3. package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
  4. package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
  5. package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
  6. package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
  7. package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
  8. package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
  9. package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
  10. package/__tests__/features/cache/cache.timing.spec.ts +448 -0
  11. package/__tests__/features/client/client.clear.spec.ts +313 -0
  12. package/__tests__/features/client/client.configuration.spec.ts +416 -0
  13. package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
  14. package/__tests__/features/client/client.interceptor.spec.ts +54 -45
  15. package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
  16. package/__tests__/features/client/client.user-errors.spec.ts +220 -0
  17. package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
  18. package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
  19. package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
  20. package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
  21. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
  22. package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
  23. package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
  24. package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
  25. package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
  26. package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
  27. package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
  28. package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
  29. package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
  30. package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
  31. package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
  32. package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
  33. package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -0
  34. package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
  35. package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
  36. package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
  37. package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
  38. package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
  39. package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
  40. package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
  41. package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
  42. package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
  43. package/__tests__/features/request/request.immutability.spec.ts +259 -0
  44. package/__tests__/features/request/request.inference.spec.ts +269 -0
  45. package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
  46. package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
  47. package/__tests__/features/request/request.optimistic.spec.ts +12 -1
  48. package/__tests__/features/request/request.values.spec.ts +408 -0
  49. package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
  50. package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
  51. package/__tests__/utils/controlled-adapter.utils.ts +119 -0
  52. package/__tests__/utils/fixtures.utils.ts +193 -0
  53. package/__tests__/utils/optimistic.utils.ts +124 -0
  54. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  55. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  56. package/dist/cache/cache.d.ts +12 -1
  57. package/dist/cache/cache.d.ts.map +1 -1
  58. package/dist/cache/cache.events.d.ts +20 -6
  59. package/dist/cache/cache.events.d.ts.map +1 -1
  60. package/dist/cache/cache.utils.d.ts +1 -0
  61. package/dist/cache/cache.utils.d.ts.map +1 -1
  62. package/dist/client/client.d.ts +3 -3
  63. package/dist/client/client.d.ts.map +1 -1
  64. package/dist/client/client.utils.d.ts.map +1 -1
  65. package/dist/dispatcher/dispatcher.d.ts +26 -5
  66. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  67. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.mjs +2787 -1893
  71. package/dist/index.mjs.map +1 -1
  72. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  73. package/dist/managers/app/app.manager.d.ts +9 -0
  74. package/dist/managers/app/app.manager.d.ts.map +1 -1
  75. package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
  76. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  77. package/dist/managers/request/request.manager.d.ts.map +1 -1
  78. package/dist/managers/request/request.manager.types.d.ts +2 -0
  79. package/dist/managers/request/request.manager.types.d.ts.map +1 -1
  80. package/dist/mocker/mocker.d.ts +1 -1
  81. package/dist/mocker/mocker.d.ts.map +1 -1
  82. package/dist/optimistic/index.d.ts +5 -0
  83. package/dist/optimistic/index.d.ts.map +1 -0
  84. package/dist/optimistic/optimistic.d.ts +67 -0
  85. package/dist/optimistic/optimistic.d.ts.map +1 -0
  86. package/dist/optimistic/optimistic.settlement.d.ts +60 -0
  87. package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
  88. package/dist/optimistic/optimistic.types.d.ts +109 -0
  89. package/dist/optimistic/optimistic.types.d.ts.map +1 -0
  90. package/dist/optimistic/optimistic.utils.d.ts +29 -0
  91. package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
  92. package/dist/plugin/plugin.d.ts +2 -0
  93. package/dist/plugin/plugin.d.ts.map +1 -1
  94. package/dist/request/request.d.ts +14 -6
  95. package/dist/request/request.d.ts.map +1 -1
  96. package/dist/request/request.types.d.ts +40 -1
  97. package/dist/request/request.types.d.ts.map +1 -1
  98. package/dist/request/request.utils.d.ts.map +1 -1
  99. package/dist/utils/emitter.utils.d.ts.map +1 -1
  100. package/dist/utils/error.utils.d.ts +17 -0
  101. package/dist/utils/error.utils.d.ts.map +1 -0
  102. package/dist/utils/index.d.ts +1 -0
  103. package/dist/utils/index.d.ts.map +1 -1
  104. package/package.json +1 -1
  105. package/src/adapter/adapter.bindings.ts +46 -18
  106. package/src/adapter/adapter.utils.ts +47 -7
  107. package/src/cache/cache.events.ts +24 -8
  108. package/src/cache/cache.ts +110 -21
  109. package/src/cache/cache.utils.ts +33 -10
  110. package/src/client/client.ts +101 -7
  111. package/src/client/client.utils.ts +10 -4
  112. package/src/dispatcher/dispatcher.ts +285 -132
  113. package/src/http-adapter/http-adapter.fetch.ts +15 -3
  114. package/src/index.ts +4 -0
  115. package/src/managers/app/app.manager.constants.ts +12 -1
  116. package/src/managers/app/app.manager.ts +43 -23
  117. package/src/managers/app/app.manager.utils.ts +8 -4
  118. package/src/managers/logger/logger.manager.ts +21 -8
  119. package/src/managers/request/request.manager.ts +7 -1
  120. package/src/managers/request/request.manager.types.ts +2 -0
  121. package/src/mocker/mocker.ts +14 -11
  122. package/src/optimistic/index.ts +4 -0
  123. package/src/optimistic/optimistic.settlement.ts +406 -0
  124. package/src/optimistic/optimistic.ts +162 -0
  125. package/src/optimistic/optimistic.types.ts +175 -0
  126. package/src/optimistic/optimistic.utils.ts +112 -0
  127. package/src/plugin/plugin.ts +6 -0
  128. package/src/request/request.ts +50 -28
  129. package/src/request/request.types.ts +41 -1
  130. package/src/request/request.utils.ts +51 -66
  131. package/src/utils/emitter.utils.ts +9 -2
  132. package/src/utils/error.utils.ts +29 -0
  133. package/src/utils/index.ts +1 -0
  134. package/tsconfig.json +2 -0
@@ -0,0 +1,599 @@
1
+ import type { ResponseType } from "adapter";
2
+ import { Client } from "client";
3
+ import type { HttpAdapterType } from "http-adapter";
4
+ import { xhrExtra } from "http-adapter";
5
+ import { LoggerManager } from "managers";
6
+ import type { RequestInstance } from "request";
7
+
8
+ import { getUnhandledRejections } from "../../utils/fixtures.utils";
9
+
10
+ type Data = Record<string, unknown>;
11
+
12
+ const defaultData: Data = { id: 1 };
13
+
14
+ const createResponse = (
15
+ overrides: Partial<ResponseType<Data, Error, HttpAdapterType>> = {},
16
+ ): ResponseType<Data, Error, HttpAdapterType> => ({
17
+ data: {},
18
+ error: null,
19
+ status: 200,
20
+ success: true,
21
+ extra: xhrExtra,
22
+ requestTimestamp: Date.now(),
23
+ responseTimestamp: Date.now(),
24
+ ...overrides,
25
+ });
26
+
27
+ describe("Client [ Interceptors Pipeline ]", () => {
28
+ let client = new Client({ url: "shared-base-url" });
29
+ let request = client.createRequest<{ response: Data }>()({ endpoint: "/users" });
30
+ let sentRequest: RequestInstance | undefined;
31
+
32
+ const mockSuccess = (data: Data = defaultData) => {
33
+ const mock = vi.fn(({ request: sent }: { request: RequestInstance }) => {
34
+ sentRequest = sent;
35
+ return { data, status: 200 };
36
+ });
37
+ request.setMock(mock);
38
+ return mock;
39
+ };
40
+
41
+ const mockError = (error = new Error("Server error")) => {
42
+ const mock = vi.fn(() => ({ error, status: 400 }));
43
+ request.setMock(mock);
44
+ return mock;
45
+ };
46
+
47
+ beforeEach(() => {
48
+ client = new Client({ url: "shared-base-url" });
49
+ request = client.createRequest<{ response: Data }>()({ endpoint: "/users" });
50
+ sentRequest = undefined;
51
+ });
52
+
53
+ afterEach(() => {
54
+ client.clear();
55
+ });
56
+
57
+ describe("When request interceptors are chained", () => {
58
+ it("should run them in the order they were added", async () => {
59
+ const order: string[] = [];
60
+ client
61
+ .onRequest(async (req) => {
62
+ await Promise.resolve();
63
+ order.push("first");
64
+ return req;
65
+ })
66
+ .onRequest((req) => {
67
+ order.push("second");
68
+ return req;
69
+ })
70
+ .onRequest(async (req) => {
71
+ order.push("third");
72
+ return req;
73
+ });
74
+
75
+ await client.unstable_modifyRequest(request);
76
+
77
+ expect(order).toStrictEqual(["first", "second", "third"]);
78
+ });
79
+
80
+ it("should pass the request returned by the previous interceptor to the next one", async () => {
81
+ client
82
+ .onRequest((req) => req.setHeaders({ ...req.headers, first: "1" }))
83
+ .onRequest((req) => req.setHeaders({ ...req.headers, second: "2" }))
84
+ .onRequest((req) => req.setHeaders({ ...req.headers, third: "3" }));
85
+
86
+ const modified = await client.unstable_modifyRequest(request);
87
+
88
+ expect(modified.headers).toStrictEqual({ first: "1", second: "2", third: "3" });
89
+ });
90
+
91
+ it("should send the request modified by every interceptor", async () => {
92
+ mockSuccess();
93
+ client
94
+ .onRequest((req) => req.setHeaders({ ...req.headers, first: "1" }))
95
+ .onRequest(async (req) => req.setHeaders({ ...req.headers, second: "2" }));
96
+
97
+ await request.send();
98
+
99
+ expect(sentRequest?.headers).toStrictEqual({ first: "1", second: "2" });
100
+ });
101
+
102
+ it("should not change the original request", async () => {
103
+ mockSuccess();
104
+ client.onRequest((req) => req.setHeaders({ ...req.headers, first: "1" }));
105
+
106
+ await request.send();
107
+
108
+ expect(request.headers).toBeUndefined();
109
+ });
110
+
111
+ it("should return the original request when there are no interceptors", async () => {
112
+ await expect(client.unstable_modifyRequest(request)).resolves.toBe(request);
113
+ await expect(client.unstable_modifyAuth(request)).resolves.toBe(request);
114
+ });
115
+
116
+ it("should run the interceptor added twice two times", async () => {
117
+ const interceptor = vi.fn((req: RequestInstance) => req);
118
+ client.onRequest(interceptor).onRequest(interceptor);
119
+
120
+ await client.unstable_modifyRequest(request);
121
+
122
+ expect(interceptor).toHaveBeenCalledTimes(2);
123
+ });
124
+
125
+ it("should skip the interceptors when the request disables them", async () => {
126
+ const onRequest = vi.fn((req: RequestInstance) => req);
127
+ const onAuth = vi.fn((req: RequestInstance) => req);
128
+ client.onRequest(onRequest).onAuth(onAuth);
129
+ const disabled = client.createRequest<{ response: Data }>()({
130
+ endpoint: "/users",
131
+ auth: true,
132
+ disableRequestInterceptors: true,
133
+ });
134
+ disabled.setMock(() => ({ data: {}, status: 200 }));
135
+
136
+ const response = await disabled.send();
137
+
138
+ expect(response.success).toBeTrue();
139
+ expect(onRequest).not.toHaveBeenCalled();
140
+ expect(onAuth).not.toHaveBeenCalled();
141
+ });
142
+
143
+ it("should stop calling the removed interceptors", async () => {
144
+ const removed = vi.fn((req: RequestInstance) => req);
145
+ const kept = vi.fn((req: RequestInstance) => req);
146
+ client.onRequest(removed).onRequest(kept).onRequest(removed);
147
+
148
+ client.removeOnRequestInterceptors([removed]);
149
+ client.removeOnRequestInterceptors([() => request]);
150
+ await client.unstable_modifyRequest(request);
151
+
152
+ expect(removed).not.toHaveBeenCalled();
153
+ expect(kept).toHaveBeenCalledTimes(1);
154
+ });
155
+ });
156
+
157
+ describe("When auth interceptors are used", () => {
158
+ it("should run them for the requests by default", async () => {
159
+ const onAuth = vi.fn((req: RequestInstance) => req);
160
+ mockSuccess();
161
+ client.onAuth(onAuth);
162
+
163
+ await request.send();
164
+
165
+ expect(request.auth).toBeTrue();
166
+ expect(onAuth).toHaveBeenCalledTimes(1);
167
+ });
168
+
169
+ it("should not run them for the requests with the auth disabled", async () => {
170
+ const onAuth = vi.fn((req: RequestInstance) => req);
171
+ const publicRequest = request.setAuth(false);
172
+ publicRequest.setMock(() => ({ data: {}, status: 200 }));
173
+ client.onAuth(onAuth);
174
+
175
+ const response = await publicRequest.send();
176
+
177
+ expect(response.success).toBeTrue();
178
+ expect(onAuth).not.toHaveBeenCalled();
179
+ });
180
+
181
+ it("should run them after the request interceptors with the request they returned", async () => {
182
+ const order: string[] = [];
183
+ let authInput: RequestInstance | undefined;
184
+ const authRequest = request.setAuth(true);
185
+ authRequest.setMock(({ request: sent }) => {
186
+ sentRequest = sent;
187
+ return { data: {}, status: 200 };
188
+ });
189
+ client
190
+ .onAuth((req) => {
191
+ order.push("auth");
192
+ authInput = req;
193
+ return req.setHeaders({ ...req.headers, Authorization: "Bearer token" });
194
+ })
195
+ .onRequest((req) => {
196
+ order.push("request");
197
+ return req.setHeaders({ ...req.headers, "x-trace": "1" });
198
+ });
199
+
200
+ await authRequest.send();
201
+
202
+ expect(order).toStrictEqual(["request", "auth"]);
203
+ expect(authInput?.headers).toStrictEqual({ "x-trace": "1" });
204
+ expect(sentRequest?.headers).toStrictEqual({ "x-trace": "1", Authorization: "Bearer token" });
205
+ });
206
+
207
+ it("should chain many auth interceptors", async () => {
208
+ client
209
+ .onAuth((req) => req.setHeaders({ ...req.headers, first: "1" }))
210
+ .onAuth((req) => req.setHeaders({ ...req.headers, second: "2" }));
211
+
212
+ const modified = await client.unstable_modifyAuth(request);
213
+
214
+ expect(modified.headers).toStrictEqual({ first: "1", second: "2" });
215
+ });
216
+
217
+ it("should stop calling the removed auth interceptors", async () => {
218
+ const removed = vi.fn((req: RequestInstance) => req);
219
+ client.onAuth(removed);
220
+
221
+ client.removeOnAuthInterceptors([removed]);
222
+ await client.unstable_modifyAuth(request);
223
+
224
+ expect(removed).not.toHaveBeenCalled();
225
+ });
226
+ });
227
+
228
+ describe("When request interceptors fail", () => {
229
+ it.each([
230
+ {
231
+ name: "throws",
232
+ interceptor: () => {
233
+ throw new Error("Interceptor failed");
234
+ },
235
+ message: "Interceptor failed",
236
+ },
237
+ {
238
+ name: "rejects",
239
+ interceptor: () => Promise.reject(new Error("Interceptor failed")),
240
+ message: "Interceptor failed",
241
+ },
242
+ {
243
+ name: "returns nothing",
244
+ interceptor: () => undefined as unknown as RequestInstance,
245
+ message: "Request modifier must return request",
246
+ },
247
+ ])("should end the request with the error when the interceptor $name", async ({ interceptor, message }) => {
248
+ const mock = mockSuccess();
249
+ const next = vi.fn((req: RequestInstance) => req);
250
+ client.onRequest(interceptor).onRequest(next);
251
+
252
+ let response: Awaited<ReturnType<typeof request.send>> | undefined;
253
+ const rejections = await getUnhandledRejections(async () => {
254
+ response = await request.send();
255
+ });
256
+
257
+ expect(rejections).toHaveLength(0);
258
+ expect(response?.success).toBeFalse();
259
+ expect(response?.data).toBeNull();
260
+ expect(response?.error?.message).toBe(message);
261
+ expect(mock).not.toHaveBeenCalled();
262
+ expect(next).not.toHaveBeenCalled();
263
+ expect(request.read()).toBeUndefined();
264
+ });
265
+
266
+ it("should end the request with the error when the auth interceptor fails", async () => {
267
+ const authRequest = request.setAuth(true);
268
+ const mock = vi.fn(() => ({ data: {}, status: 200 }));
269
+ authRequest.setMock(mock);
270
+ client.onAuth(() => {
271
+ throw new Error("Auth failed");
272
+ });
273
+
274
+ const response = await authRequest.send();
275
+
276
+ expect(response.success).toBeFalse();
277
+ expect(response.error?.message).toBe("Auth failed");
278
+ expect(mock).not.toHaveBeenCalled();
279
+ });
280
+
281
+ it("should handle the next request after the failed one", async () => {
282
+ mockSuccess();
283
+ let shouldFail = true;
284
+ client.onRequest((req) => {
285
+ if (shouldFail) {
286
+ throw new Error("Interceptor failed");
287
+ }
288
+ return req;
289
+ });
290
+
291
+ const failed = await request.send();
292
+ shouldFail = false;
293
+ const succeeded = await request.send();
294
+
295
+ expect(failed.success).toBeFalse();
296
+ expect(succeeded.success).toBeTrue();
297
+ expect(succeeded.data).toStrictEqual({ id: 1 });
298
+ });
299
+ });
300
+
301
+ describe("When response interceptors are chained", () => {
302
+ it("should pass the response returned by the previous interceptor to the next one", async () => {
303
+ client
304
+ .onResponse((response) => ({ ...response, data: { ...response.data, first: 1 } }))
305
+ .onResponse(async (response) => ({ ...response, data: { ...response.data, second: 2 } }))
306
+ .onResponse((response) => ({ ...response, data: { ...response.data, third: 3 } }));
307
+
308
+ const modified = await client.unstable_modifyResponse(createResponse({ data: { id: 1 } }), request);
309
+
310
+ expect(modified.data).toStrictEqual({ id: 1, first: 1, second: 2, third: 3 });
311
+ });
312
+
313
+ it("should chain the success interceptors", async () => {
314
+ client
315
+ .onSuccess((response) => ({ ...response, data: { ...response.data, first: 1 } }))
316
+ .onSuccess((response) => ({ ...response, data: { ...response.data, second: 2 } }));
317
+
318
+ const modified = await client.unstable_modifySuccessResponse(createResponse({ data: { id: 1 } }), request);
319
+
320
+ expect(modified.data).toStrictEqual({ id: 1, first: 1, second: 2 });
321
+ });
322
+
323
+ it("should chain the error interceptors", async () => {
324
+ client
325
+ .onError((response) => ({ ...response, status: 401 }))
326
+ .onError((response) => ({ ...response, error: new Error(`Status ${response.status}`) }));
327
+
328
+ const modified = await client.unstable_modifyErrorResponse(
329
+ createResponse({ data: null, success: false, status: 400, error: new Error("Failed") }),
330
+ request,
331
+ );
332
+
333
+ expect(modified.status).toBe(401);
334
+ expect(modified.error?.message).toBe("Status 401");
335
+ });
336
+
337
+ it("should pass the request to every interceptor", async () => {
338
+ const interceptor = vi.fn((response: ResponseType<any, any, HttpAdapterType>) => response);
339
+ client.onResponse(interceptor).onResponse(interceptor);
340
+
341
+ await client.unstable_modifyResponse(createResponse(), request);
342
+
343
+ expect(interceptor).toHaveBeenCalledTimes(2);
344
+ expect(interceptor.mock.calls.every((call) => (call as unknown[])[1] === request)).toBeTrue();
345
+ });
346
+
347
+ it("should return the original response when there are no interceptors", async () => {
348
+ const response = createResponse();
349
+
350
+ await expect(client.unstable_modifyResponse(response, request)).resolves.toBe(response);
351
+ await expect(client.unstable_modifySuccessResponse(response, request)).resolves.toBe(response);
352
+ await expect(client.unstable_modifyErrorResponse(response, request)).resolves.toBe(response);
353
+ });
354
+
355
+ it("should run the general interceptors before the success ones", async () => {
356
+ const order: string[] = [];
357
+ mockSuccess();
358
+ client
359
+ .onSuccess((response) => {
360
+ order.push("success");
361
+ return response;
362
+ })
363
+ .onError((response) => {
364
+ order.push("error");
365
+ return response;
366
+ })
367
+ .onResponse((response) => {
368
+ order.push("response");
369
+ return response;
370
+ });
371
+
372
+ await request.send();
373
+
374
+ expect(order).toStrictEqual(["response", "success"]);
375
+ });
376
+
377
+ it("should run the general interceptors before the error ones", async () => {
378
+ const order: string[] = [];
379
+ mockError();
380
+ client
381
+ .onSuccess((response) => {
382
+ order.push("success");
383
+ return response;
384
+ })
385
+ .onError((response) => {
386
+ order.push("error");
387
+ return response;
388
+ })
389
+ .onResponse((response) => {
390
+ order.push("response");
391
+ return response;
392
+ });
393
+
394
+ await request.send();
395
+
396
+ expect(order).toStrictEqual(["response", "error"]);
397
+ });
398
+
399
+ it("should resolve and cache the response modified by every interceptor", async () => {
400
+ mockSuccess({ id: 1 });
401
+ client
402
+ .onResponse((response) => ({ ...response, data: { ...response.data, general: true } }))
403
+ .onSuccess((response) => ({ ...response, data: { ...response.data, success: true } }));
404
+
405
+ const response = await request.send();
406
+
407
+ expect(response.data).toStrictEqual({ id: 1, general: true, success: true });
408
+ expect(request.read()?.data).toStrictEqual({ id: 1, general: true, success: true });
409
+ });
410
+
411
+ it("should let the error interceptor recover the request", async () => {
412
+ mockError();
413
+ client.onError((response) => ({ ...response, data: { recovered: true }, error: null, success: true }));
414
+
415
+ const response = await request.send();
416
+
417
+ expect(response.success).toBeTrue();
418
+ expect(response.data).toStrictEqual({ recovered: true });
419
+ expect(request.read()?.data).toStrictEqual({ recovered: true });
420
+ });
421
+
422
+ it("should skip the interceptors when the request disables them", async () => {
423
+ const interceptor = vi.fn((response: ResponseType<any, any, HttpAdapterType>) => response);
424
+ client.onResponse(interceptor).onSuccess(interceptor).onError(interceptor);
425
+ const disabled = client.createRequest<{ response: Data }>()({
426
+ endpoint: "/users",
427
+ disableResponseInterceptors: true,
428
+ });
429
+ disabled.setMock(() => ({ data: { id: 1 }, status: 200 }));
430
+
431
+ const response = await disabled.send();
432
+
433
+ expect(response.data).toStrictEqual({ id: 1 });
434
+ expect(interceptor).not.toHaveBeenCalled();
435
+ });
436
+
437
+ it("should stop calling the removed interceptors", async () => {
438
+ const removed = vi.fn((response: ResponseType<any, any, HttpAdapterType>) => response);
439
+ const kept = vi.fn((response: ResponseType<any, any, HttpAdapterType>) => response);
440
+ client.onResponse(removed).onResponse(kept).onSuccess(removed).onError(removed);
441
+
442
+ client
443
+ .removeOnResponseInterceptors([removed])
444
+ .removeOnSuccessInterceptors([removed])
445
+ .removeOnErrorInterceptors([removed]);
446
+ await client.unstable_modifyResponse(createResponse(), request);
447
+ await client.unstable_modifySuccessResponse(createResponse(), request);
448
+ await client.unstable_modifyErrorResponse(createResponse(), request);
449
+
450
+ expect(removed).not.toHaveBeenCalled();
451
+ expect(kept).toHaveBeenCalledTimes(1);
452
+ });
453
+ });
454
+
455
+ describe("When response interceptors fail", () => {
456
+ const failures = [
457
+ {
458
+ name: "throws",
459
+ interceptor: () => {
460
+ throw new Error("Interceptor failed");
461
+ },
462
+ message: "Interceptor failed",
463
+ },
464
+ {
465
+ name: "rejects",
466
+ interceptor: () => Promise.reject(new Error("Interceptor failed")),
467
+ message: "Interceptor failed",
468
+ },
469
+ {
470
+ name: "returns nothing",
471
+ interceptor: () => undefined as unknown as ResponseType<any, any, HttpAdapterType>,
472
+ message: "Response modifier must return data",
473
+ },
474
+ ];
475
+
476
+ it.each(failures)(
477
+ "should end the successful request with the error when the general interceptor $name",
478
+ async ({ interceptor, message }) => {
479
+ mockSuccess();
480
+ const next = vi.fn((response: ResponseType<any, any, HttpAdapterType>) => response);
481
+ client.onResponse(interceptor).onResponse(next);
482
+
483
+ let response: Awaited<ReturnType<typeof request.send>> | undefined;
484
+ const rejections = await getUnhandledRejections(async () => {
485
+ response = await request.send();
486
+ });
487
+
488
+ expect(rejections).toHaveLength(0);
489
+ expect(response?.success).toBeFalse();
490
+ expect(response?.data).toBeNull();
491
+ expect(response?.status).toBe(0);
492
+ expect(response?.error?.message).toBe(message);
493
+ expect(next).not.toHaveBeenCalled();
494
+ expect(request.read()).toBeUndefined();
495
+ },
496
+ );
497
+
498
+ it.each(failures)(
499
+ "should end the successful request with the error when the success interceptor $name",
500
+ async ({ interceptor, message }) => {
501
+ mockSuccess();
502
+ client.onSuccess(interceptor);
503
+
504
+ let response: Awaited<ReturnType<typeof request.send>> | undefined;
505
+ const rejections = await getUnhandledRejections(async () => {
506
+ response = await request.send();
507
+ });
508
+
509
+ expect(rejections).toHaveLength(0);
510
+ expect(response?.success).toBeFalse();
511
+ expect(response?.error?.message).toBe(message);
512
+ expect(request.read()).toBeUndefined();
513
+ },
514
+ );
515
+
516
+ it.each(failures)(
517
+ "should end the failed request with the error when the error interceptor $name",
518
+ async ({ interceptor, message }) => {
519
+ mockError();
520
+ client.onError(interceptor);
521
+
522
+ let response: Awaited<ReturnType<typeof request.send>> | undefined;
523
+ const rejections = await getUnhandledRejections(async () => {
524
+ response = await request.send();
525
+ });
526
+
527
+ expect(rejections).toHaveLength(0);
528
+ expect(response?.success).toBeFalse();
529
+ expect(response?.data).toBeNull();
530
+ expect(response?.error?.message).toBe(message);
531
+ },
532
+ );
533
+
534
+ it("should keep the timestamps of the intercepted response", async () => {
535
+ const response = createResponse({ requestTimestamp: 100, responseTimestamp: 200 });
536
+ client.onResponse(() => {
537
+ throw new Error("Interceptor failed");
538
+ });
539
+
540
+ const modified = await client.unstable_modifyResponse(response, request);
541
+
542
+ expect(modified).toStrictEqual({
543
+ data: null,
544
+ error: new Error("Interceptor failed"),
545
+ status: 0,
546
+ success: false,
547
+ extra: xhrExtra,
548
+ requestTimestamp: 100,
549
+ responseTimestamp: 200,
550
+ });
551
+ });
552
+
553
+ it("should log the failure of the interceptor", async () => {
554
+ const logger = vi.fn();
555
+ client.setDebug(true).setLogger(() => new LoggerManager({ logger }));
556
+ client.onResponse(() => {
557
+ throw new Error("Interceptor failed");
558
+ });
559
+
560
+ await client.unstable_modifyResponse(createResponse(), request);
561
+
562
+ expect(logger).toHaveBeenCalledTimes(1);
563
+ expect(logger.mock.calls[0][0]).toStrictEqual(
564
+ expect.objectContaining({ level: "error", module: "Client", title: "Response interceptor failed" }),
565
+ );
566
+ });
567
+
568
+ it("should handle the next request after the failed one", async () => {
569
+ mockSuccess();
570
+ let shouldFail = true;
571
+ client.onResponse((response) => {
572
+ if (shouldFail) {
573
+ throw new Error("Interceptor failed");
574
+ }
575
+ return response;
576
+ });
577
+
578
+ const failed = await request.send();
579
+ shouldFail = false;
580
+ const succeeded = await request.send();
581
+
582
+ expect(failed.success).toBeFalse();
583
+ expect(succeeded.success).toBeTrue();
584
+ expect(request.read()?.data).toStrictEqual({ id: 1 });
585
+ });
586
+
587
+ it("should end the request sent without the dispatcher with the error", async () => {
588
+ mockSuccess();
589
+ client.onSuccess(() => {
590
+ throw new Error("Interceptor failed");
591
+ });
592
+
593
+ const response = await request.exec();
594
+
595
+ expect(response.success).toBeFalse();
596
+ expect(response.error?.message).toBe("Interceptor failed");
597
+ });
598
+ });
599
+ });