@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,270 @@
1
+ import { waitFor } from "@testing-library/dom";
2
+
3
+ import { optimistic, resetOptimisticState } from "optimistic";
4
+ import type { Todo } from "../../utils/optimistic.utils";
5
+ import { createControlledClient, createTodo, readCache, seedCache } from "../../utils/optimistic.utils";
6
+
7
+ const BEFORE = [createTodo(1), createTodo(2)];
8
+ const OPTIMISTIC = [createTodo(1, { done: true }), createTodo(2)];
9
+ const AFTER = [createTodo(1, { done: true }), createTodo(2, { title: "changed on server" })];
10
+
11
+ const createSetup = (options: { seeded?: boolean } = {}) => {
12
+ const { client, calls, waitForCall } = createControlledClient();
13
+ const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
14
+ const toggle = client
15
+ .createRequest<{ response: Todo; payload: Partial<Todo> }>()({ endpoint: "/todos/:todoId", method: "PATCH" })
16
+ .setParams({ todoId: 1 })
17
+ .setOptimistic(({ params, payload }) => [
18
+ optimistic(getTodos)
19
+ .patch(params.todoId, payload)
20
+ .rollback(({ data, previous }) => {
21
+ const before = previous.find((todo) => todo.id === params.todoId);
22
+ return data.map((todo) => (todo.id === params.todoId && before ? before : todo));
23
+ }),
24
+ ]);
25
+
26
+ if (options.seeded !== false) {
27
+ seedCache(client, getTodos, BEFORE);
28
+ }
29
+
30
+ const invalidate = vi.spyOn(client.cache, "invalidate");
31
+ const todos = () => readCache<Todo[]>(client, getTodos);
32
+ const callOf = (requestId: string) => calls.find((call) => call.requestId === requestId);
33
+
34
+ /** Starts a request and resolves to its id once it reaches the network */
35
+ const start = async (send: (onBeforeSent: (data: { requestId: string }) => void) => Promise<unknown>) => {
36
+ let requestId = "";
37
+ const promise = send(({ requestId: id }) => {
38
+ requestId = id;
39
+ });
40
+ await waitFor(
41
+ () => {
42
+ expect(callOf(requestId)).toBeDefined();
43
+ },
44
+ { interval: 1 },
45
+ );
46
+ return { promise, call: callOf(requestId)! };
47
+ };
48
+
49
+ const startFetch = () => start((onBeforeSent) => getTodos.send({ onBeforeSent }));
50
+ const startMutation = () => start((onBeforeSent) => toggle.send({ payload: { done: true }, onBeforeSent }));
51
+
52
+ return { client, calls, waitForCall, getTodos, toggle, invalidate, todos, startFetch, startMutation };
53
+ };
54
+
55
+ type Order = "fetch-first" | "mutation-first";
56
+ type Landing = "while-pending" | "after-settle";
57
+ type Outcome = "success" | "error";
58
+
59
+ const cases: { order: Order; landing: Landing; outcome: Outcome }[] = (
60
+ ["fetch-first", "mutation-first"] as const
61
+ ).flatMap((order) =>
62
+ (["while-pending", "after-settle"] as const).flatMap((landing) =>
63
+ (["success", "error"] as const).map((outcome) => ({ order, landing, outcome })),
64
+ ),
65
+ );
66
+
67
+ describe("Optimistic [ Races with fetches ]", () => {
68
+ describe("when a fetch started before the mutation settled", () => {
69
+ it.each(cases)(
70
+ "should discard its response ($order, lands $landing, mutation $outcome)",
71
+ async ({ order, landing, outcome }) => {
72
+ const setup = createSetup();
73
+
74
+ const first = order === "fetch-first" ? await setup.startFetch() : await setup.startMutation();
75
+ const second = order === "fetch-first" ? await setup.startMutation() : await setup.startFetch();
76
+ const fetch = order === "fetch-first" ? first : second;
77
+ const mutation = order === "fetch-first" ? second : first;
78
+
79
+ expect(setup.todos()).toStrictEqual(OPTIMISTIC);
80
+
81
+ const settleMutation = async () => {
82
+ mutation.call.respond(outcome === "success" ? { data: OPTIMISTIC[0] } : { error: new Error("Failed") });
83
+ await mutation.promise;
84
+ };
85
+
86
+ if (landing === "after-settle") {
87
+ await settleMutation();
88
+ }
89
+
90
+ // The server answers with what it had when the fetch was handled - before the change
91
+ fetch.call.respond({ data: BEFORE });
92
+ const fetchResponse = (await fetch.promise) as { data: Todo[] };
93
+
94
+ // The caller still receives its response, only the cache write is skipped
95
+ expect(fetchResponse.data).toStrictEqual(BEFORE);
96
+ expect(setup.todos()).toStrictEqual(landing === "after-settle" && outcome === "error" ? BEFORE : OPTIMISTIC);
97
+
98
+ if (landing === "while-pending") {
99
+ expect(setup.invalidate).not.toHaveBeenCalled();
100
+ await settleMutation();
101
+ }
102
+
103
+ expect(setup.todos()).toStrictEqual(outcome === "success" ? OPTIMISTIC : BEFORE);
104
+ // One refresh, once both the mutation and the stale fetch are done
105
+ expect(setup.invalidate).toHaveBeenCalledTimes(1);
106
+ expect(setup.invalidate).toHaveBeenCalledWith(setup.getTodos);
107
+
108
+ // The refresh fetch is written
109
+ const refresh = await setup.startFetch();
110
+ refresh.call.respond({ data: AFTER });
111
+ await refresh.promise;
112
+ expect(setup.todos()).toStrictEqual(AFTER);
113
+ },
114
+ );
115
+ });
116
+
117
+ describe("when a fetch starts after the mutation settled", () => {
118
+ it.each(["success", "error"] as const)("should write its response (mutation %s)", async (outcome) => {
119
+ const setup = createSetup();
120
+ const mutation = await setup.startMutation();
121
+ mutation.call.respond(outcome === "success" ? { data: OPTIMISTIC[0] } : { error: new Error("Failed") });
122
+ await mutation.promise;
123
+
124
+ const fetch = await setup.startFetch();
125
+ fetch.call.respond({ data: AFTER });
126
+ await fetch.promise;
127
+
128
+ expect(setup.todos()).toStrictEqual(AFTER);
129
+ });
130
+ });
131
+
132
+ describe("when the stale fetch is still running at settle", () => {
133
+ it("should refresh only after the stale fetch is done", async () => {
134
+ const setup = createSetup();
135
+ const fetch = await setup.startFetch();
136
+ const mutation = await setup.startMutation();
137
+
138
+ mutation.call.respond({ data: OPTIMISTIC[0] });
139
+ await mutation.promise;
140
+
141
+ expect(setup.invalidate).not.toHaveBeenCalled();
142
+
143
+ fetch.call.respond({ data: BEFORE });
144
+ await fetch.promise;
145
+
146
+ expect(setup.invalidate).toHaveBeenCalledTimes(1);
147
+ });
148
+
149
+ it("should accept the retried attempt of a stale fetch", async () => {
150
+ const setup = createSetup();
151
+ const retried = setup.getTodos.setRetry(1).setRetryTime(0);
152
+ let requestId = "";
153
+ const promise = retried.send({
154
+ onBeforeSent: ({ requestId: id }) => {
155
+ requestId = id;
156
+ },
157
+ });
158
+ const firstAttempt = await setup.waitForCall(0);
159
+ const mutation = await setup.startMutation();
160
+ mutation.call.respond({ data: OPTIMISTIC[0] });
161
+ await mutation.promise;
162
+
163
+ // The attempt in flight at settle fails, the retry starts after the settle
164
+ firstAttempt.respond({ error: new Error("Network") });
165
+ const secondAttempt = await setup.waitForCall(2);
166
+ expect(secondAttempt.requestId).toBe(requestId);
167
+ secondAttempt.respond({ data: AFTER });
168
+ await promise;
169
+
170
+ expect(setup.todos()).toStrictEqual(AFTER);
171
+ });
172
+ });
173
+
174
+ describe("when the key has no data", () => {
175
+ it("should write the first load even while a mutation is pending", async () => {
176
+ const setup = createSetup({ seeded: false });
177
+ const mutation = await setup.startMutation();
178
+ const fetch = await setup.startFetch();
179
+
180
+ fetch.call.respond({ data: BEFORE });
181
+ await fetch.promise;
182
+
183
+ expect(setup.todos()).toStrictEqual(BEFORE);
184
+
185
+ mutation.call.respond({ data: OPTIMISTIC[0] });
186
+ await mutation.promise;
187
+
188
+ expect(setup.invalidate).toHaveBeenCalledWith(setup.getTodos);
189
+ });
190
+ });
191
+
192
+ describe("when the cache is written by hand", () => {
193
+ it("should never block manual writes while a mutation is pending", async () => {
194
+ const setup = createSetup();
195
+ const mutation = await setup.startMutation();
196
+
197
+ seedCache(setup.client, setup.getTodos, AFTER);
198
+ setup.client.cache.update(setup.getTodos, (prev) => ({ data: [...(prev?.data ?? []), createTodo(3)] }));
199
+
200
+ expect(setup.todos()).toStrictEqual([...AFTER, createTodo(3)]);
201
+ mutation.call.respond({ data: OPTIMISTIC[0] });
202
+ await mutation.promise;
203
+ });
204
+ });
205
+
206
+ describe("when other keys are fetched", () => {
207
+ it("should write responses of keys without pending mutations", async () => {
208
+ const setup = createSetup();
209
+ const getOther = setup.client.createRequest<{ response: Todo[] }>()({ endpoint: "/other" });
210
+ seedCache(setup.client, getOther, BEFORE);
211
+ const mutation = await setup.startMutation();
212
+
213
+ const promise = getOther.send();
214
+ const call = await setup.waitForCall(1);
215
+ call.respond({ data: AFTER });
216
+ await promise;
217
+
218
+ expect(readCache(setup.client, getOther)).toStrictEqual(AFTER);
219
+ mutation.call.respond({ data: OPTIMISTIC[0] });
220
+ await mutation.promise;
221
+ });
222
+ });
223
+
224
+ describe("when the client is cleared", () => {
225
+ it("should drop the pending state so later fetches are written", async () => {
226
+ const setup = createSetup();
227
+ await setup.startMutation();
228
+
229
+ setup.client.clear();
230
+ seedCache(setup.client, setup.getTodos, BEFORE);
231
+ const fetch = await setup.startFetch();
232
+ fetch.call.respond({ data: AFTER });
233
+ await fetch.promise;
234
+
235
+ expect(setup.todos()).toStrictEqual(AFTER);
236
+ });
237
+ });
238
+
239
+ describe("when the pending state is reset while a mutation is in flight", () => {
240
+ it("should still settle the mutation", async () => {
241
+ const setup = createSetup();
242
+ const mutation = await setup.startMutation();
243
+
244
+ resetOptimisticState(setup.client);
245
+ mutation.call.respond({ error: new Error("Failed") });
246
+ await mutation.promise;
247
+
248
+ expect(setup.todos()).toStrictEqual(BEFORE);
249
+ expect(setup.invalidate).not.toHaveBeenCalled();
250
+ });
251
+ });
252
+
253
+ describe("when a scope is used", () => {
254
+ it("should only guard the scope of the target", async () => {
255
+ const setup = createSetup();
256
+ const scoped = setup.getTodos.setScope("user-1");
257
+ seedCache(setup.client, scoped, BEFORE);
258
+ const mutation = await setup.startMutation();
259
+
260
+ const promise = scoped.send();
261
+ const call = await setup.waitForCall(1);
262
+ call.respond({ data: AFTER });
263
+ await promise;
264
+
265
+ expect(readCache(setup.client, scoped)).toStrictEqual(AFTER);
266
+ mutation.call.respond({ data: OPTIMISTIC[0] });
267
+ await mutation.promise;
268
+ });
269
+ });
270
+ });
@@ -0,0 +1,191 @@
1
+ import { waitFor } from "@testing-library/dom";
2
+
3
+ import { optimistic } from "optimistic";
4
+ import type { OptimisticOperation } from "optimistic";
5
+ import type { ControlledCall } from "../../utils/optimistic.utils";
6
+ import { createControlledClient, createRandom, readCache, seedCache } from "../../utils/optimistic.utils";
7
+
8
+ /** `version` grows with every change the server accepts for the item */
9
+ type Item = { id: number; value: number; version: number };
10
+
11
+ type Pending = { call: ControlledCall; promise: Promise<unknown> };
12
+ type PendingMutation = Pending & { commitOnServer: () => void };
13
+ type PendingFetch = Pending & { snapshot: Item[] };
14
+
15
+ const SEEDS = Array.from({ length: 40 }, (_, index) => index + 1);
16
+ const STEPS = 60;
17
+
18
+ const sortById = (items: Item[] | undefined) => (items ?? []).toSorted((a, b) => a.id - b.id);
19
+ const copy = (items: Item[]) => items.map((item) => ({ ...item }));
20
+
21
+ /**
22
+ * Random sequences of mutations, their outcomes, fetches answered with the server data of the moment they were
23
+ * handled, and deleted entries - against a simulated server. Every rollback uses a documented pattern.
24
+ */
25
+ const run = async (seed: number) => {
26
+ const random = createRandom(seed);
27
+ const { client, calls } = createControlledClient();
28
+ const getItems = client.createRequest<{ response: Item[] }>()({ endpoint: "/items" });
29
+ const mutation = client.createRequest<{ response: null }>()({ endpoint: "/items/:id", method: "POST" });
30
+
31
+ let server: Item[] = [1, 2, 3, 4].map((id) => ({ id, value: 0, version: 0 }));
32
+ let nextId = 5;
33
+ seedCache(client, getItems, copy(server));
34
+
35
+ /** Lowest version of every item the cache may hold, raised by every fetch response written to the cache */
36
+ const floor = new Map<number, number>();
37
+ const mutations: PendingMutation[] = [];
38
+ const fetches: PendingFetch[] = [];
39
+ const read = () => readCache<Item[]>(client, getItems);
40
+
41
+ const checkInvariants = (step: string) => {
42
+ const items = read() ?? [];
43
+ const ids = items.map((item) => item.id);
44
+ expect(new Set(ids).size, `${step}: duplicated items ${ids}`).toBe(ids.length);
45
+ items.forEach((item) => {
46
+ const minimum = floor.get(item.id) ?? 0;
47
+ expect(item.version, `${step}: item ${item.id} went back to an older server version`).toBeGreaterThanOrEqual(
48
+ minimum,
49
+ );
50
+ });
51
+ };
52
+
53
+ const waitForCall = async (getRequestId: () => string) => {
54
+ await waitFor(() => expect(calls.some((call) => call.requestId === getRequestId())).toBeTrue(), {
55
+ interval: 1,
56
+ });
57
+ return calls.find((call) => call.requestId === getRequestId())!;
58
+ };
59
+
60
+ const startMutation = async () => {
61
+ const kind = random.pick(["patch", "remove", "insert"] as const);
62
+ const id = kind === "insert" ? nextId++ : random.pick([1, 2, 3, 4, 5, 6]);
63
+ const value = random.int(100);
64
+ let operation: OptimisticOperation<Item[], any>;
65
+ let commitOnServer: () => void;
66
+
67
+ if (kind === "patch") {
68
+ operation = optimistic(getItems)
69
+ .patch(id, { value })
70
+ .rollback(({ data, previous }) => {
71
+ const before = previous.find((item) => item.id === id);
72
+ return data.map((item) => (item.id === id && before ? before : item));
73
+ });
74
+ commitOnServer = () => {
75
+ server = server.map((item) => (item.id === id ? { ...item, value, version: item.version + 1 } : item));
76
+ };
77
+ } else if (kind === "remove") {
78
+ operation = optimistic(getItems)
79
+ .remove(id)
80
+ .rollback(({ data, previous }) => {
81
+ const removed = previous.find((item) => item.id === id);
82
+ return removed ? [...data, removed] : data;
83
+ });
84
+ commitOnServer = () => {
85
+ server = server.filter((item) => item.id !== id);
86
+ };
87
+ } else {
88
+ operation = optimistic(getItems)
89
+ .insert({ id, value, version: 0 })
90
+ .rollback(({ data }) => data.filter((item) => item.id !== id));
91
+ commitOnServer = () => {
92
+ server = [...server, { id, value, version: 0 }];
93
+ };
94
+ }
95
+
96
+ let requestId = "";
97
+ const promise = mutation.send({
98
+ params: { id },
99
+ optimistic: [operation],
100
+ onBeforeSent: (data) => {
101
+ requestId = data.requestId;
102
+ },
103
+ });
104
+ const call = await waitForCall(() => requestId);
105
+ mutations.push({ call, promise, commitOnServer });
106
+ };
107
+
108
+ const settleMutation = async (index: number, success: boolean) => {
109
+ const [settled] = mutations.splice(index, 1);
110
+ if (success) {
111
+ settled.commitOnServer();
112
+ settled.call.respond({ data: null });
113
+ } else {
114
+ settled.call.respond({ error: new Error("Rejected") });
115
+ }
116
+ await settled.promise;
117
+ };
118
+
119
+ const startFetch = async () => {
120
+ let requestId = "";
121
+ const promise = getItems.send({
122
+ onBeforeSent: (data) => {
123
+ requestId = data.requestId;
124
+ },
125
+ });
126
+ const call = await waitForCall(() => requestId);
127
+ // The server reads its data when it handles the request
128
+ fetches.push({ call, promise, snapshot: copy(server) });
129
+ };
130
+
131
+ const answerFetch = async (index: number) => {
132
+ const [answered] = fetches.splice(index, 1);
133
+ let written = false;
134
+ const unmount = client.cache.events.onDataByKey(getItems.cacheKey, () => {
135
+ written = true;
136
+ });
137
+ answered.call.respond({ data: answered.snapshot });
138
+ await answered.promise;
139
+ unmount();
140
+ if (written) {
141
+ expect(sortById(read())).toStrictEqual(sortById(answered.snapshot));
142
+ answered.snapshot.forEach((item) => floor.set(item.id, Math.max(floor.get(item.id) ?? 0, item.version)));
143
+ }
144
+ };
145
+
146
+ for (let step = 0; step < STEPS; step += 1) {
147
+ const action = random.int(10);
148
+ const label = `seed ${seed}, step ${step}`;
149
+
150
+ if (action < 3 || (mutations.length === 0 && action < 6)) {
151
+ // eslint-disable-next-line no-await-in-loop
152
+ await startMutation();
153
+ } else if (action < 6) {
154
+ // eslint-disable-next-line no-await-in-loop
155
+ await settleMutation(random.int(mutations.length), random.next() < 0.6);
156
+ } else if (action < 8 || fetches.length === 0) {
157
+ // eslint-disable-next-line no-await-in-loop
158
+ await startFetch();
159
+ } else if (action < 9) {
160
+ // eslint-disable-next-line no-await-in-loop
161
+ await answerFetch(random.int(fetches.length));
162
+ } else {
163
+ client.cache.delete(getItems.cacheKey);
164
+ }
165
+
166
+ checkInvariants(label);
167
+ }
168
+
169
+ // Everything settles in a random order
170
+ while (mutations.length > 0 || fetches.length > 0) {
171
+ if (mutations.length > 0 && (random.next() < 0.5 || fetches.length === 0)) {
172
+ // eslint-disable-next-line no-await-in-loop
173
+ await settleMutation(random.int(mutations.length), random.next() < 0.6);
174
+ } else {
175
+ // eslint-disable-next-line no-await-in-loop
176
+ await answerFetch(random.int(fetches.length));
177
+ }
178
+ checkInvariants(`seed ${seed}, settling`);
179
+ }
180
+
181
+ // Nothing is pending anymore, so the refresh is written and the cache matches the server
182
+ await startFetch();
183
+ await answerFetch(0);
184
+ expect(sortById(read())).toStrictEqual(sortById(server));
185
+ };
186
+
187
+ describe("Optimistic [ Randomized invariants ]", () => {
188
+ it.each(SEEDS)("should converge to the server data and never go back in time (seed %i)", async (seed) => {
189
+ await run(seed);
190
+ });
191
+ });