@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,308 @@
1
+ import { createControlledClient, flushPromises, isPending } from "../../utils/controlled-adapter.utils";
2
+
3
+ describe("Mocker [ Outcomes ]", () => {
4
+ const fast = { requestTime: 0, responseTime: 0 };
5
+
6
+ const setup = () => {
7
+ const { client, calls } = createControlledClient();
8
+ const request = client.createRequest<{ response: any; error: any; payload: any }>()({
9
+ endpoint: "/mocked",
10
+ method: "POST",
11
+ });
12
+ /** Send and let the timers of the mocker pass */
13
+ const run = async <T>(sent: Promise<T>, time = 1000) => {
14
+ await vi.advanceTimersByTimeAsync(time);
15
+ return sent;
16
+ };
17
+
18
+ return { client, calls, request, run };
19
+ };
20
+
21
+ beforeEach(() => {
22
+ vi.useFakeTimers();
23
+ });
24
+
25
+ afterEach(() => {
26
+ vi.useRealTimers();
27
+ });
28
+
29
+ describe("When deciding if the mocked response is a success", () => {
30
+ it.each([
31
+ ["data only", { data: { id: 1 }, status: 200 }, true],
32
+ ["falsy data", { data: 0, status: 200 }, true],
33
+ ["an empty string as data", { data: "", status: 200 }, true],
34
+ ["null data without an error", { data: null, status: 204 }, true],
35
+ ["an error only", { error: { message: "Bad" }, status: 400 }, false],
36
+ ["null data with an error", { data: null, error: { message: "Bad" }, status: 500 }, false],
37
+ ["data together with an error", { data: { id: 1 }, error: { message: "Partial" }, status: 200 }, true],
38
+ ["data marked as a failure", { data: { id: 1 }, status: 400, success: false }, false],
39
+ ["an error marked as a failure", { error: { message: "Bad" }, status: 400, success: false }, false],
40
+ ["an error marked as a success", { error: { message: "Bad" }, status: 200, success: true }, true],
41
+ ] as const)("should treat %s accordingly", async (_, mock, success) => {
42
+ const { request, run } = setup();
43
+
44
+ const response = await run(request.setMock(() => mock as never, fast).send());
45
+
46
+ expect(response.success).toBe(success);
47
+ expect(response.status).toBe(mock.status);
48
+ });
49
+
50
+ it("should give the error of a failed mock without the data", async () => {
51
+ const { request, run } = setup();
52
+ request.setMock(() => ({ error: { message: "Bad" }, status: 400 }), fast);
53
+
54
+ const response = await run(request.send());
55
+
56
+ expect(response).toMatchObject({ data: null, error: { message: "Bad" }, status: 400, success: false });
57
+ });
58
+
59
+ it("should retry a mock which gives only an error", async () => {
60
+ const { request, run } = setup();
61
+ const mock = vi.fn(() => ({ error: { message: "Bad" }, status: 500 }));
62
+
63
+ await run(request.setRetry(2).setRetryTime(10).setMock(mock, fast).send());
64
+
65
+ expect(mock).toHaveBeenCalledTimes(3);
66
+ });
67
+
68
+ it("should give both the data and the error of a partial response", async () => {
69
+ const { request, run } = setup();
70
+ request.setMock(() => ({ data: { id: 1 }, error: { message: "Partial" }, status: 200 }), fast);
71
+
72
+ const response = await run(request.send());
73
+
74
+ expect(response).toMatchObject({ data: { id: 1 }, error: { message: "Partial" }, success: true });
75
+ });
76
+
77
+ it("should use the default extra of the adapter and the one given by the mock", async () => {
78
+ const { request, run } = setup();
79
+
80
+ const withDefault = await run(request.setMock(() => ({ data: 1, status: 200 }), fast).send());
81
+ const withOwn = await run(
82
+ request.setMock(() => ({ data: 1, status: 200, extra: { headers: { "x-mock": "1" } } }), fast).send(),
83
+ );
84
+
85
+ expect(withDefault.extra).toEqual({ headers: {} });
86
+ expect(withOwn.extra).toEqual({ headers: { "x-mock": "1" } });
87
+ });
88
+ });
89
+
90
+ describe("When the mock function is called", () => {
91
+ it("should receive the request with the values of the call", async () => {
92
+ const { client, run } = setup();
93
+ const request = client.createRequest<{ response: any; payload: any }>()({
94
+ endpoint: "/mocked/:id",
95
+ method: "POST",
96
+ });
97
+ const mock = vi.fn(() => ({ data: null, status: 200 }));
98
+ request.setMock(mock, fast);
99
+
100
+ await run(request.send({ params: { id: 7 }, payload: { name: "John" } }));
101
+ const [{ request: mocked, requestId }] = mock.mock.calls[0] as unknown as [{ request: any; requestId: string }];
102
+
103
+ expect(mocked.endpoint).toBe("/mocked/7");
104
+ expect(mocked.params).toEqual({ id: 7 });
105
+ expect(mocked.payload).toEqual({ name: "John" });
106
+ expect(requestId).toEqual(expect.any(String));
107
+ });
108
+
109
+ it("should wait for an async mock", async () => {
110
+ const { request, run } = setup();
111
+ request.setMock(async () => ({ data: "async", status: 200 }), fast);
112
+
113
+ await expect(run(request.send())).resolves.toHaveProperty("data", "async");
114
+ });
115
+
116
+ it.each([
117
+ [
118
+ "throws",
119
+ () => {
120
+ throw new Error("Broken mock");
121
+ },
122
+ ],
123
+ [
124
+ "rejects",
125
+ async () => {
126
+ throw new Error("Broken mock");
127
+ },
128
+ ],
129
+ ])("should give the error when the mock %s", async (_, mock) => {
130
+ const { request, run, client } = setup();
131
+
132
+ const response = await run(request.setMock(mock as never, fast).send());
133
+
134
+ expect(response.success).toBe(false);
135
+ expect(response.status).toBe(0);
136
+ expect(response.error.message).toBe("Broken mock");
137
+ expect(client.submitDispatcher.getQueue(request.queryKey).requests).toHaveLength(0);
138
+ });
139
+
140
+ it("should not call the real adapter", async () => {
141
+ const { request, run, calls } = setup();
142
+
143
+ await run(request.setMock(() => ({ data: 1, status: 200 }), fast).send());
144
+
145
+ expect(calls).toHaveLength(0);
146
+ });
147
+
148
+ it("should be used by exec too", async () => {
149
+ const { request, run } = setup();
150
+
151
+ const response = await run(request.setMock(() => ({ data: "exec", status: 200 }), fast).exec({}));
152
+
153
+ expect(response.data).toBe("exec");
154
+ });
155
+ });
156
+
157
+ describe("When mocking is switched off", () => {
158
+ it("should use the real adapter for a request with the disabled mock", async () => {
159
+ const { request, calls } = setup();
160
+ request.setMock(() => ({ data: "mock", status: 200 }), fast).setMockingEnabled(false);
161
+
162
+ const sent = request.send();
163
+ await flushPromises();
164
+ await calls[0].succeed("real");
165
+
166
+ await expect(sent).resolves.toHaveProperty("data", "real");
167
+ });
168
+
169
+ it("should use the mock again after enabling it", async () => {
170
+ const { request, run } = setup();
171
+ request.setMock(() => ({ data: "mock", status: 200 }), fast).setMockingEnabled(false);
172
+ request.setMockingEnabled(true);
173
+
174
+ await expect(run(request.send())).resolves.toHaveProperty("data", "mock");
175
+ });
176
+
177
+ it("should use the real adapter after clearing the mock", async () => {
178
+ const { request, calls } = setup();
179
+ request.setMock(() => ({ data: "mock", status: 200 }), fast).clearMock();
180
+
181
+ const sent = request.send();
182
+ await flushPromises();
183
+ await calls[0].succeed("real");
184
+
185
+ await expect(sent).resolves.toHaveProperty("data", "real");
186
+ });
187
+
188
+ it("should use the real adapter when mocking is disabled for the whole client", async () => {
189
+ const { client, request, calls } = setup();
190
+ request.setMock(() => ({ data: "mock", status: 200 }), fast);
191
+ client.setEnableGlobalMocking(false);
192
+
193
+ const sent = request.send();
194
+ await flushPromises();
195
+ await calls[0].succeed("real");
196
+
197
+ await expect(sent).resolves.toHaveProperty("data", "real");
198
+ });
199
+ });
200
+
201
+ describe("When the mock takes time", () => {
202
+ it("should answer after the request and the response time", async () => {
203
+ const { request } = setup();
204
+ request.setMock(() => ({ data: 1, status: 200 }), { requestTime: 100, responseTime: 200 });
205
+
206
+ const sent = request.send();
207
+ await vi.advanceTimersByTimeAsync(299);
208
+ expect(await isPending(sent)).toBe(true);
209
+ await vi.advanceTimersByTimeAsync(1);
210
+
211
+ await expect(sent).resolves.toHaveProperty("data", 1);
212
+ });
213
+
214
+ it("should report the whole upload and download", async () => {
215
+ const { request, run } = setup();
216
+ const upload: number[] = [];
217
+ const download: number[] = [];
218
+ request.setMock(() => ({ data: 1, status: 200 }), {
219
+ requestTime: 60,
220
+ responseTime: 60,
221
+ totalUploaded: 300,
222
+ totalDownloaded: 900,
223
+ });
224
+
225
+ await run(
226
+ request.send({
227
+ onUploadProgress: ({ loaded }) => upload.push(loaded),
228
+ onDownloadProgress: ({ loaded }) => download.push(loaded),
229
+ }),
230
+ );
231
+
232
+ expect(upload.at(-1)).toBe(300);
233
+ expect(download.at(-1)).toBe(900);
234
+ expect(upload).toEqual(upload.toSorted((a, b) => a - b));
235
+ expect(download).toEqual(download.toSorted((a, b) => a - b));
236
+ });
237
+
238
+ it("should call the lifecycle callbacks in order", async () => {
239
+ const { request, run } = setup();
240
+ const order: string[] = [];
241
+ request.setMock(() => ({ data: 1, status: 200 }), fast);
242
+
243
+ await run(
244
+ request.send({
245
+ onBeforeSent: () => order.push("onBeforeSent"),
246
+ onRequestStart: () => order.push("onRequestStart"),
247
+ onResponseStart: () => order.push("onResponseStart"),
248
+ onResponse: () => order.push("onResponse"),
249
+ }),
250
+ );
251
+
252
+ expect(order).toEqual(["onBeforeSent", "onRequestStart", "onResponseStart", "onResponse"]);
253
+ });
254
+
255
+ it("should give the abort error and stop reporting the progress after an abort", async () => {
256
+ const { request, run } = setup();
257
+ const onUploadProgress = vi.fn();
258
+ const onResponseStart = vi.fn();
259
+ request.setMock(() => ({ data: 1, status: 200 }), { requestTime: 1000, responseTime: 1000 });
260
+
261
+ const sent = request.send({ onUploadProgress, onResponseStart });
262
+ await vi.advanceTimersByTimeAsync(100);
263
+ request.abort();
264
+ const callsBeforeAbort = onUploadProgress.mock.calls.length;
265
+ const response = await run(sent, 5000);
266
+
267
+ expect(response.error.message).toBe("Request aborted");
268
+ expect(onUploadProgress).toHaveBeenCalledTimes(callsBeforeAbort);
269
+ expect(onResponseStart).not.toHaveBeenCalled();
270
+ });
271
+
272
+ it("should give one response for an aborted mock", async () => {
273
+ const { client, request, run } = setup();
274
+ const onResponse = vi.fn();
275
+ client.requestManager.events.onResponse(onResponse);
276
+ request.setMock(() => ({ data: 1, status: 200 }), { requestTime: 100, responseTime: 100 });
277
+
278
+ const sent = request.send();
279
+ await vi.advanceTimersByTimeAsync(50);
280
+ request.abort();
281
+ await run(sent, 5000);
282
+
283
+ expect(onResponse).toHaveBeenCalledTimes(1);
284
+ });
285
+
286
+ it("should give the timeout error when the mock is slower than its timeout", async () => {
287
+ const { request, run } = setup();
288
+ request.setMock(() => ({ data: 1, status: 200 }), { requestTime: 500, responseTime: 500, timeout: 300 });
289
+
290
+ const response = await run(request.send(), 5000);
291
+
292
+ expect(response.success).toBe(false);
293
+ expect(response.error.message).toBe("Request timeout");
294
+ });
295
+
296
+ it("should give the response when the mock is faster than its timeout", async () => {
297
+ const { client, request, run } = setup();
298
+ const onResponse = vi.fn();
299
+ client.requestManager.events.onResponse(onResponse);
300
+ request.setMock(() => ({ data: 1, status: 200 }), { requestTime: 20, responseTime: 20, timeout: 300 });
301
+
302
+ const response = await run(request.send(), 5000);
303
+
304
+ expect(response.data).toBe(1);
305
+ expect(onResponse).toHaveBeenCalledTimes(1);
306
+ });
307
+ });
308
+ });
@@ -0,0 +1,278 @@
1
+ import { waitFor } from "@testing-library/dom";
2
+
3
+ import type { ClientInstance } from "client";
4
+ import { optimistic } from "optimistic";
5
+ import type { OptimisticOperation } from "optimistic";
6
+ import type { RequestInstance } from "request";
7
+ import type { Stats, Todo } from "../../utils/optimistic.utils";
8
+ import { createControlledClient, createTodo, permutations, readCache, seedCache } from "../../utils/optimistic.utils";
9
+
10
+ type State = "pending" | "success" | "error";
11
+ type Message = { id: number; status: "sending" | "failed" };
12
+
13
+ /**
14
+ * A documented rollback pattern, applied by mutation `index`. `expected` tells what the target holds for the given
15
+ * state of every mutation - the change stays while pending or after success, and is reverted after an error.
16
+ */
17
+ type Pattern = {
18
+ name: string;
19
+ seed: (targets: Targets) => void;
20
+ operation: (targets: Targets, index: number) => OptimisticOperation<any, RequestInstance>;
21
+ read: (targets: Targets) => unknown;
22
+ expected: (states: State[]) => unknown;
23
+ };
24
+
25
+ type Targets = {
26
+ client: ClientInstance;
27
+ getTodos: RequestInstance;
28
+ getStats: RequestInstance;
29
+ getMessages: RequestInstance;
30
+ };
31
+
32
+ const ITEMS = [1, 2, 3];
33
+ const sortById = <T extends { id: number }>(list: T[] | undefined) => (list ?? []).toSorted((a, b) => a.id - b.id);
34
+
35
+ const patterns: Pattern[] = [
36
+ {
37
+ name: "re-add from previous",
38
+ seed: ({ client, getTodos }) => seedCache(client, getTodos, ITEMS.map((id) => createTodo(id))),
39
+ operation: ({ getTodos }, index) =>
40
+ optimistic(getTodos as RequestInstance)
41
+ .remove(ITEMS[index])
42
+ .rollback(({ data, previous }: { data: Todo[]; previous: Todo[] }) => {
43
+ const removed = previous.find((todo) => todo.id === ITEMS[index]);
44
+ return removed ? [...data, removed] : data;
45
+ }),
46
+ read: ({ client, getTodos }) => sortById(readCache<Todo[]>(client, getTodos)),
47
+ expected: (states) =>
48
+ ITEMS.filter((_, index) => states[index] === undefined || states[index] === "error").map((id) =>
49
+ createTodo(id),
50
+ ),
51
+ },
52
+ {
53
+ name: "restore one item",
54
+ seed: ({ client, getTodos }) => seedCache(client, getTodos, ITEMS.map((id) => createTodo(id))),
55
+ operation: ({ getTodos }, index) =>
56
+ optimistic(getTodos as RequestInstance)
57
+ .patch(ITEMS[index], { done: true })
58
+ .rollback(({ data, previous }: { data: Todo[]; previous: Todo[] }) => {
59
+ const before = previous.find((todo) => todo.id === ITEMS[index]);
60
+ return data.map((todo) => (todo.id === ITEMS[index] && before ? before : todo));
61
+ }),
62
+ read: ({ client, getTodos }) => readCache<Todo[]>(client, getTodos),
63
+ expected: (states) =>
64
+ ITEMS.map((id, index) =>
65
+ createTodo(id, { done: states[index] === "pending" || states[index] === "success" }),
66
+ ),
67
+ },
68
+ {
69
+ name: "opposite increment",
70
+ seed: ({ client, getStats }) => seedCache(client, getStats, { total: 10, done: 0 }),
71
+ operation: ({ getStats }, index) =>
72
+ optimistic(getStats as RequestInstance)
73
+ .increment("total", index + 1)
74
+ .rollback(({ data }: { data: Stats }) => ({ ...data, total: data.total - (index + 1) })),
75
+ read: ({ client, getStats }) => readCache<Stats>(client, getStats),
76
+ expected: (states) => ({
77
+ total: states.reduce((sum, state, index) => (state === "error" ? sum : sum + index + 1), 10),
78
+ done: 0,
79
+ }),
80
+ },
81
+ {
82
+ name: "mark as failed",
83
+ seed: ({ client, getMessages }) => seedCache(client, getMessages, []),
84
+ operation: ({ getMessages }, index) =>
85
+ optimistic(getMessages as RequestInstance)
86
+ .insert({ id: ITEMS[index], status: "sending" })
87
+ .rollback(({ data, reason }: { data: Message[]; reason: string }) =>
88
+ reason === "error"
89
+ ? data.map((message) => (message.id === ITEMS[index] ? { ...message, status: "failed" } : message))
90
+ : data.filter((message) => message.id !== ITEMS[index]),
91
+ ),
92
+ read: ({ client, getMessages }) => sortById(readCache<Message[]>(client, getMessages)),
93
+ expected: (states) =>
94
+ states.flatMap((state, index) =>
95
+ state ? [{ id: ITEMS[index], status: state === "error" ? "failed" : "sending" }] : [],
96
+ ),
97
+ },
98
+ ];
99
+
100
+ const createSetup = (pattern: Pattern) => {
101
+ const { client, calls } = createControlledClient();
102
+ const targets: Targets = {
103
+ client,
104
+ getTodos: client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" }),
105
+ getStats: client.createRequest<{ response: Stats }>()({ endpoint: "/stats" }),
106
+ getMessages: client.createRequest<{ response: Message[] }>()({ endpoint: "/messages" }),
107
+ };
108
+ pattern.seed(targets);
109
+ const invalidate = vi.spyOn(client.cache, "invalidate");
110
+ const mutation = client.createRequest<{ response: null }>()({ endpoint: "/mutations/:index", method: "POST" });
111
+
112
+ /** Sends mutation `index` and waits until it reaches the network */
113
+ const send = async (index: number) => {
114
+ let requestId = "";
115
+ const promise = mutation.send({
116
+ params: { index },
117
+ optimistic: [pattern.operation(targets, index)],
118
+ onBeforeSent: (data) => {
119
+ requestId = data.requestId;
120
+ },
121
+ });
122
+ await waitFor(
123
+ () => {
124
+ expect(calls.some((call) => call.requestId === requestId)).toBeTrue();
125
+ },
126
+ { interval: 1 },
127
+ );
128
+ const call = calls.find((item) => item.requestId === requestId)!;
129
+ return { promise, call };
130
+ };
131
+
132
+ return { targets, invalidate, send };
133
+ };
134
+
135
+ const outcomeCombinations = (count: number): ("success" | "error")[][] => {
136
+ if (count === 0) {
137
+ return [[]];
138
+ }
139
+ return outcomeCombinations(count - 1).flatMap((rest) => [
140
+ ["success" as const, ...rest],
141
+ ["error" as const, ...rest],
142
+ ]);
143
+ };
144
+
145
+ const scenarios = [2, 3].flatMap((count) => {
146
+ const indexes = Array.from({ length: count }, (_, index) => index);
147
+ return permutations(indexes).flatMap((order) =>
148
+ outcomeCombinations(count).map((outcomes) => ({ count, order, outcomes })),
149
+ );
150
+ });
151
+
152
+ describe("Optimistic [ Concurrency ]", () => {
153
+ describe.each(patterns)("when using the $name pattern", (pattern) => {
154
+ it.each(scenarios)(
155
+ "should hold the right value after each settle ($count mutations, order $order, outcomes $outcomes)",
156
+ async ({ count, order, outcomes }) => {
157
+ const { targets, invalidate, send } = createSetup(pattern);
158
+ const states: State[] = [];
159
+ const sent = [];
160
+
161
+ for (let index = 0; index < count; index += 1) {
162
+ // eslint-disable-next-line no-await-in-loop
163
+ sent.push(await send(index));
164
+ states[index] = "pending";
165
+ expect(pattern.read(targets)).toStrictEqual(pattern.expected(states));
166
+ }
167
+
168
+ for (const [step, index] of order.entries()) {
169
+ const outcome = outcomes[index];
170
+ sent[index].call.respond(outcome === "success" ? { data: null } : { error: new Error("Failed") });
171
+ // eslint-disable-next-line no-await-in-loop
172
+ await sent[index].promise;
173
+ states[index] = outcome;
174
+
175
+ expect(pattern.read(targets)).toStrictEqual(pattern.expected(states));
176
+ // The refresh waits for the last pending mutation on the key
177
+ expect(invalidate).toHaveBeenCalledTimes(step === count - 1 ? 1 : 0);
178
+ }
179
+ },
180
+ );
181
+ });
182
+
183
+ describe("when two mutations change the same field", () => {
184
+ const createToggles = () => {
185
+ const { client, calls } = createControlledClient();
186
+ const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
187
+ seedCache(client, getTodos, [createTodo(1)]);
188
+ const toggle = client
189
+ .createRequest<{ response: Todo; payload: { done: boolean } }>()({ endpoint: "/todos/:id", method: "PATCH" })
190
+ .setParams({ id: 1 })
191
+ .setOptimistic(({ payload }) => [
192
+ optimistic(getTodos)
193
+ .patch(1, payload)
194
+ .rollback(({ data, previous }) => {
195
+ const before = previous.find((todo) => todo.id === 1);
196
+ return data.map((todo) => (todo.id === 1 && before ? before : todo));
197
+ }),
198
+ ]);
199
+ const done = () => readCache<Todo[]>(client, getTodos)?.[0].done;
200
+ return { client, calls, getTodos, toggle, done };
201
+ };
202
+
203
+ it("should restore the value from before the failed toggle, then refresh to the server value", async () => {
204
+ const { client, calls, getTodos, toggle, done } = createToggles();
205
+ const invalidate = vi.spyOn(client.cache, "invalidate");
206
+
207
+ const first = toggle.send({ payload: { done: true } });
208
+ const second = toggle.send({ payload: { done: false } });
209
+ await waitFor(() => expect(calls).toHaveLength(2), { interval: 1 });
210
+ expect(done()).toBeFalse();
211
+
212
+ // The later toggle succeeded, the earlier one fails and restores what it saw: `false`
213
+ calls[1].respond({ data: createTodo(1) });
214
+ await second;
215
+ expect(done()).toBeFalse();
216
+ calls[0].respond({ error: new Error("Failed") });
217
+ await first;
218
+ expect(done()).toBeFalse();
219
+ expect(invalidate).toHaveBeenCalledTimes(1);
220
+
221
+ const refresh = getTodos.send();
222
+ await waitFor(() => expect(calls).toHaveLength(3), { interval: 1 });
223
+ calls[2].respond({ data: [createTodo(1, { done: false })] });
224
+ await refresh;
225
+ expect(done()).toBeFalse();
226
+ });
227
+
228
+ it("should document the rollback of the later toggle overwriting the earlier success", async () => {
229
+ const { calls, getTodos, toggle, done } = createToggles();
230
+
231
+ const first = toggle.send({ payload: { done: true } });
232
+ const second = toggle.send({ payload: { done: false } });
233
+ await waitFor(() => expect(calls).toHaveLength(2), { interval: 1 });
234
+
235
+ calls[0].respond({ data: createTodo(1, { done: true }) });
236
+ await first;
237
+ // The later toggle fails and restores its own previous value - the earlier, successful `true`
238
+ calls[1].respond({ error: new Error("Failed") });
239
+ await second;
240
+ expect(done()).toBeTrue();
241
+
242
+ // The server holds `true` too, so the refresh confirms it
243
+ const refresh = getTodos.send();
244
+ await waitFor(() => expect(calls).toHaveLength(3), { interval: 1 });
245
+ calls[2].respond({ data: [createTodo(1, { done: true })] });
246
+ await refresh;
247
+ expect(done()).toBeTrue();
248
+ });
249
+ });
250
+
251
+ describe("when mutations target different keys", () => {
252
+ it("should refresh each key once its own last mutation settled", async () => {
253
+ const { client, calls } = createControlledClient();
254
+ const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
255
+ const getStats = client.createRequest<{ response: Stats }>()({ endpoint: "/stats" });
256
+ seedCache(client, getTodos, [createTodo(1)]);
257
+ seedCache(client, getStats, { total: 1, done: 0 });
258
+ const invalidate = vi.spyOn(client.cache, "invalidate");
259
+ const mutation = client.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" });
260
+
261
+ const both = mutation.send({
262
+ optimistic: [optimistic(getTodos).patch(1, { done: true }), optimistic(getStats).increment("done", 1)],
263
+ });
264
+ const statsOnly = mutation.send({ optimistic: [optimistic(getStats).increment("total", 1)] });
265
+ await waitFor(() => expect(calls).toHaveLength(2), { interval: 1 });
266
+
267
+ calls[0].respond({ data: null });
268
+ await both;
269
+ expect(invalidate).toHaveBeenCalledTimes(1);
270
+ expect(invalidate).toHaveBeenCalledWith(getTodos);
271
+
272
+ calls[1].respond({ data: null });
273
+ await statsOnly;
274
+ expect(invalidate).toHaveBeenCalledTimes(2);
275
+ expect(invalidate).toHaveBeenLastCalledWith(getStats);
276
+ });
277
+ });
278
+ });