@hyper-fetch/hono 9.8.1 → 10.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -3
- package/__tests__/features/inputs/inputs.sdk.spec.ts +113 -0
- package/__tests__/features/inputs/inputs.types.spec.ts +87 -0
- package/__tests__/features/paths/paths.sdk.spec.ts +159 -0
- package/__tests__/features/paths/paths.types.spec.ts +223 -0
- package/__tests__/features/realtime/realtime.react.spec.tsx +226 -0
- package/__tests__/features/realtime/realtime.sse.spec.ts +340 -0
- package/__tests__/features/realtime/realtime.types.spec.ts +140 -0
- package/__tests__/features/realtime/realtime.websocket.spec.ts +414 -0
- package/__tests__/features/responses/responses.sdk.spec.ts +149 -0
- package/__tests__/features/responses/responses.types.spec.ts +107 -0
- package/__tests__/features/schema/schema.types.spec.ts +42 -0
- package/__tests__/utils/inputs.app.ts +57 -0
- package/__tests__/utils/paths.app.ts +31 -0
- package/__tests__/utils/realtime-server.ts +333 -0
- package/__tests__/utils/responses.app.ts +54 -0
- package/__tests__/utils/server.ts +18 -0
- package/dist/hono.types.d.ts +105 -10
- package/dist/hono.types.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/package.json +6 -2
- package/src/hono.types.ts +162 -26
- package/src/index.ts +1 -1
- package/vite.config.ts +7 -0
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import type { EmitterModel, ListenerModel, SocketInstance, WebsocketAdapterOptionsType } from "@hyper-fetch/sockets";
|
|
2
|
+
import { createSocketSdk, Socket } from "@hyper-fetch/sockets";
|
|
3
|
+
|
|
4
|
+
import type { HonoWebSocketPath } from "../../../src";
|
|
5
|
+
import type { ChatMessage, Notification, Price, RealtimeApp, RealtimeServer } from "../../utils/realtime-server";
|
|
6
|
+
import { createRealtimeServer } from "../../utils/realtime-server";
|
|
7
|
+
|
|
8
|
+
describe("Hono realtime [ WebSocket ]", () => {
|
|
9
|
+
let server: RealtimeServer;
|
|
10
|
+
let sockets: SocketInstance[] = [];
|
|
11
|
+
|
|
12
|
+
const createSocket = (
|
|
13
|
+
path: HonoWebSocketPath<RealtimeApp>,
|
|
14
|
+
options?: { queryParams?: Record<string, string>; adapterOptions?: WebsocketAdapterOptionsType },
|
|
15
|
+
) => {
|
|
16
|
+
// A short reconnect delay keeps the reconnect tests fast, `connectionTimeout` keeps slow handshakes alive
|
|
17
|
+
const socket = new Socket({
|
|
18
|
+
url: `${server.wsUrl}${path}`,
|
|
19
|
+
reconnectTime: 10,
|
|
20
|
+
connectionTimeout: 5000,
|
|
21
|
+
...options,
|
|
22
|
+
});
|
|
23
|
+
sockets.push(socket);
|
|
24
|
+
return socket;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const waitForConnected = (socket: SocketInstance) =>
|
|
28
|
+
vi.waitFor(() => {
|
|
29
|
+
expect(socket.adapter.connected).toBe(true);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
/** Joins a room of the multiplexed /ws route and waits until the Hono handler registered the member */
|
|
33
|
+
const joinRoom = async (socket: Socket, roomId: string) => {
|
|
34
|
+
socket.createEmitter<{ roomId: string }>()({ topic: "rooms/join" }).emit({ payload: { roomId } });
|
|
35
|
+
await vi.waitFor(() => {
|
|
36
|
+
expect(server.state.rooms.get(roomId)?.size).toBe(1);
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
beforeEach(async () => {
|
|
41
|
+
server = createRealtimeServer();
|
|
42
|
+
await server.start();
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
afterEach(async () => {
|
|
46
|
+
await Promise.all(sockets.map((socket) => socket.disconnect()));
|
|
47
|
+
sockets = [];
|
|
48
|
+
await server.stop();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
describe("when listening by topic", () => {
|
|
52
|
+
it("should deliver the frames of the listened topic only", async () => {
|
|
53
|
+
const socket = createSocket("/ws");
|
|
54
|
+
const onEcho = vi.fn();
|
|
55
|
+
const onOther = vi.fn();
|
|
56
|
+
socket.createListener<{ text: string }>()({ topic: "echo" }).listen(onEcho);
|
|
57
|
+
socket.createListener<{ text: string }>()({ topic: "other" }).listen(onOther);
|
|
58
|
+
await waitForConnected(socket);
|
|
59
|
+
|
|
60
|
+
socket
|
|
61
|
+
.createEmitter<{ text: string }>()({ topic: "echo" })
|
|
62
|
+
.emit({ payload: { text: "hello" } });
|
|
63
|
+
|
|
64
|
+
await vi.waitFor(() => {
|
|
65
|
+
expect(onEcho).toHaveBeenCalledTimes(1);
|
|
66
|
+
});
|
|
67
|
+
expect(onEcho.mock.calls[0][0].data).toStrictEqual({ text: "hello" });
|
|
68
|
+
expect(onOther).not.toHaveBeenCalled();
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("should match the topic params of the listener", async () => {
|
|
72
|
+
const socket = createSocket("/ws");
|
|
73
|
+
const onRoom = vi.fn();
|
|
74
|
+
socket.createListener<ChatMessage>()({ topic: "chat/:roomId" }).setParams({ roomId: "1" }).listen(onRoom);
|
|
75
|
+
await waitForConnected(socket);
|
|
76
|
+
await joinRoom(socket, "1");
|
|
77
|
+
await joinRoom(socket, "2");
|
|
78
|
+
|
|
79
|
+
// Frames arrive in order, so the room 2 frame was already ignored when the room 1 frame arrives
|
|
80
|
+
server.broadcast("2", "not for this listener");
|
|
81
|
+
server.broadcast("1", "hi");
|
|
82
|
+
|
|
83
|
+
await vi.waitFor(() => {
|
|
84
|
+
expect(onRoom).toHaveBeenCalledTimes(1);
|
|
85
|
+
});
|
|
86
|
+
expect(onRoom.mock.calls[0][0].data).toStrictEqual({ roomId: "1", text: "hi" });
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("should stop delivering after the listener is removed", async () => {
|
|
90
|
+
const socket = createSocket("/ws");
|
|
91
|
+
const onEcho = vi.fn();
|
|
92
|
+
const onControl = vi.fn();
|
|
93
|
+
const removeListener = socket.createListener<{ text: string }>()({ topic: "echo" }).listen(onEcho);
|
|
94
|
+
socket.createListener<{ roomId: string }>()({ topic: "rooms/joined" }).listen(onControl);
|
|
95
|
+
await waitForConnected(socket);
|
|
96
|
+
|
|
97
|
+
removeListener();
|
|
98
|
+
socket
|
|
99
|
+
.createEmitter<{ text: string }>()({ topic: "echo" })
|
|
100
|
+
.emit({ payload: { text: "hello" } });
|
|
101
|
+
await joinRoom(socket, "1");
|
|
102
|
+
await vi.waitFor(() => {
|
|
103
|
+
expect(onControl).toHaveBeenCalledTimes(1);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
expect(onEcho).not.toHaveBeenCalled();
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
describe("when emitting", () => {
|
|
111
|
+
it("should send a { topic, data } frame the Hono handler reads, with the topic params filled in", async () => {
|
|
112
|
+
const socket = createSocket("/ws");
|
|
113
|
+
const onRoom = vi.fn();
|
|
114
|
+
socket.createListener<ChatMessage>()({ topic: "chat/:roomId" }).setParams({ roomId: "7" }).listen(onRoom);
|
|
115
|
+
await waitForConnected(socket);
|
|
116
|
+
await joinRoom(socket, "7");
|
|
117
|
+
|
|
118
|
+
socket
|
|
119
|
+
.createEmitter<{ text: string }>()({ topic: "chat/:roomId" })
|
|
120
|
+
.emit({ params: { roomId: "7" }, payload: { text: "from the client" } });
|
|
121
|
+
|
|
122
|
+
await vi.waitFor(() => {
|
|
123
|
+
expect(onRoom).toHaveBeenCalledTimes(1);
|
|
124
|
+
});
|
|
125
|
+
expect(onRoom.mock.calls[0][0].data).toStrictEqual({ roomId: "7", text: "from the client" });
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it("should report an emit before the connection opens through the emitter error event", async () => {
|
|
129
|
+
const socket = createSocket("/ws", { adapterOptions: { autoConnect: false } });
|
|
130
|
+
const onEmitError = vi.fn();
|
|
131
|
+
socket.events.onEmitterError(onEmitError);
|
|
132
|
+
|
|
133
|
+
socket
|
|
134
|
+
.createEmitter<{ text: string }>()({ topic: "echo" })
|
|
135
|
+
.emit({ payload: { text: "too early" } });
|
|
136
|
+
|
|
137
|
+
await vi.waitFor(() => {
|
|
138
|
+
expect(onEmitError).toHaveBeenCalledTimes(1);
|
|
139
|
+
});
|
|
140
|
+
expect(onEmitError.mock.calls[0][0].error.message).toBe("Cannot emit event when connection is not open");
|
|
141
|
+
expect(server.state.connections.size).toBe(0);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
describe("when the subscription needs input", () => {
|
|
146
|
+
it("should start and stop a server-side subscription with messages", async () => {
|
|
147
|
+
const socket = createSocket("/ws");
|
|
148
|
+
const onRoom = vi.fn();
|
|
149
|
+
const removeListener = socket
|
|
150
|
+
.createListener<ChatMessage>()({ topic: "chat/:roomId" })
|
|
151
|
+
.setParams({ roomId: "1" })
|
|
152
|
+
.listen(onRoom);
|
|
153
|
+
await waitForConnected(socket);
|
|
154
|
+
|
|
155
|
+
await joinRoom(socket, "1");
|
|
156
|
+
server.broadcast("1", "first");
|
|
157
|
+
await vi.waitFor(() => {
|
|
158
|
+
expect(onRoom).toHaveBeenCalledTimes(1);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
removeListener();
|
|
162
|
+
socket
|
|
163
|
+
.createEmitter<{ roomId: string }>()({ topic: "rooms/leave" })
|
|
164
|
+
.emit({ payload: { roomId: "1" } });
|
|
165
|
+
|
|
166
|
+
await vi.waitFor(() => {
|
|
167
|
+
expect(server.state.rooms.has("1")).toBe(false);
|
|
168
|
+
});
|
|
169
|
+
expect(server.state.connections.size).toBe(1);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it("should pass the subscription input in the query params of the handshake", async () => {
|
|
173
|
+
const socket = createSocket("/notifications", { queryParams: { userId: "1" } });
|
|
174
|
+
const onNotification = vi.fn();
|
|
175
|
+
socket.createListener<Notification>()({ topic: "notification" }).listen(onNotification);
|
|
176
|
+
await vi.waitFor(() => {
|
|
177
|
+
expect(server.state.notificationConnections.get("1")?.size).toBe(1);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
server.notify({ userId: "1", title: "Welcome" });
|
|
181
|
+
await vi.waitFor(() => {
|
|
182
|
+
expect(onNotification).toHaveBeenCalledTimes(1);
|
|
183
|
+
});
|
|
184
|
+
expect(onNotification.mock.calls[0][0].data).toStrictEqual({ userId: "1", title: "Welcome" });
|
|
185
|
+
|
|
186
|
+
// New input, new handshake - the listener stays registered across the reconnect
|
|
187
|
+
socket.setQueryParams({ userId: "2" });
|
|
188
|
+
await socket.reconnect();
|
|
189
|
+
await vi.waitFor(() => {
|
|
190
|
+
expect(server.state.notificationConnections.get("2")?.size).toBe(1);
|
|
191
|
+
});
|
|
192
|
+
expect(server.state.notificationConnections.has("1")).toBe(false);
|
|
193
|
+
|
|
194
|
+
server.notify({ userId: "2", title: "Hello again" });
|
|
195
|
+
await vi.waitFor(() => {
|
|
196
|
+
expect(onNotification).toHaveBeenCalledTimes(2);
|
|
197
|
+
});
|
|
198
|
+
expect(onNotification.mock.calls[1][0].data).toStrictEqual({ userId: "2", title: "Hello again" });
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it("should open one connection per room on a route with path params", async () => {
|
|
202
|
+
const roomPath = (roomId: string): HonoWebSocketPath<RealtimeApp> => `/chat/${roomId}`;
|
|
203
|
+
const socket = createSocket(roomPath("1"));
|
|
204
|
+
const onMessage = vi.fn();
|
|
205
|
+
socket.createListener<ChatMessage>()({ topic: "message" }).listen(onMessage);
|
|
206
|
+
await waitForConnected(socket);
|
|
207
|
+
|
|
208
|
+
socket
|
|
209
|
+
.createEmitter<{ text: string }>()({ topic: "message" })
|
|
210
|
+
.emit({ payload: { text: "in room 1" } });
|
|
211
|
+
await vi.waitFor(() => {
|
|
212
|
+
expect(onMessage).toHaveBeenCalledTimes(1);
|
|
213
|
+
});
|
|
214
|
+
expect(onMessage.mock.calls[0][0].data).toStrictEqual({ roomId: "1", text: "in room 1" });
|
|
215
|
+
|
|
216
|
+
// Switching rooms switches the connection
|
|
217
|
+
socket.setUrl(`${server.wsUrl}${roomPath("2")}`);
|
|
218
|
+
await socket.reconnect();
|
|
219
|
+
await vi.waitFor(() => {
|
|
220
|
+
expect(server.state.roomConnections.get("2")?.size).toBe(1);
|
|
221
|
+
});
|
|
222
|
+
expect(server.state.roomConnections.has("1")).toBe(false);
|
|
223
|
+
// Hono runs onOpen before the client gets the open event
|
|
224
|
+
await waitForConnected(socket);
|
|
225
|
+
|
|
226
|
+
socket
|
|
227
|
+
.createEmitter<{ text: string }>()({ topic: "message" })
|
|
228
|
+
.emit({ payload: { text: "in room 2" } });
|
|
229
|
+
await vi.waitFor(() => {
|
|
230
|
+
expect(onMessage).toHaveBeenCalledTimes(2);
|
|
231
|
+
});
|
|
232
|
+
expect(onMessage.mock.calls[1][0].data).toStrictEqual({ roomId: "2", text: "in room 2" });
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
describe("when the app has its own message format", () => {
|
|
237
|
+
const legacyCodec: WebsocketAdapterOptionsType = {
|
|
238
|
+
decode: (event) => {
|
|
239
|
+
if (typeof event.data !== "string" || !event.data.startsWith("{")) {
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
const { type, payload } = JSON.parse(event.data);
|
|
243
|
+
return { topic: type, data: payload };
|
|
244
|
+
},
|
|
245
|
+
encode: ({ topic, payload }) => JSON.stringify({ type: topic, payload }),
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
it("should read and write { type, payload } frames with a custom codec", async () => {
|
|
249
|
+
const socket = createSocket("/legacy", { adapterOptions: legacyCodec });
|
|
250
|
+
const onPrice = vi.fn();
|
|
251
|
+
const onError = vi.fn();
|
|
252
|
+
socket.onError(onError);
|
|
253
|
+
socket.createListener<Price>()({ topic: "price" }).listen(onPrice);
|
|
254
|
+
await waitForConnected(socket);
|
|
255
|
+
|
|
256
|
+
socket
|
|
257
|
+
.createEmitter<{ symbol: string }>()({ topic: "subscribe" })
|
|
258
|
+
.emit({ payload: { symbol: "BTC" } });
|
|
259
|
+
|
|
260
|
+
await vi.waitFor(() => {
|
|
261
|
+
expect(onPrice).toHaveBeenCalledTimes(1);
|
|
262
|
+
});
|
|
263
|
+
expect(onPrice.mock.calls[0][0].data).toStrictEqual({ symbol: "BTC", price: 100 });
|
|
264
|
+
expect(server.state.legacyFrames).toStrictEqual([{ type: "subscribe", payload: { symbol: "BTC" } }]);
|
|
265
|
+
// The plain-text "ping" sent before the price is skipped by the decoder, not reported as an error
|
|
266
|
+
expect(onError).not.toHaveBeenCalled();
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
it("should report a decoder failure and keep the connection", async () => {
|
|
270
|
+
const socket = createSocket("/legacy", {
|
|
271
|
+
adapterOptions: {
|
|
272
|
+
...legacyCodec,
|
|
273
|
+
decode: (event) => {
|
|
274
|
+
if (event.data === "ping") {
|
|
275
|
+
throw new Error("Unexpected frame");
|
|
276
|
+
}
|
|
277
|
+
return legacyCodec.decode?.(event) ?? null;
|
|
278
|
+
},
|
|
279
|
+
},
|
|
280
|
+
});
|
|
281
|
+
const onPrice = vi.fn();
|
|
282
|
+
const onError = vi.fn();
|
|
283
|
+
socket.onError(onError);
|
|
284
|
+
socket.createListener<Price>()({ topic: "price" }).listen(onPrice);
|
|
285
|
+
await waitForConnected(socket);
|
|
286
|
+
|
|
287
|
+
socket
|
|
288
|
+
.createEmitter<{ symbol: string }>()({ topic: "subscribe" })
|
|
289
|
+
.emit({ payload: { symbol: "BTC" } });
|
|
290
|
+
|
|
291
|
+
await vi.waitFor(() => {
|
|
292
|
+
expect(onPrice).toHaveBeenCalledTimes(1);
|
|
293
|
+
});
|
|
294
|
+
expect(onError).toHaveBeenCalledTimes(1);
|
|
295
|
+
expect(onError.mock.calls[0][0].error.message).toBe("Unexpected frame");
|
|
296
|
+
expect(socket.adapter.connected).toBe(true);
|
|
297
|
+
});
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
describe("when the connection drops", () => {
|
|
301
|
+
it.each([
|
|
302
|
+
{ name: "with an error code", code: 1011 },
|
|
303
|
+
{ name: "without a code", code: undefined },
|
|
304
|
+
])("should reconnect when the Hono handler closes the socket $name", async ({ code }) => {
|
|
305
|
+
const socket = createSocket("/ws");
|
|
306
|
+
const onEcho = vi.fn();
|
|
307
|
+
const onReconnect = vi.fn();
|
|
308
|
+
socket.onReconnect(onReconnect);
|
|
309
|
+
socket.createListener<{ text: string }>()({ topic: "echo" }).listen(onEcho);
|
|
310
|
+
await waitForConnected(socket);
|
|
311
|
+
const [firstConnection] = server.state.connections;
|
|
312
|
+
|
|
313
|
+
server.closeConnections(code);
|
|
314
|
+
|
|
315
|
+
await vi.waitFor(() => {
|
|
316
|
+
expect(onReconnect).toHaveBeenCalledTimes(1);
|
|
317
|
+
expect(server.state.connections.size).toBe(1);
|
|
318
|
+
expect(server.state.connections.has(firstConnection)).toBe(false);
|
|
319
|
+
});
|
|
320
|
+
await waitForConnected(socket);
|
|
321
|
+
|
|
322
|
+
socket
|
|
323
|
+
.createEmitter<{ text: string }>()({ topic: "echo" })
|
|
324
|
+
.emit({ payload: { text: "after reconnect" } });
|
|
325
|
+
await vi.waitFor(() => {
|
|
326
|
+
expect(onEcho).toHaveBeenCalledTimes(1);
|
|
327
|
+
});
|
|
328
|
+
expect(onEcho.mock.calls[0][0].data).toStrictEqual({ text: "after reconnect" });
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
it("should not reconnect when the Hono handler closes the socket normally", async () => {
|
|
332
|
+
const socket = createSocket("/ws");
|
|
333
|
+
const onDisconnected = vi.fn();
|
|
334
|
+
const onReconnect = vi.fn();
|
|
335
|
+
socket.onDisconnected(onDisconnected);
|
|
336
|
+
socket.onReconnect(onReconnect);
|
|
337
|
+
await waitForConnected(socket);
|
|
338
|
+
|
|
339
|
+
server.closeConnections(1000);
|
|
340
|
+
|
|
341
|
+
await vi.waitFor(() => {
|
|
342
|
+
expect(onDisconnected).toHaveBeenCalledTimes(1);
|
|
343
|
+
});
|
|
344
|
+
expect(socket.adapter.connected).toBe(false);
|
|
345
|
+
expect(onReconnect).not.toHaveBeenCalled();
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
it("should reconnect and resubscribe after the Hono server restarts", async () => {
|
|
349
|
+
const socket = createSocket("/ws");
|
|
350
|
+
const join = socket.createEmitter<{ roomId: string }>()({ topic: "rooms/join" });
|
|
351
|
+
const onRoom = vi.fn();
|
|
352
|
+
// The server forgets subscriptions with the connection - join again on every (re)connection
|
|
353
|
+
socket.onConnected(() => join.emit({ payload: { roomId: "1" } }));
|
|
354
|
+
socket.createListener<ChatMessage>()({ topic: "chat/:roomId" }).setParams({ roomId: "1" }).listen(onRoom);
|
|
355
|
+
await vi.waitFor(() => {
|
|
356
|
+
expect(server.state.rooms.get("1")?.size).toBe(1);
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
await server.stop();
|
|
360
|
+
await vi.waitFor(() => {
|
|
361
|
+
expect(server.state.rooms.has("1")).toBe(false);
|
|
362
|
+
});
|
|
363
|
+
await server.start();
|
|
364
|
+
|
|
365
|
+
await vi.waitFor(() => {
|
|
366
|
+
expect(server.state.rooms.get("1")?.size).toBe(1);
|
|
367
|
+
});
|
|
368
|
+
server.broadcast("1", "back online");
|
|
369
|
+
await vi.waitFor(() => {
|
|
370
|
+
expect(onRoom).toHaveBeenCalledTimes(1);
|
|
371
|
+
});
|
|
372
|
+
expect(onRoom.mock.calls[0][0].data).toStrictEqual({ roomId: "1", text: "back online" });
|
|
373
|
+
});
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
describe("when using createSocketSdk", () => {
|
|
377
|
+
type ChatSchema = {
|
|
378
|
+
chat: {
|
|
379
|
+
$roomId: {
|
|
380
|
+
$listener: ListenerModel<{ response: ChatMessage; topic: "chat/:roomId" }>;
|
|
381
|
+
$emitter: EmitterModel<{ payload: { text: string }; topic: "chat/:roomId" }>;
|
|
382
|
+
};
|
|
383
|
+
};
|
|
384
|
+
rooms: {
|
|
385
|
+
join: { $emitter: EmitterModel<{ payload: { roomId: string }; topic: "rooms/join" }> };
|
|
386
|
+
leave: { $emitter: EmitterModel<{ payload: { roomId: string }; topic: "rooms/leave" }> };
|
|
387
|
+
};
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
it("should listen and emit through the typed SDK", async () => {
|
|
391
|
+
const socket = createSocket("/ws");
|
|
392
|
+
const sdk = createSocketSdk<typeof socket, ChatSchema>(socket);
|
|
393
|
+
const onRoom = vi.fn();
|
|
394
|
+
sdk.chat.$roomId.$listener.setParams({ roomId: "3" }).listen(onRoom);
|
|
395
|
+
await waitForConnected(socket);
|
|
396
|
+
|
|
397
|
+
sdk.rooms.join.$emitter.emit({ payload: { roomId: "3" } });
|
|
398
|
+
await vi.waitFor(() => {
|
|
399
|
+
expect(server.state.rooms.get("3")?.size).toBe(1);
|
|
400
|
+
});
|
|
401
|
+
sdk.chat.$roomId.$emitter.emit({ params: { roomId: "3" }, payload: { text: "typed" } });
|
|
402
|
+
|
|
403
|
+
await vi.waitFor(() => {
|
|
404
|
+
expect(onRoom).toHaveBeenCalledTimes(1);
|
|
405
|
+
});
|
|
406
|
+
expect(onRoom.mock.calls[0][0].data).toStrictEqual({ roomId: "3", text: "typed" });
|
|
407
|
+
|
|
408
|
+
sdk.rooms.leave.$emitter.emit({ payload: { roomId: "3" } });
|
|
409
|
+
await vi.waitFor(() => {
|
|
410
|
+
expect(server.state.rooms.has("3")).toBe(false);
|
|
411
|
+
});
|
|
412
|
+
});
|
|
413
|
+
});
|
|
414
|
+
});
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import type { ServerType } from "@hono/node-server";
|
|
2
|
+
import { createClient, createSdk } from "@hyper-fetch/core";
|
|
3
|
+
|
|
4
|
+
import type { HonoAppToHyperFetch } from "../../../src";
|
|
5
|
+
import { responsesApp } from "../../utils/responses.app";
|
|
6
|
+
import { startServer, stopServer } from "../../utils/server";
|
|
7
|
+
|
|
8
|
+
type Schema = HonoAppToHyperFetch<typeof responsesApp>;
|
|
9
|
+
|
|
10
|
+
describe("HonoAppToHyperFetch [ Responses against a Hono server ]", () => {
|
|
11
|
+
let server: ServerType;
|
|
12
|
+
let url: string;
|
|
13
|
+
|
|
14
|
+
const createAppSdk = () => {
|
|
15
|
+
const client = createClient({ url });
|
|
16
|
+
return createSdk<typeof client, Schema>(client);
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
beforeAll(async () => {
|
|
20
|
+
({ server, url } = await startServer(responsesApp));
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
afterAll(async () => {
|
|
24
|
+
await stopServer(server);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it("should resolve JSON primitives", async () => {
|
|
28
|
+
const sdk = createAppSdk();
|
|
29
|
+
|
|
30
|
+
const text = await sdk.json.string.$get.send();
|
|
31
|
+
const number = await sdk.json.number.$get.send();
|
|
32
|
+
const boolean = await sdk.json.boolean.$get.send();
|
|
33
|
+
|
|
34
|
+
expect(text.data).toBe("a-string");
|
|
35
|
+
expect(number.data).toBe(37);
|
|
36
|
+
expect(boolean.data).toBe(true);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("should resolve null and empty object bodies", async () => {
|
|
40
|
+
const sdk = createAppSdk();
|
|
41
|
+
|
|
42
|
+
const empty = await sdk.json.empty.$get.send();
|
|
43
|
+
const nullBody = await sdk.json.null.$get.send();
|
|
44
|
+
|
|
45
|
+
expect(empty.data).toStrictEqual({});
|
|
46
|
+
expect(nullBody.data).toBeNull();
|
|
47
|
+
expect(nullBody.success).toBe(true);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("should resolve dates as ISO strings", async () => {
|
|
51
|
+
const sdk = createAppSdk();
|
|
52
|
+
|
|
53
|
+
const { data } = await sdk.json.date.$get.send();
|
|
54
|
+
|
|
55
|
+
expect(data).toStrictEqual({ at: "2024-01-01T00:00:00.000Z" });
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("should resolve the body of the branch the handler took", async () => {
|
|
59
|
+
const sdk = createAppSdk();
|
|
60
|
+
|
|
61
|
+
const data = await sdk.json.union.$get.setQueryParams({ flag: "yes" }).send();
|
|
62
|
+
const message = await sdk.json.union.$get.setQueryParams({ flag: "no" }).send();
|
|
63
|
+
|
|
64
|
+
expect(data.data).toStrictEqual({ data: "foo" });
|
|
65
|
+
expect(message.data).toStrictEqual({ message: "error" });
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("should resolve a 2xx status as data and any other status as the error", async () => {
|
|
69
|
+
const sdk = createAppSdk();
|
|
70
|
+
|
|
71
|
+
const ok = await sdk.statuses.$get.setQueryParams({ flag: "no" }).send();
|
|
72
|
+
const failed = await sdk.statuses.$get.setQueryParams({ flag: "yes" }).send();
|
|
73
|
+
|
|
74
|
+
expect(ok).toMatchObject({ status: 200, success: true, data: { data: "foo" }, error: null });
|
|
75
|
+
expect(failed).toMatchObject({ status: 400, success: false, data: null, error: { message: "Bad request" } });
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("should resolve the response a middleware returns early as the error", async () => {
|
|
79
|
+
const sdk = createAppSdk();
|
|
80
|
+
|
|
81
|
+
const rejected = await sdk.guarded.$post.send();
|
|
82
|
+
const created = await sdk.guarded.$post.setHeaders({ authorization: "Bearer token" }).send();
|
|
83
|
+
|
|
84
|
+
expect(rejected).toMatchObject({ status: 401, data: null, error: { error: "Unauthorized" } });
|
|
85
|
+
expect(created).toMatchObject({ status: 201, data: { created: true } });
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("should resolve c.text() as the raw text", async () => {
|
|
89
|
+
const sdk = createAppSdk();
|
|
90
|
+
|
|
91
|
+
const { data } = await sdk.text.$get.send();
|
|
92
|
+
|
|
93
|
+
expect(data).toBe("Hello, Hono!");
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("should parse a c.text() body that is valid JSON, unlike its string type", async () => {
|
|
97
|
+
const sdk = createAppSdk();
|
|
98
|
+
|
|
99
|
+
const { data } = await sdk.text.numeric.$get.send();
|
|
100
|
+
|
|
101
|
+
expect(data).toBe(42);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("should resolve c.body() as the raw body", async () => {
|
|
105
|
+
const sdk = createAppSdk();
|
|
106
|
+
|
|
107
|
+
const { data } = await sdk.body.$get.send();
|
|
108
|
+
|
|
109
|
+
expect(data).toBe("raw body");
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("should resolve an empty c.body(null) as an empty string, unlike its null type", async () => {
|
|
113
|
+
const sdk = createAppSdk();
|
|
114
|
+
|
|
115
|
+
const ok = await sdk.body.null.$get.send();
|
|
116
|
+
const noContent = await sdk.body.empty.$delete.send();
|
|
117
|
+
|
|
118
|
+
expect(ok).toMatchObject({ status: 200, success: true, data: "" });
|
|
119
|
+
expect(noContent).toMatchObject({ status: 204, success: true, data: "" });
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("should follow c.redirect() and resolve the body of the target, unlike its undefined type", async () => {
|
|
123
|
+
const sdk = createAppSdk();
|
|
124
|
+
|
|
125
|
+
const { data, status } = await sdk.redirect.$get.setQueryParams({ flag: "yes" }).send();
|
|
126
|
+
|
|
127
|
+
expect(status).toBe(200);
|
|
128
|
+
expect(data).toBe("Hello, Hono!");
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("should resolve c.newResponse() with its body and status", async () => {
|
|
132
|
+
const sdk = createAppSdk();
|
|
133
|
+
|
|
134
|
+
const { data, status } = await sdk.newResponse.$get.send();
|
|
135
|
+
|
|
136
|
+
expect(status).toBe(202);
|
|
137
|
+
expect(data).toBe("custom");
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it("should resolve c.notFound() as a 404 error", async () => {
|
|
141
|
+
const sdk = createAppSdk();
|
|
142
|
+
|
|
143
|
+
const { data, error, status } = await sdk.notFound.$get.send();
|
|
144
|
+
|
|
145
|
+
expect(status).toBe(404);
|
|
146
|
+
expect(data).toBeNull();
|
|
147
|
+
expect(error).toBe("404 Not Found");
|
|
148
|
+
});
|
|
149
|
+
});
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { ExtractResponseType } from "@hyper-fetch/core";
|
|
2
|
+
import { Hono } from "hono";
|
|
3
|
+
import type { ApplyGlobalResponse, PickResponseByStatusCode } from "hono/client";
|
|
4
|
+
import { expectTypeOf } from "vitest";
|
|
5
|
+
|
|
6
|
+
import type { HonoAppToHyperFetch } from "../../../src";
|
|
7
|
+
import type { Result, responsesApp } from "../../utils/responses.app";
|
|
8
|
+
|
|
9
|
+
type Schema = HonoAppToHyperFetch<typeof responsesApp>;
|
|
10
|
+
|
|
11
|
+
describe("HonoAppToHyperFetch [ JSON responses ]", () => {
|
|
12
|
+
it("should keep the literal type of JSON primitives", () => {
|
|
13
|
+
expectTypeOf<ExtractResponseType<Schema["json"]["string"]["$get"]>>().toEqualTypeOf<"a-string">();
|
|
14
|
+
expectTypeOf<ExtractResponseType<Schema["json"]["number"]["$get"]>>().toEqualTypeOf<37>();
|
|
15
|
+
expectTypeOf<ExtractResponseType<Schema["json"]["boolean"]["$get"]>>().toEqualTypeOf<true>();
|
|
16
|
+
expect(true).toBe(true);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("should type null and empty object bodies", () => {
|
|
20
|
+
expectTypeOf<ExtractResponseType<Schema["json"]["null"]["$get"]>>().toEqualTypeOf<null>();
|
|
21
|
+
expectTypeOf<ExtractResponseType<Schema["json"]["empty"]["$get"]>>().toEqualTypeOf<{}>();
|
|
22
|
+
expect(true).toBe(true);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it("should type dates as the strings JSON turns them into", () => {
|
|
26
|
+
expectTypeOf<ExtractResponseType<Schema["json"]["date"]["$get"]>>().toEqualTypeOf<{ at: string }>();
|
|
27
|
+
expect(true).toBe(true);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it("should keep interfaces with optional fields", () => {
|
|
31
|
+
expectTypeOf<ExtractResponseType<Schema["json"]["interface"]["$get"]>>().toEqualTypeOf<Result[]>();
|
|
32
|
+
expect(true).toBe(true);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("should union the bodies of every branch", () => {
|
|
36
|
+
expectTypeOf<ExtractResponseType<Schema["json"]["union"]["$get"]>>().toEqualTypeOf<
|
|
37
|
+
{ data: string } | { message: string }
|
|
38
|
+
>();
|
|
39
|
+
expect(true).toBe(true);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("should type a body JSON cannot serialize as never", () => {
|
|
43
|
+
const app = new Hono().get("/bigint", (c) => c.json({ value: 42n }));
|
|
44
|
+
type BigIntSchema = HonoAppToHyperFetch<typeof app>;
|
|
45
|
+
|
|
46
|
+
expectTypeOf<ExtractResponseType<BigIntSchema["bigint"]["$get"]>>().toBeNever();
|
|
47
|
+
expect(true).toBe(true);
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
describe("HonoAppToHyperFetch [ Statuses ]", () => {
|
|
52
|
+
it("should union the bodies of every status", () => {
|
|
53
|
+
expectTypeOf<ExtractResponseType<Schema["statuses"]["$get"]>>().toEqualTypeOf<
|
|
54
|
+
{ data: string } | { message: string }
|
|
55
|
+
>();
|
|
56
|
+
expect(true).toBe(true);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("should add the response a middleware returns", () => {
|
|
60
|
+
expectTypeOf<ExtractResponseType<Schema["guarded"]["$post"]>>().toEqualTypeOf<
|
|
61
|
+
{ created: true } | { error: "Unauthorized" }
|
|
62
|
+
>();
|
|
63
|
+
expect(true).toBe(true);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("should keep only the statuses PickResponseByStatusCode picks", () => {
|
|
67
|
+
type SuccessSchema = HonoAppToHyperFetch<PickResponseByStatusCode<typeof responsesApp, 200>>;
|
|
68
|
+
|
|
69
|
+
expectTypeOf<ExtractResponseType<SuccessSchema["statuses"]["$get"]>>().toEqualTypeOf<{ data: string }>();
|
|
70
|
+
expect(true).toBe(true);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("should add the responses ApplyGlobalResponse declares", () => {
|
|
74
|
+
type GlobalSchema = HonoAppToHyperFetch<
|
|
75
|
+
ApplyGlobalResponse<typeof responsesApp, { 500: { json: { error: string } } }>
|
|
76
|
+
>;
|
|
77
|
+
|
|
78
|
+
expectTypeOf<ExtractResponseType<GlobalSchema["json"]["number"]["$get"]>>().toEqualTypeOf<37 | { error: string }>();
|
|
79
|
+
expect(true).toBe(true);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
describe("HonoAppToHyperFetch [ Other response helpers ]", () => {
|
|
84
|
+
it("should type c.text() with the literal text", () => {
|
|
85
|
+
expectTypeOf<ExtractResponseType<Schema["text"]["$get"]>>().toEqualTypeOf<"Hello, Hono!">();
|
|
86
|
+
expectTypeOf<ExtractResponseType<Schema["text"]["numeric"]["$get"]>>().toEqualTypeOf<"42">();
|
|
87
|
+
expect(true).toBe(true);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("should type c.body() with the body it sends", () => {
|
|
91
|
+
expectTypeOf<ExtractResponseType<Schema["body"]["$get"]>>().toEqualTypeOf<"raw body">();
|
|
92
|
+
expectTypeOf<ExtractResponseType<Schema["body"]["empty"]["$delete"]>>().toEqualTypeOf<null>();
|
|
93
|
+
expectTypeOf<ExtractResponseType<Schema["body"]["null"]["$get"]>>().toEqualTypeOf<null>();
|
|
94
|
+
expect(true).toBe(true);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("should type c.redirect() as undefined", () => {
|
|
98
|
+
expectTypeOf<ExtractResponseType<Schema["redirect"]["$get"]>>().toEqualTypeOf<{ stayed: true } | undefined>();
|
|
99
|
+
expect(true).toBe(true);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it("should type untyped responses as an empty object", () => {
|
|
103
|
+
expectTypeOf<ExtractResponseType<Schema["newResponse"]["$get"]>>().toEqualTypeOf<{}>();
|
|
104
|
+
expectTypeOf<ExtractResponseType<Schema["notFound"]["$get"]>>().toEqualTypeOf<{}>();
|
|
105
|
+
expect(true).toBe(true);
|
|
106
|
+
});
|
|
107
|
+
});
|