@hyper-fetch/plugin-devtools 9.9.0 → 10.1.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.
@@ -0,0 +1,427 @@
1
+ import type { CacheValueType } from "@hyper-fetch/core";
2
+ import { Client } from "@hyper-fetch/core";
3
+ import type { AddressInfo } from "net";
4
+ import type { WebSocket } from "ws";
5
+ import { WebSocket as NodeWebSocket, WebSocketServer } from "ws";
6
+
7
+ import type { BaseMessagePayload } from "../../src/index";
8
+ import {
9
+ CoreEvents,
10
+ CustomEvents,
11
+ DevtoolsPlugin,
12
+ EventSourceType,
13
+ InternalEvents,
14
+ MessageOrigin,
15
+ MessageType,
16
+ SocketTopics,
17
+ } from "../../src/index";
18
+
19
+ type ReceivedMessage = { topic: string; data: BaseMessagePayload };
20
+
21
+ /**
22
+ * Stands in for the HyperFlow server: records what the plugin emits and sends it messages the way HyperFlow does.
23
+ */
24
+ const createHyperFlowServer = async () => {
25
+ // A random port can be taken by another process (EADDRINUSE never emits "listening"), the system picks a free one
26
+ const wss = new WebSocketServer({ port: 0 });
27
+ await new Promise<void>((resolve) => {
28
+ wss.once("listening", () => resolve());
29
+ });
30
+ const { port } = wss.address() as AddressInfo;
31
+
32
+ const received: ReceivedMessage[] = [];
33
+ let plugin: WebSocket | null = null;
34
+ const queries: string[] = [];
35
+
36
+ wss.on("connection", (ws, request) => {
37
+ plugin = ws;
38
+ queries.push(request.url ?? "");
39
+ ws.on("message", (raw) => {
40
+ received.push(JSON.parse(raw.toString()));
41
+ });
42
+ });
43
+
44
+ const send = (data: Partial<BaseMessagePayload> & Record<string, unknown>) => {
45
+ plugin?.send(JSON.stringify({ topic: SocketTopics.PLUGIN_LISTENER, data }));
46
+ };
47
+
48
+ const sendEvent = (eventSource: EventSourceType, eventName: CoreEvents, eventData: unknown) => {
49
+ send({
50
+ messageType: MessageType.EVENT,
51
+ eventSource,
52
+ eventName,
53
+ eventData,
54
+ connectionName: "App",
55
+ origin: MessageOrigin.APP,
56
+ isTriggeredExternally: true,
57
+ });
58
+ };
59
+
60
+ const initializeApp = () => {
61
+ send({ messageType: MessageType.INTERNAL, eventType: InternalEvents.APP_INITIALIZED });
62
+ };
63
+
64
+ const close = async () => {
65
+ wss.clients.forEach((ws) => ws.terminate());
66
+ await new Promise((resolve) => {
67
+ wss.close(resolve);
68
+ });
69
+ };
70
+
71
+ const events = () => received.filter(({ data }) => data.messageType === MessageType.EVENT).map(({ data }) => data);
72
+
73
+ return {
74
+ port,
75
+ received,
76
+ queries,
77
+ events,
78
+ send,
79
+ sendEvent,
80
+ initializeApp,
81
+ close,
82
+ isConnected: () => !!plugin,
83
+ };
84
+ };
85
+
86
+ describe("DevtoolsPlugin [ Event handler ]", () => {
87
+ let server: Awaited<ReturnType<typeof createHyperFlowServer>>;
88
+ let client: Client;
89
+ let plugin: ReturnType<typeof DevtoolsPlugin>;
90
+
91
+ beforeEach(async () => {
92
+ server = await createHyperFlowServer();
93
+ client = new Client({ url: "http://localhost:5000" });
94
+ plugin = DevtoolsPlugin({ appName: "App", url: `ws://localhost:${server.port}`, environment: "staging" });
95
+ client.addPlugin(plugin);
96
+ await vi.waitFor(() => expect(plugin.data.eventHandler?.isConnected).toBe(true));
97
+ });
98
+
99
+ afterEach(async () => {
100
+ const socket = plugin.data.eventHandler?.socket;
101
+ if (socket) {
102
+ socket.reconnectAttempts = 0;
103
+ await socket.disconnect();
104
+ }
105
+ await server.close();
106
+ });
107
+
108
+ const initialize = async () => {
109
+ server.initializeApp();
110
+ await vi.waitFor(() => expect(plugin.data.eventHandler?.isInitialized).toBe(true));
111
+ };
112
+
113
+ const createCacheValue = (overrides: Partial<CacheValueType> = {}): CacheValueType => ({
114
+ data: { id: 1 },
115
+ error: null,
116
+ status: 200,
117
+ success: true,
118
+ extra: { headers: {} },
119
+ requestTimestamp: Date.now(),
120
+ responseTimestamp: Date.now(),
121
+ retries: 0,
122
+ isCanceled: false,
123
+ isOffline: false,
124
+ willRetry: false,
125
+ addedTimestamp: Date.now(),
126
+ triggerTimestamp: Date.now(),
127
+ cacheKey: "GET_/users",
128
+ scope: null,
129
+ staleTime: 60_000,
130
+ cacheTime: 120_000,
131
+ version: client.cache.version,
132
+ cached: true,
133
+ hydrated: false,
134
+ ...overrides,
135
+ });
136
+
137
+ describe("when connecting", () => {
138
+ it("should identify itself as a plugin of the application", () => {
139
+ const query = new URLSearchParams(server.queries[0].replace(/^.*\?/, ""));
140
+ expect(query.get("connectionName")).toBe("App");
141
+ expect(query.get("origin")).toBe(MessageOrigin.PLUGIN);
142
+ });
143
+
144
+ it("should introduce the client to HyperFlow", async () => {
145
+ await vi.waitFor(() => expect(server.received.length).toBeGreaterThan(0));
146
+
147
+ const [handshake] = server.received;
148
+ expect(handshake.topic).toBe(SocketTopics.PLUGIN_EMITTER);
149
+ expect(handshake.data).toMatchObject({
150
+ messageType: MessageType.INTERNAL,
151
+ eventType: InternalEvents.PLUGIN_INITIALIZED,
152
+ connectionName: "App",
153
+ environment: "staging",
154
+ origin: MessageOrigin.PLUGIN,
155
+ clientOptions: { url: "http://localhost:5000" },
156
+ adapterOptions: { name: client.adapter.name },
157
+ });
158
+ });
159
+
160
+ it("should default the environment to the application name", async () => {
161
+ const other = await createHyperFlowServer();
162
+ const otherPlugin = DevtoolsPlugin({ appName: "Other", url: `ws://localhost:${other.port}` });
163
+ new Client({ url: "http://localhost:5000" }).addPlugin(otherPlugin);
164
+
165
+ await vi.waitFor(() => expect(other.received.length).toBeGreaterThan(0));
166
+ expect(other.received[0].data.environment).toBe("Other");
167
+
168
+ otherPlugin.data.eventHandler!.socket.reconnectAttempts = 0;
169
+ await otherPlugin.data.eventHandler?.socket.disconnect();
170
+ await other.close();
171
+ });
172
+ });
173
+
174
+ describe("when streaming events", () => {
175
+ it("should hold events until HyperFlow confirms the handshake and then send them in order", async () => {
176
+ client.cache.events.emitInvalidation("first");
177
+ client.cache.events.emitInvalidation("second");
178
+ expect(server.events()).toHaveLength(0);
179
+
180
+ await initialize();
181
+
182
+ await vi.waitFor(() => {
183
+ const invalidations = server
184
+ .events()
185
+ .filter((event) => event.eventSource === EventSourceType.CACHE)
186
+ .map((event) => event.eventData);
187
+ expect(invalidations).toStrictEqual(expect.arrayContaining(["first", "second"]));
188
+ expect(invalidations.indexOf("first")).toBeLessThan(invalidations.indexOf("second"));
189
+ });
190
+ });
191
+
192
+ it("should stream events from every module of the client", async () => {
193
+ await initialize();
194
+
195
+ client.cache.events.emitInvalidation("key");
196
+ client.fetchDispatcher.stop("fetch-queue");
197
+ client.submitDispatcher.stop("submit-queue");
198
+ client.appManager.setOnline(false);
199
+
200
+ await vi.waitFor(() => {
201
+ const sources = new Set(server.events().map((event) => event.eventSource));
202
+ expect(sources).toContain(EventSourceType.CACHE);
203
+ expect(sources).toContain(EventSourceType.FETCH_DISPATCHER);
204
+ expect(sources).toContain(EventSourceType.SUBMIT_DISPATCHER);
205
+ expect(sources).toContain(EventSourceType.APP_MANAGER);
206
+ });
207
+ expect(server.events().every((event) => event.connectionName === "App")).toBe(true);
208
+ expect(server.events().every((event) => event.origin === MessageOrigin.PLUGIN)).toBe(true);
209
+ });
210
+
211
+ it("should stream the request lifecycle", async () => {
212
+ await initialize();
213
+ client.requestManager.events.emitAbort({
214
+ requestId: "id",
215
+ request: client.createRequest()({ endpoint: "/users" }),
216
+ });
217
+
218
+ await vi.waitFor(() =>
219
+ expect(server.events().some((event) => event.eventSource === EventSourceType.REQUEST_MANAGER)).toBe(true),
220
+ );
221
+ });
222
+
223
+ it("should report created requests", async () => {
224
+ await initialize();
225
+ client.createRequest()({ endpoint: "/users" });
226
+
227
+ await vi.waitFor(() => {
228
+ const created = server.events().find((event) => event.eventName === CustomEvents.REQUEST_CREATED);
229
+ expect(created?.eventSource).toBe(EventSourceType.CUSTOM_EVENT);
230
+ });
231
+ });
232
+
233
+ it("should not send back events that HyperFlow triggered", async () => {
234
+ await initialize();
235
+
236
+ client.cache.events.emitInvalidation("from-hyperflow", true);
237
+ client.cache.events.emitInvalidation("from-app");
238
+
239
+ await vi.waitFor(() => expect(server.events().some((event) => event.eventData === "from-app")).toBe(true));
240
+ expect(server.events().some((event) => event.eventData === "from-hyperflow")).toBe(false);
241
+ });
242
+ });
243
+
244
+ describe("when HyperFlow changes the application", () => {
245
+ beforeEach(async () => {
246
+ await initialize();
247
+ });
248
+
249
+ it("should write cache data into the application's cache", async () => {
250
+ const onData = vi.fn();
251
+ client.cache.events.onDataByKey("GET_/users", onData);
252
+ const value = createCacheValue({ data: { id: 99 } });
253
+
254
+ server.sendEvent(EventSourceType.CACHE, CoreEvents.ON_CACHE_CHANGE, value);
255
+
256
+ await vi.waitFor(() => expect(client.cache.storage.get("GET_/users")?.data).toStrictEqual({ id: 99 }));
257
+ expect(onData).toHaveBeenCalled();
258
+ });
259
+
260
+ it("should make invalidated data stale in the application's cache", async () => {
261
+ client.cache.storage.set("GET_/users", createCacheValue({ staleTime: 60_000 }));
262
+ const onInvalidate = vi.fn();
263
+ client.cache.events.onInvalidateByKey("GET_/users", onInvalidate);
264
+
265
+ server.sendEvent(EventSourceType.CACHE, CoreEvents.ON_CACHE_INVALIDATION, "GET_/users");
266
+
267
+ await vi.waitFor(() => expect(onInvalidate).toHaveBeenCalled());
268
+ expect(client.cache.storage.get("GET_/users")?.staleTime).toBe(0);
269
+ expect(client.cache.storage.get("GET_/users")?.data).toStrictEqual({ id: 1 });
270
+ });
271
+
272
+ it("should not create entries when invalidating a missing key", async () => {
273
+ const onInvalidate = vi.fn();
274
+ client.cache.events.onInvalidateByKey("GET_/missing", onInvalidate);
275
+
276
+ server.sendEvent(EventSourceType.CACHE, CoreEvents.ON_CACHE_INVALIDATION, "GET_/missing");
277
+
278
+ await vi.waitFor(() => expect(onInvalidate).toHaveBeenCalled());
279
+ expect(client.cache.storage.get("GET_/missing")).toBeUndefined();
280
+ });
281
+
282
+ it("should delete entries from the application's cache", async () => {
283
+ client.cache.storage.set("GET_/users", createCacheValue());
284
+
285
+ server.sendEvent(EventSourceType.CACHE, CoreEvents.ON_CACHE_DELETE, "GET_/users");
286
+
287
+ await vi.waitFor(() => expect(client.cache.storage.get("GET_/users")).toBeUndefined());
288
+ });
289
+
290
+ it("should stop and start fetch queues", async () => {
291
+ server.sendEvent(EventSourceType.FETCH_DISPATCHER, CoreEvents.ON_FETCH_QUEUE_STATUS_CHANGE, {
292
+ queryKey: "GET_/users",
293
+ stopped: true,
294
+ requests: [],
295
+ });
296
+ await vi.waitFor(() => expect(client.fetchDispatcher.getQueue("GET_/users").stopped).toBe(true));
297
+ expect(client.submitDispatcher.getQueue("GET_/users").stopped).toBe(false);
298
+
299
+ server.sendEvent(EventSourceType.FETCH_DISPATCHER, CoreEvents.ON_FETCH_QUEUE_STATUS_CHANGE, {
300
+ queryKey: "GET_/users",
301
+ stopped: false,
302
+ requests: [],
303
+ });
304
+ await vi.waitFor(() => expect(client.fetchDispatcher.getQueue("GET_/users").stopped).toBe(false));
305
+ });
306
+
307
+ it("should stop and start submit queues", async () => {
308
+ server.sendEvent(EventSourceType.SUBMIT_DISPATCHER, CoreEvents.ON_SUBMIT_QUEUE_STATUS_CHANGE, {
309
+ queryKey: "POST_/users",
310
+ stopped: true,
311
+ requests: [],
312
+ });
313
+ await vi.waitFor(() => expect(client.submitDispatcher.getQueue("POST_/users").stopped).toBe(true));
314
+ expect(client.fetchDispatcher.getQueue("POST_/users").stopped).toBe(false);
315
+
316
+ server.sendEvent(EventSourceType.SUBMIT_DISPATCHER, CoreEvents.ON_SUBMIT_QUEUE_STATUS_CHANGE, {
317
+ queryKey: "POST_/users",
318
+ stopped: false,
319
+ requests: [],
320
+ });
321
+ await vi.waitFor(() => expect(client.submitDispatcher.getQueue("POST_/users").stopped).toBe(false));
322
+ });
323
+
324
+ it("should clear fetch and submit queues", async () => {
325
+ const fetchClear = vi.spyOn(client.fetchDispatcher, "clearQueue");
326
+ const submitClear = vi.spyOn(client.submitDispatcher, "clearQueue");
327
+
328
+ server.sendEvent(EventSourceType.FETCH_DISPATCHER, CoreEvents.ON_FETCH_QUEUE_CLEAR, { queryKey: "GET_/users" });
329
+ server.sendEvent(EventSourceType.SUBMIT_DISPATCHER, CoreEvents.ON_SUBMIT_QUEUE_CLEAR, {
330
+ queryKey: "POST_/users",
331
+ });
332
+
333
+ await vi.waitFor(() => {
334
+ expect(fetchClear).toHaveBeenCalledWith("GET_/users");
335
+ expect(submitClear).toHaveBeenCalledWith("POST_/users");
336
+ });
337
+ });
338
+
339
+ it("should set the loading state of requests", async () => {
340
+ const onLoading = vi.fn();
341
+ client.requestManager.events.onLoading(onLoading);
342
+ const request = client.createRequest()({ endpoint: "/users" });
343
+
344
+ server.sendEvent(EventSourceType.REQUEST_MANAGER, CoreEvents.ON_REQUEST_LOADING, {
345
+ request: request.toJSON(),
346
+ requestId: "",
347
+ loading: true,
348
+ isRetry: false,
349
+ isOffline: false,
350
+ });
351
+
352
+ await vi.waitFor(() => expect(onLoading).toHaveBeenCalledWith(expect.objectContaining({ loading: true }), true));
353
+ });
354
+
355
+ it("should ignore request lifecycle events it doesn't apply", async () => {
356
+ const onResponse = vi.fn();
357
+ client.requestManager.events.onResponse(onResponse);
358
+ const onLoading = vi.fn();
359
+ client.requestManager.events.onLoading(onLoading);
360
+
361
+ server.sendEvent(EventSourceType.REQUEST_MANAGER, "ON_REQUEST_START" as CoreEvents, {});
362
+ server.sendEvent(EventSourceType.CACHE, CoreEvents.ON_CACHE_DELETE, "GET_/users");
363
+ client.cache.storage.set("GET_/users", createCacheValue());
364
+ server.sendEvent(EventSourceType.CACHE, CoreEvents.ON_CACHE_DELETE, "GET_/users");
365
+
366
+ await vi.waitFor(() => expect(client.cache.storage.get("GET_/users")).toBeUndefined());
367
+ expect(onResponse).not.toHaveBeenCalled();
368
+ expect(onLoading).not.toHaveBeenCalled();
369
+ });
370
+
371
+ it("should keep working after unknown messages", async () => {
372
+ server.send({ messageType: MessageType.INTERNAL, eventType: InternalEvents.PLUGIN_HANGUP });
373
+ server.send({ messageType: "UNKNOWN" as MessageType });
374
+ client.cache.storage.set("GET_/users", createCacheValue());
375
+
376
+ server.sendEvent(EventSourceType.CACHE, CoreEvents.ON_CACHE_DELETE, "GET_/users");
377
+
378
+ await vi.waitFor(() => expect(client.cache.storage.get("GET_/users")).toBeUndefined());
379
+ });
380
+ });
381
+
382
+ describe("when running in Node.js", () => {
383
+ const connectPlugin = async (options: Partial<Parameters<typeof DevtoolsPlugin>[0]> = {}) => {
384
+ const other = await createHyperFlowServer();
385
+ const otherPlugin = DevtoolsPlugin({ appName: "Backend", url: `ws://localhost:${other.port}`, ...options });
386
+ new Client({ url: "http://localhost:5000" }).addPlugin(otherPlugin);
387
+ const cleanup = async () => {
388
+ const socket = otherPlugin.data.eventHandler?.socket;
389
+ if (socket) {
390
+ socket.reconnectAttempts = 0;
391
+ await socket.disconnect();
392
+ }
393
+ await other.close();
394
+ };
395
+ return { other, otherPlugin, cleanup };
396
+ };
397
+
398
+ it("should run without a window", () => {
399
+ expect(typeof window).toBe("undefined");
400
+ });
401
+
402
+ it("should connect with the native WebSocket", async () => {
403
+ const { other, otherPlugin, cleanup } = await connectPlugin();
404
+ try {
405
+ await vi.waitFor(() => expect(otherPlugin.data.eventHandler?.isConnected).toBe(true));
406
+ await vi.waitFor(() => expect(other.received[0]?.data.connectionName).toBe("Backend"));
407
+ } finally {
408
+ await cleanup();
409
+ }
410
+ });
411
+
412
+ it("should connect with the WebSocket option where there is no global WebSocket", async () => {
413
+ const globalWebSocket = globalThis.WebSocket;
414
+ Reflect.deleteProperty(globalThis, "WebSocket");
415
+ const { other, otherPlugin, cleanup } = await connectPlugin({
416
+ WebSocket: NodeWebSocket as unknown as typeof globalThis.WebSocket,
417
+ });
418
+ try {
419
+ await vi.waitFor(() => expect(otherPlugin.data.eventHandler?.isConnected).toBe(true));
420
+ await vi.waitFor(() => expect(other.received[0]?.data.eventType).toBe(InternalEvents.PLUGIN_INITIALIZED));
421
+ } finally {
422
+ globalThis.WebSocket = globalWebSocket;
423
+ await cleanup();
424
+ }
425
+ });
426
+ });
427
+ });
@@ -0,0 +1,255 @@
1
+ import { Client } from "@hyper-fetch/core";
2
+ import { createHttpMockingServer } from "@hyper-fetch/testing";
3
+ import type { AddressInfo } from "net";
4
+ import type { WebSocket } from "ws";
5
+ import { WebSocketServer } from "ws";
6
+
7
+ import { createObserversReporter } from "../../src/devtools.observers-reporter";
8
+ import type { BaseMessagePayload, DevtoolsObserversEventData } from "../../src/index";
9
+ import {
10
+ DevtoolsPlugin,
11
+ EventSourceType,
12
+ InternalEvents,
13
+ MessageType,
14
+ ObserverEvents,
15
+ SocketTopics,
16
+ } from "../../src/index";
17
+
18
+ const { startServer, stopServer, resetMocks, mockRequest } = createHttpMockingServer();
19
+
20
+ type Received = { data: BaseMessagePayload };
21
+
22
+ /** Stands in for the HyperFlow server */
23
+ const createHyperFlowServer = async () => {
24
+ // A random port can be taken by another process (EADDRINUSE never emits "listening"), the system picks a free one
25
+ const wss = new WebSocketServer({ port: 0 });
26
+ await new Promise<void>((resolve) => {
27
+ wss.once("listening", () => resolve());
28
+ });
29
+ const { port } = wss.address() as AddressInfo;
30
+ const received: Received[] = [];
31
+ let plugin: WebSocket | null = null;
32
+ wss.on("connection", (ws) => {
33
+ plugin = ws;
34
+ ws.on("message", (raw) => received.push(JSON.parse(raw.toString())));
35
+ });
36
+
37
+ const initializeApp = () =>
38
+ plugin?.send(
39
+ JSON.stringify({
40
+ topic: SocketTopics.PLUGIN_LISTENER,
41
+ data: { messageType: MessageType.INTERNAL, eventType: InternalEvents.APP_INITIALIZED },
42
+ }),
43
+ );
44
+
45
+ /** The plugin sends its handshake as soon as it connects, HyperFlow answers only after receiving it */
46
+ const receivedHandshake = () =>
47
+ received.some(
48
+ ({ data }) => data.messageType === MessageType.INTERNAL && data.eventType === InternalEvents.PLUGIN_INITIALIZED,
49
+ );
50
+
51
+ const observerEvents = () =>
52
+ received
53
+ .map(({ data }) => data)
54
+ .filter((data) => data.messageType === MessageType.EVENT && data.eventSource === EventSourceType.OBSERVERS)
55
+ .map((data) => {
56
+ expect(data.eventName).toBe(ObserverEvents.CHANGED);
57
+ return data.eventData as DevtoolsObserversEventData;
58
+ });
59
+
60
+ const close = async () => {
61
+ wss.clients.forEach((ws) => ws.terminate());
62
+ await new Promise((resolve) => {
63
+ wss.close(resolve);
64
+ });
65
+ };
66
+
67
+ return { port, received, receivedHandshake, initializeApp, observerEvents, close };
68
+ };
69
+
70
+ describe("DevtoolsPlugin [ Observers ]", () => {
71
+ let hyperFlow: Awaited<ReturnType<typeof createHyperFlowServer>>;
72
+ let plugin: ReturnType<typeof DevtoolsPlugin> | undefined;
73
+ let client = new Client({ url: "http://localhost:5000" });
74
+ let getUsers = client.createRequest<{ response: { id: number }[] }>()({ endpoint: "/users" });
75
+ let postUser = client.createRequest<{ response: { id: number } }>()({ endpoint: "/users", method: "POST" });
76
+
77
+ beforeAll(() => startServer());
78
+ afterAll(() => stopServer());
79
+
80
+ beforeEach(async () => {
81
+ resetMocks();
82
+ hyperFlow = await createHyperFlowServer();
83
+ client = new Client({ url: "http://localhost:5000" });
84
+ getUsers = client.createRequest<{ response: { id: number }[] }>()({ endpoint: "/users" });
85
+ postUser = client.createRequest<{ response: { id: number } }>()({ endpoint: "/users", method: "POST" });
86
+ mockRequest(getUsers, { data: [{ id: 1 }] });
87
+ mockRequest(postUser, { data: { id: 2 } });
88
+ });
89
+
90
+ afterEach(async () => {
91
+ const devtoolsSocket = plugin?.data.eventHandler?.socket;
92
+ if (devtoolsSocket) {
93
+ devtoolsSocket.reconnectAttempts = 0;
94
+ await devtoolsSocket.disconnect();
95
+ }
96
+ plugin = undefined;
97
+ await hyperFlow.close();
98
+ });
99
+
100
+ const connectPlugin = async ({ initialize = true }: { initialize?: boolean } = {}) => {
101
+ const created = DevtoolsPlugin({ appName: "App", url: `ws://localhost:${hyperFlow.port}` });
102
+ plugin = created;
103
+ client.addPlugin(created);
104
+ // msw intercepts WebSocket too: it opens the plugin's socket at once and connects to this server only afterwards,
105
+ // so an answer sent right after the plugin connected could find no connection here and get lost
106
+ await vi.waitFor(() => expect(hyperFlow.receivedHandshake()).toBe(true));
107
+ if (initialize) {
108
+ await initializeApp();
109
+ }
110
+ };
111
+
112
+ const initializeApp = async () => {
113
+ hyperFlow.initializeApp();
114
+ await vi.waitFor(() => expect(plugin?.data.eventHandler?.isInitialized).toBe(true));
115
+ };
116
+
117
+ const lastObservers = () => hyperFlow.observerEvents().at(-1);
118
+
119
+ describe("When a cache key gets its first data", () => {
120
+ it("should report the observers it already had", async () => {
121
+ await connectPlugin();
122
+ client.cache.events.onDataByKey(getUsers.cacheKey, vi.fn());
123
+ client.cache.events.onDataByKey(getUsers.cacheKey, vi.fn());
124
+
125
+ await getUsers.send();
126
+
127
+ await vi.waitFor(() => {
128
+ expect(hyperFlow.observerEvents()).toContainEqual({ cache: { [getUsers.cacheKey]: 2 }, queues: {} });
129
+ });
130
+ });
131
+
132
+ it("should report every observer subscribing and unsubscribing from then on", async () => {
133
+ await connectPlugin();
134
+ const unmount = client.cache.events.onDataByKey(getUsers.cacheKey, vi.fn());
135
+ await getUsers.send();
136
+ await vi.waitFor(() => expect(lastObservers()).toStrictEqual({ cache: { [getUsers.cacheKey]: 1 }, queues: {} }));
137
+
138
+ client.cache.events.onDataByKey(getUsers.cacheKey, vi.fn());
139
+ await vi.waitFor(() => expect(lastObservers()).toStrictEqual({ cache: { [getUsers.cacheKey]: 2 }, queues: {} }));
140
+
141
+ unmount();
142
+ await vi.waitFor(() => expect(lastObservers()).toStrictEqual({ cache: { [getUsers.cacheKey]: 1 }, queues: {} }));
143
+ });
144
+
145
+ it("should report a key once when it gets data again", async () => {
146
+ await connectPlugin();
147
+ client.cache.events.onDataByKey(getUsers.cacheKey, vi.fn());
148
+
149
+ await getUsers.send();
150
+ await getUsers.send();
151
+ await postUser.send();
152
+
153
+ // Events arrive in order, so the report of the last request means the earlier ones arrived too
154
+ await vi.waitFor(() => {
155
+ expect(hyperFlow.observerEvents()).toContainEqual({ cache: {}, queues: { [postUser.queryKey]: 0 } });
156
+ });
157
+ const reports = hyperFlow.observerEvents();
158
+ expect(reports.filter(({ cache }) => getUsers.cacheKey in cache)).toStrictEqual([
159
+ { cache: { [getUsers.cacheKey]: 1 }, queues: {} },
160
+ ]);
161
+ expect(reports.filter(({ queues }) => getUsers.queryKey in queues)).toHaveLength(1);
162
+ });
163
+ });
164
+
165
+ describe("When requests go through a queue", () => {
166
+ it("should count the loading and queue observers of the query key in both dispatchers", async () => {
167
+ await connectPlugin();
168
+ client.requestManager.events.onLoadingByQueue(getUsers.queryKey, vi.fn());
169
+ client.fetchDispatcher.events.onQueueChangeByKey(getUsers.queryKey, vi.fn());
170
+ const unmount = client.submitDispatcher.events.onQueueChangeByKey(getUsers.queryKey, vi.fn());
171
+
172
+ await getUsers.send();
173
+ await vi.waitFor(() => {
174
+ expect(hyperFlow.observerEvents()).toContainEqual({ cache: {}, queues: { [getUsers.queryKey]: 3 } });
175
+ });
176
+
177
+ unmount();
178
+ await vi.waitFor(() => expect(lastObservers()).toStrictEqual({ cache: {}, queues: { [getUsers.queryKey]: 2 } }));
179
+
180
+ client.requestManager.events.onLoadingByQueue(getUsers.queryKey, vi.fn());
181
+ await vi.waitFor(() => expect(lastObservers()).toStrictEqual({ cache: {}, queues: { [getUsers.queryKey]: 3 } }));
182
+ });
183
+
184
+ it("should track the queues of the submit dispatcher", async () => {
185
+ await connectPlugin();
186
+ client.requestManager.events.onLoadingByQueue(postUser.queryKey, vi.fn());
187
+
188
+ await postUser.send();
189
+
190
+ await vi.waitFor(() => {
191
+ expect(hyperFlow.observerEvents()).toContainEqual({ cache: {}, queues: { [postUser.queryKey]: 1 } });
192
+ });
193
+ });
194
+ });
195
+
196
+ describe("When HyperFlow connects", () => {
197
+ it("should send the observers of every key at once instead of queueing their changes", async () => {
198
+ await connectPlugin({ initialize: false });
199
+ client.cache.events.onDataByKey(getUsers.cacheKey, vi.fn());
200
+ client.requestManager.events.onLoadingByQueue(getUsers.queryKey, vi.fn());
201
+ await getUsers.send();
202
+ client.cache.events.onDataByKey(getUsers.cacheKey, vi.fn());
203
+
204
+ await initializeApp();
205
+
206
+ await vi.waitFor(() => expect(hyperFlow.observerEvents()).toHaveLength(1));
207
+ expect(lastObservers()).toStrictEqual({
208
+ cache: { [getUsers.cacheKey]: 2 },
209
+ queues: { [getUsers.queryKey]: 1 },
210
+ });
211
+ });
212
+
213
+ it("should send the snapshot again to a reloaded HyperFlow", async () => {
214
+ await connectPlugin();
215
+ client.cache.events.onDataByKey(getUsers.cacheKey, vi.fn());
216
+ await getUsers.send();
217
+ await vi.waitFor(() => expect(lastObservers()).toBeDefined());
218
+ hyperFlow.received.length = 0;
219
+
220
+ hyperFlow.initializeApp();
221
+
222
+ await vi.waitFor(() => {
223
+ expect(lastObservers()).toStrictEqual({
224
+ cache: { [getUsers.cacheKey]: 1 },
225
+ queues: { [getUsers.queryKey]: 0 },
226
+ });
227
+ });
228
+ });
229
+
230
+ it("should send an empty snapshot when the app has no keys yet", async () => {
231
+ await connectPlugin();
232
+
233
+ await vi.waitFor(() => expect(lastObservers()).toStrictEqual({ cache: {}, queues: {} }));
234
+ });
235
+ });
236
+
237
+ describe("When the reporter is unmounted", () => {
238
+ it("should stop following the keys and their observers", async () => {
239
+ const report = vi.fn();
240
+ const reporter = createObserversReporter({ client, report });
241
+ await getUsers.send();
242
+ expect(report).toHaveBeenCalledWith({ cache: { [getUsers.cacheKey]: 0 }, queues: {} });
243
+ report.mockClear();
244
+
245
+ reporter.unmount();
246
+ client.cache.events.onDataByKey(getUsers.cacheKey, vi.fn());
247
+ client.requestManager.events.onLoadingByQueue(getUsers.queryKey, vi.fn());
248
+ await postUser.send();
249
+
250
+ expect(report).not.toHaveBeenCalled();
251
+ reporter.sendSnapshot();
252
+ expect(report).toHaveBeenCalledWith({ cache: {}, queues: {} });
253
+ });
254
+ });
255
+ });