@hyper-fetch/orpc 0.0.0-stage → 9.8.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 (42) hide show
  1. package/README.md +100 -2
  2. package/__tests__/e2e/e2e.conformance.spec.ts +187 -0
  3. package/__tests__/e2e/e2e.orpc-server.ts +163 -0
  4. package/__tests__/e2e/e2e.orpc.spec.ts +338 -0
  5. package/__tests__/e2e/e2e.react.spec.tsx +219 -0
  6. package/__tests__/features/adapter/adapter.fetch.spec.ts +388 -0
  7. package/__tests__/features/adapter/adapter.lifecycle.spec.ts +529 -0
  8. package/__tests__/features/adapter/adapter.schema.spec.ts +271 -0
  9. package/__tests__/features/adapter/adapter.transport.spec.ts +346 -0
  10. package/__tests__/features/adapter/adapter.utils.spec.ts +329 -0
  11. package/__tests__/tsconfig.json +16 -0
  12. package/__tests__/vitest.setup.ts +5 -0
  13. package/dist/adapter/adapter.constants.d.ts +12 -0
  14. package/dist/adapter/adapter.constants.d.ts.map +1 -0
  15. package/dist/adapter/adapter.d.ts +10 -0
  16. package/dist/adapter/adapter.d.ts.map +1 -0
  17. package/dist/adapter/adapter.fetch.d.ts +3 -0
  18. package/dist/adapter/adapter.fetch.d.ts.map +1 -0
  19. package/dist/adapter/adapter.schema.d.ts +50 -0
  20. package/dist/adapter/adapter.schema.d.ts.map +1 -0
  21. package/dist/adapter/adapter.types.d.ts +42 -0
  22. package/dist/adapter/adapter.types.d.ts.map +1 -0
  23. package/dist/adapter/adapter.utils.d.ts +52 -0
  24. package/dist/adapter/adapter.utils.d.ts.map +1 -0
  25. package/dist/adapter/index.d.ts +7 -0
  26. package/dist/adapter/index.d.ts.map +1 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.mjs +282 -0
  30. package/dist/index.mjs.map +1 -0
  31. package/package.json +74 -4
  32. package/project.json +4 -0
  33. package/src/adapter/adapter.constants.ts +20 -0
  34. package/src/adapter/adapter.fetch.ts +227 -0
  35. package/src/adapter/adapter.schema.ts +73 -0
  36. package/src/adapter/adapter.ts +13 -0
  37. package/src/adapter/adapter.types.ts +65 -0
  38. package/src/adapter/adapter.utils.ts +189 -0
  39. package/src/adapter/index.ts +6 -0
  40. package/src/index.ts +3 -0
  41. package/tsconfig.json +12 -0
  42. package/vite.config.ts +42 -0
@@ -0,0 +1,271 @@
1
+ import type {
2
+ ExtractAdapterMethodType,
3
+ ExtractEndpointType,
4
+ ExtractLocalErrorType,
5
+ ExtractPayloadType,
6
+ ExtractResponseType,
7
+ } from "@hyper-fetch/core";
8
+ import { createClient, createSdk } from "@hyper-fetch/core";
9
+ import { useFetch, useSubmit } from "@hyper-fetch/react";
10
+ import { oc } from "@orpc/contract";
11
+ import type { ContractRouterClient } from "@orpc/contract";
12
+ import { implement, os } from "@orpc/server";
13
+ import type { RouterClient } from "@orpc/server";
14
+ import { expectTypeOf } from "vitest";
15
+ import { z } from "zod";
16
+
17
+ import type {
18
+ OrpcAdapterOptionsType,
19
+ OrpcAdapterType,
20
+ OrpcErrorType,
21
+ OrpcMethod,
22
+ OrpcSchema,
23
+ } from "../../../src/adapter";
24
+ import { OrpcAdapter } from "../../../src/adapter";
25
+ import type { AppRouter, User } from "../../e2e/e2e.orpc-server";
26
+
27
+ describe("Orpc Adapter [ Schema ]", () => {
28
+ const client = createClient({ url: "http://localhost:3000/rpc" }).setAdapter(OrpcAdapter());
29
+ const api = createSdk<typeof client, OrpcSchema<AppRouter>>(client, { camelCaseToKebabCase: false });
30
+
31
+ type Api = typeof api;
32
+ type ById = Api["user"]["byId"]["$query"];
33
+ type List = Api["user"]["list"]["$query"];
34
+ type Create = Api["user"]["create"]["$mutation"];
35
+ type Health = Api["health"]["$query"];
36
+
37
+ it("should expose QUERY and MUTATION as the adapter methods", () => {
38
+ expectTypeOf<ExtractAdapterMethodType<OrpcAdapterType>>().toEqualTypeOf<OrpcMethod>();
39
+ expectTypeOf<OrpcMethod>().toEqualTypeOf<"QUERY" | "MUTATION">();
40
+
41
+ client.createRequest()({ endpoint: "health", method: "QUERY" });
42
+ client.createRequest()({ endpoint: "user/create", method: "MUTATION" });
43
+ // @ts-expect-error POST is the wire method, not a method of this adapter
44
+ client.createRequest()({ endpoint: "health", method: "POST" });
45
+ });
46
+
47
+ it("should infer the output of the procedures", () => {
48
+ expectTypeOf<ExtractResponseType<ById>>().toEqualTypeOf<User>();
49
+ expectTypeOf<ExtractResponseType<List>>().toEqualTypeOf<User[]>();
50
+ expectTypeOf<ExtractResponseType<Create>>().toEqualTypeOf<User>();
51
+ expectTypeOf<ExtractResponseType<Health>>().toEqualTypeOf<"ok">();
52
+ });
53
+
54
+ it("should keep the special output types", () => {
55
+ type NextDay = Api["types"]["nextDay"]["$query"];
56
+
57
+ expectTypeOf<ExtractPayloadType<NextDay>>().toEqualTypeOf<{ date: Date; total: bigint }>();
58
+ expectTypeOf<ExtractResponseType<NextDay>["date"]>().toEqualTypeOf<Date>();
59
+ expectTypeOf<ExtractResponseType<NextDay>["total"]>().toEqualTypeOf<bigint>();
60
+ expectTypeOf<ExtractResponseType<NextDay>["tags"]>().toEqualTypeOf<Set<string>>();
61
+ expectTypeOf<ExtractResponseType<Api["types"]["download"]["$query"]>["file"]>().toEqualTypeOf<File>();
62
+ expectTypeOf<ExtractPayloadType<Api["types"]["upload"]["$mutation"]>>().toEqualTypeOf<{
63
+ name: string;
64
+ file: Blob;
65
+ }>();
66
+ });
67
+
68
+ it("should infer the input of the procedures", () => {
69
+ expectTypeOf<ExtractPayloadType<ById>>().toEqualTypeOf<{ id: number }>();
70
+ expectTypeOf<ExtractPayloadType<Create>>().toEqualTypeOf<{ name: string }>();
71
+ expectTypeOf<ExtractPayloadType<List>>().toEqualTypeOf<{ limit?: number | undefined }>();
72
+ expectTypeOf<ExtractPayloadType<Health>>().toEqualTypeOf<undefined>();
73
+ expectTypeOf<ExtractPayloadType<Api["double"]["$query"]>>().toEqualTypeOf<number>();
74
+ });
75
+
76
+ it("should require the input only when the procedure needs it", () => {
77
+ const check = () => {
78
+ api.health.$query.send();
79
+ api.user.list.$query.send();
80
+ api.user.list.$query.setPayload({ limit: 1 }).send();
81
+ api.user.byId.$query.setPayload({ id: 1 }).send();
82
+ api.user.byId.$query.send({ payload: { id: 1 } });
83
+
84
+ // @ts-expect-error the input is required
85
+ api.user.byId.$query.send();
86
+ // @ts-expect-error wrong input type
87
+ api.user.byId.$query.setPayload({ id: "1" });
88
+ // @ts-expect-error wrong input type
89
+ api.user.create.$mutation.setPayload({ id: 1 });
90
+ };
91
+
92
+ expectTypeOf(check).toBeFunction();
93
+ });
94
+
95
+ it("should infer the defined errors of the procedure", () => {
96
+ type Error = ExtractLocalErrorType<ById>;
97
+ type Defined = Extract<Error, { defined: true }>;
98
+
99
+ expectTypeOf<Defined>().toEqualTypeOf<OrpcErrorType<"NOT_FOUND", { id: number }> & { defined: true }>();
100
+ expectTypeOf<Extract<Error, { defined: false }>>().toEqualTypeOf<OrpcErrorType & { defined: false }>();
101
+ });
102
+
103
+ it("should narrow the error by the defined flag and the code", () => {
104
+ const read = (error: ExtractLocalErrorType<ById>) => {
105
+ if (error.defined && error.code === "NOT_FOUND") {
106
+ expectTypeOf(error.data).toEqualTypeOf<{ id: number }>();
107
+ return error.data.id;
108
+ }
109
+ expectTypeOf(error.data).toEqualTypeOf<unknown>();
110
+ return null;
111
+ };
112
+
113
+ expectTypeOf(read).toBeFunction();
114
+ });
115
+
116
+ it("should type procedures without defined errors", () => {
117
+ expectTypeOf<ExtractLocalErrorType<Health>>().toEqualTypeOf<OrpcErrorType & { defined: false }>();
118
+ expectTypeOf<OrpcErrorType["status"]>().toEqualTypeOf<number>();
119
+ });
120
+
121
+ it("should use the procedure path as the endpoint", () => {
122
+ expectTypeOf<ExtractEndpointType<ById>>().toEqualTypeOf<"/user/byId">();
123
+ expectTypeOf<ExtractEndpointType<Health>>().toEqualTypeOf<"/health">();
124
+ });
125
+
126
+ it("should expose every procedure as a query and a mutation", () => {
127
+ expectTypeOf<Api["user"]["byId"]>().toHaveProperty("$query");
128
+ expectTypeOf<Api["user"]["byId"]>().toHaveProperty("$mutation");
129
+ expectTypeOf<ExtractResponseType<Api["user"]["byId"]["$mutation"]>>().toEqualTypeOf<User>();
130
+ });
131
+
132
+ it("should skip the event iterators and keep the procedures that only throw", () => {
133
+ expectTypeOf<OrpcSchema<AppRouter>>().not.toHaveProperty("ticks");
134
+ expectTypeOf<OrpcSchema<AppRouter>>().toHaveProperty("crash");
135
+ expectTypeOf<OrpcSchema<AppRouter>>().toHaveProperty("fail");
136
+ expectTypeOf<Api["crash"]>().toHaveProperty("$query");
137
+ });
138
+
139
+ it("should accept the client type of the router", () => {
140
+ expectTypeOf<OrpcSchema<RouterClient<AppRouter>>>().toEqualTypeOf<OrpcSchema<AppRouter>>();
141
+ });
142
+
143
+ it("should reject types that are not a router", () => {
144
+ // @ts-expect-error a string is not a router
145
+ expectTypeOf<OrpcSchema<string>>().toBeObject();
146
+ });
147
+
148
+ describe("when the router is composed", () => {
149
+ const nested = { count: os.handler(() => 1) };
150
+ const composedRouter = {
151
+ lazyRouter: os.lazy(async () => ({ default: nested })),
152
+ a: { b: { c: { leaf: os.handler(() => "deep" as const) } } },
153
+ camelCaseName: os.handler(() => true),
154
+ nothing: os.handler(() => {}),
155
+ union: os
156
+ .input(
157
+ z.discriminatedUnion("kind", [
158
+ z.object({ kind: z.literal("a") }),
159
+ z.object({ kind: z.literal("b"), id: z.number() }),
160
+ ]),
161
+ )
162
+ .handler(() => 1),
163
+ nullable: os.input(z.string().nullable()).handler(() => 1),
164
+ list: os.input(z.array(z.number())).handler(({ input }) => input.length),
165
+ transformed: os.input(z.string().transform((value) => value.length)).handler(({ input }) => input),
166
+ };
167
+ const composedClient = createClient({ url: "http://localhost:3000/rpc" }).setAdapter(OrpcAdapter());
168
+ const composed = createSdk<typeof composedClient, OrpcSchema<typeof composedRouter>>(composedClient, {
169
+ camelCaseToKebabCase: false,
170
+ });
171
+ type Composed = typeof composed;
172
+
173
+ it("should infer the lazy and deep procedures", () => {
174
+ expectTypeOf<ExtractResponseType<Composed["lazyRouter"]["count"]["$query"]>>().toEqualTypeOf<number>();
175
+ expectTypeOf<ExtractResponseType<Composed["a"]["b"]["c"]["leaf"]["$query"]>>().toEqualTypeOf<"deep">();
176
+ expectTypeOf<ExtractEndpointType<Composed["a"]["b"]["c"]["leaf"]["$query"]>>().toEqualTypeOf<"/a/b/c/leaf">();
177
+ });
178
+
179
+ it("should keep the procedure names as written", () => {
180
+ expectTypeOf<ExtractEndpointType<Composed["camelCaseName"]["$query"]>>().toEqualTypeOf<"/camelCaseName">();
181
+ });
182
+
183
+ it("should infer a procedure without an output", () => {
184
+ expectTypeOf<ExtractResponseType<Composed["nothing"]["$mutation"]>>().toEqualTypeOf<unknown>();
185
+ expectTypeOf<ExtractPayloadType<Composed["nothing"]["$mutation"]>>().toEqualTypeOf<undefined>();
186
+ });
187
+
188
+ it("should infer union, nullable and array inputs", () => {
189
+ expectTypeOf<ExtractPayloadType<Composed["union"]["$query"]>>().toEqualTypeOf<
190
+ { kind: "a" } | { kind: "b"; id: number }
191
+ >();
192
+ expectTypeOf<ExtractPayloadType<Composed["nullable"]["$query"]>>().toEqualTypeOf<string | null>();
193
+ expectTypeOf<ExtractPayloadType<Composed["list"]["$mutation"]>>().toEqualTypeOf<number[]>();
194
+ });
195
+
196
+ it("should use the schema input before the transformation", () => {
197
+ expectTypeOf<ExtractPayloadType<Composed["transformed"]["$query"]>>().toEqualTypeOf<string>();
198
+ expectTypeOf<ExtractResponseType<Composed["transformed"]["$query"]>>().toEqualTypeOf<number>();
199
+ });
200
+
201
+ it("should validate the SDK configuration keys", () => {
202
+ composed.$configure({ "*": { retry: 1 }, "camelCaseName.$query": { cache: false } });
203
+
204
+ expectTypeOf(composed.$configure).toBeFunction();
205
+ });
206
+ });
207
+
208
+ describe("when the API is contract-first", () => {
209
+ const contract = {
210
+ planet: {
211
+ find: oc
212
+ .input(z.object({ id: z.number() }))
213
+ .output(z.object({ name: z.string() }))
214
+ .errors({ NOT_FOUND: { data: z.object({ id: z.number() }) } }),
215
+ },
216
+ };
217
+ const contractClient = createClient({ url: "http://localhost:3000/rpc" }).setAdapter(OrpcAdapter());
218
+
219
+ it("should infer the procedures from the contract client type", () => {
220
+ const planets = createSdk<typeof contractClient, OrpcSchema<ContractRouterClient<typeof contract>>>(
221
+ contractClient,
222
+ { camelCaseToKebabCase: false },
223
+ );
224
+ type Find = (typeof planets)["planet"]["find"]["$query"];
225
+
226
+ expectTypeOf<ExtractPayloadType<Find>>().toEqualTypeOf<{ id: number }>();
227
+ expectTypeOf<ExtractResponseType<Find>>().toEqualTypeOf<{ name: string }>();
228
+ expectTypeOf<Extract<ExtractLocalErrorType<Find>, { defined: true }>["data"]>().toEqualTypeOf<{ id: number }>();
229
+ });
230
+
231
+ it("should infer the procedures from the implemented router", () => {
232
+ const router = implement(contract).router({
233
+ planet: { find: implement(contract).planet.find.handler(({ input }) => ({ name: `${input.id}` })) },
234
+ });
235
+ const planets = createSdk<typeof contractClient, OrpcSchema<typeof router>>(contractClient, {
236
+ camelCaseToKebabCase: false,
237
+ });
238
+
239
+ expectTypeOf<ExtractResponseType<(typeof planets)["planet"]["find"]["$query"]>>().toEqualTypeOf<{
240
+ name: string;
241
+ }>();
242
+ });
243
+ });
244
+
245
+ it("should type the React hooks", () => {
246
+ const useTypedHooks = () => {
247
+ const fetchHook = useFetch(api.user.byId.$query.setPayload({ id: 1 }));
248
+ const submitHook = useSubmit(api.user.create.$mutation);
249
+
250
+ expectTypeOf(fetchHook.data).toEqualTypeOf<User | null>();
251
+ expectTypeOf(submitHook.data).toEqualTypeOf<User | null>();
252
+ submitHook.submit({ payload: { name: "John" } });
253
+ // @ts-expect-error wrong input type
254
+ submitHook.submit({ payload: { id: 1 } });
255
+ };
256
+
257
+ expectTypeOf(useTypedHooks).toBeFunction();
258
+ });
259
+
260
+ it("should validate the adapter options", () => {
261
+ OrpcAdapter({ queryMethod: "GET" });
262
+ OrpcAdapter({ queryMethod: "POST", customJsonSerializers: [] });
263
+ // @ts-expect-error mutations always use POST, other methods are not supported
264
+ OrpcAdapter({ queryMethod: "PUT" });
265
+ expectTypeOf<NonNullable<OrpcAdapterOptionsType["queryMethod"]>>().toEqualTypeOf<"POST" | "GET">();
266
+
267
+ client.createRequest()({ endpoint: "health" }).setOptions({ queryMethod: "GET", timeout: 1 });
268
+ // @ts-expect-error unknown method
269
+ client.createRequest()({ endpoint: "health" }).setOptions({ queryMethod: "DELETE" });
270
+ });
271
+ });
@@ -0,0 +1,346 @@
1
+ /**
2
+ * @vitest-environment node
3
+ */
4
+ import { createClient, getErrorMessage } from "@hyper-fetch/core";
5
+
6
+ import { OrpcAdapter } from "../../../src/adapter";
7
+
8
+ const url = "http://localhost:3000/rpc";
9
+
10
+ const encoder = new TextEncoder();
11
+
12
+ const jsonHeaders = { "content-type": "application/json" };
13
+
14
+ const streamOf = (chunks: Uint8Array[]) => {
15
+ return new ReadableStream<Uint8Array>({
16
+ start(controller) {
17
+ chunks.forEach((chunk) => controller.enqueue(chunk));
18
+ controller.close();
19
+ },
20
+ });
21
+ };
22
+
23
+ /** Splits the text into single bytes, so every multi-byte character is cut in the middle */
24
+ const toSingleBytes = (text: string) => Array.from(encoder.encode(text), (byte) => Uint8Array.of(byte));
25
+
26
+ /** Fetch that stays pending until the request is aborted, the same way as the real one */
27
+ const pendingFetch = (_input: RequestInfo | URL, init?: RequestInit) => {
28
+ return new Promise<Response>((_resolve, reject) => {
29
+ init?.signal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));
30
+ });
31
+ };
32
+
33
+ describe("Orpc Adapter [ Transport ]", () => {
34
+ let client = createClient({ url }).setAdapter(OrpcAdapter());
35
+
36
+ const createQuery = () => client.createRequest<{ response: string }>()({ endpoint: "text" });
37
+
38
+ const mockFetch = (response: Response | Record<string, unknown>) => {
39
+ return vi.spyOn(globalThis, "fetch").mockResolvedValue(response as Response);
40
+ };
41
+
42
+ beforeEach(() => {
43
+ client = createClient({ url }).setAdapter(OrpcAdapter());
44
+ });
45
+
46
+ afterEach(() => {
47
+ vi.useRealTimers();
48
+ vi.restoreAllMocks();
49
+ client.clear();
50
+ });
51
+
52
+ describe("when reading the response body", () => {
53
+ it("should decode multi-byte characters split between chunks", async () => {
54
+ const text = "zażółć gęślą jaźń 🎡 日本語";
55
+ const body = JSON.stringify({ json: text });
56
+ mockFetch(new Response(streamOf(toSingleBytes(body)), { headers: jsonHeaders }));
57
+
58
+ const response = await createQuery().send();
59
+
60
+ expect(response.data).toBe(text);
61
+ });
62
+
63
+ it("should read a body sent in many chunks", async () => {
64
+ const text = "a".repeat(100_000);
65
+ const bytes = encoder.encode(JSON.stringify({ json: text }));
66
+ const chunks = Array.from({ length: Math.ceil(bytes.length / 1024) }, (_, index) => {
67
+ return bytes.slice(index * 1024, (index + 1) * 1024);
68
+ });
69
+ mockFetch(new Response(streamOf(chunks), { headers: jsonHeaders }));
70
+
71
+ const response = await createQuery().send();
72
+
73
+ expect(response.data).toBe(text);
74
+ });
75
+
76
+ it("should report the progress based on the content length", async () => {
77
+ const bytes = encoder.encode(JSON.stringify({ json: "progress" }));
78
+ const half = Math.floor(bytes.length / 2);
79
+ const onDownloadProgress = vi.fn();
80
+ mockFetch(
81
+ new Response(streamOf([bytes.slice(0, half), bytes.slice(half)]), {
82
+ headers: { ...jsonHeaders, "content-length": String(bytes.length) },
83
+ }),
84
+ );
85
+
86
+ await createQuery().send({ onDownloadProgress });
87
+
88
+ expect(onDownloadProgress).toHaveBeenCalledWith(expect.objectContaining({ loaded: half, total: bytes.length }));
89
+ expect(onDownloadProgress).toHaveBeenCalledWith(
90
+ expect.objectContaining({ loaded: bytes.length, total: bytes.length }),
91
+ );
92
+ });
93
+
94
+ it("should report the progress without the content length", async () => {
95
+ const bytes = encoder.encode(JSON.stringify({ json: "progress" }));
96
+ const onDownloadProgress = vi.fn();
97
+ mockFetch(new Response(streamOf([bytes]), { headers: jsonHeaders }));
98
+
99
+ await createQuery().send({ onDownloadProgress });
100
+
101
+ expect(onDownloadProgress).toHaveBeenCalledWith(
102
+ expect.objectContaining({ loaded: bytes.length, total: bytes.length }),
103
+ );
104
+ });
105
+
106
+ it("should read the text when the response has no stream", async () => {
107
+ mockFetch({
108
+ status: 200,
109
+ headers: new Headers(jsonHeaders),
110
+ body: null,
111
+ text: async () => JSON.stringify({ json: "from text" }),
112
+ });
113
+
114
+ const response = await createQuery().send();
115
+
116
+ expect(response.data).toBe("from text");
117
+ });
118
+
119
+ it("should read the text when the stream has no reader", async () => {
120
+ mockFetch({
121
+ status: 200,
122
+ headers: new Headers(jsonHeaders),
123
+ body: {},
124
+ text: async () => JSON.stringify({ json: "from text" }),
125
+ });
126
+
127
+ const response = await createQuery().send();
128
+
129
+ expect(response.data).toBe("from text");
130
+ });
131
+
132
+ // An empty body is an undefined output for the oRPC client as well
133
+ it("should map a response without a body to null", async () => {
134
+ mockFetch(new Response(null, { status: 204 }));
135
+
136
+ const response = await createQuery().send();
137
+
138
+ expect(response.data).toBeNull();
139
+ expect(response.error).toBeNull();
140
+ expect(response.status).toBe(204);
141
+ expect(response.success).toBe(true);
142
+ });
143
+
144
+ it("should map an empty stream to null", async () => {
145
+ mockFetch(new Response(streamOf([]), { headers: jsonHeaders }));
146
+
147
+ const response = await createQuery().send();
148
+
149
+ expect(response.data).toBeNull();
150
+ expect(response.success).toBe(true);
151
+ });
152
+
153
+ it("should fail for a malformed JSON", async () => {
154
+ mockFetch(new Response('{"json":', { headers: jsonHeaders }));
155
+
156
+ const response = await createQuery().send();
157
+
158
+ expect(response.error).toStrictEqual(getErrorMessage());
159
+ expect(response.success).toBe(false);
160
+ });
161
+
162
+ it("should keep the status and headers when the stream breaks", async () => {
163
+ const failure = new Error("Connection lost");
164
+ const stream = new ReadableStream<Uint8Array>({
165
+ start(controller) {
166
+ controller.enqueue(encoder.encode('{"json":'));
167
+ controller.error(failure);
168
+ },
169
+ });
170
+ mockFetch(new Response(stream, { status: 200, headers: { "x-request-id": "abc" } }));
171
+
172
+ const response = await createQuery().send();
173
+
174
+ expect(response.error).toBe(failure);
175
+ expect(response.status).toBe(200);
176
+ expect(response.extra?.headers["x-request-id"]).toBe("abc");
177
+ });
178
+
179
+ it("should expose all the response headers", async () => {
180
+ mockFetch(Response.json({ json: "ok" }, { headers: { "x-first": "1", "x-second": "2" } }));
181
+
182
+ const response = await createQuery().send();
183
+
184
+ expect(response.extra?.headers).toMatchObject({ "x-first": "1", "x-second": "2" });
185
+ });
186
+ });
187
+
188
+ describe("when the request is interrupted", () => {
189
+ it("should time out while waiting for the response", async () => {
190
+ vi.spyOn(globalThis, "fetch").mockImplementation(pendingFetch);
191
+
192
+ const response = await createQuery().setOptions({ timeout: 5 }).send();
193
+
194
+ expect(response.error).toStrictEqual(getErrorMessage("timeout"));
195
+ expect(response.status).toBe(0);
196
+ expect(response.extra).toStrictEqual({ headers: {} });
197
+ });
198
+
199
+ it("should time out while reading the body", async () => {
200
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_input, init) => {
201
+ return new Response(
202
+ new ReadableStream<Uint8Array>({
203
+ start(controller) {
204
+ controller.enqueue(encoder.encode('{"json":'));
205
+ init?.signal?.addEventListener("abort", () => {
206
+ controller.error(new DOMException("Aborted", "AbortError"));
207
+ });
208
+ },
209
+ }),
210
+ );
211
+ });
212
+
213
+ const response = await createQuery().setOptions({ timeout: 5 }).send();
214
+
215
+ expect(response.error).toStrictEqual(getErrorMessage("timeout"));
216
+ expect(response.status).toBe(0);
217
+ });
218
+
219
+ it("should abort while reading the body", async () => {
220
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_input, init) => {
221
+ return new Response(
222
+ new ReadableStream<Uint8Array>({
223
+ start(controller) {
224
+ controller.enqueue(encoder.encode('{"json":'));
225
+ init?.signal?.addEventListener("abort", () => {
226
+ controller.error(new DOMException("Aborted", "AbortError"));
227
+ });
228
+ },
229
+ }),
230
+ );
231
+ });
232
+
233
+ const request = createQuery();
234
+ const response = await request.send({ onDownloadProgress: () => request.abort() });
235
+
236
+ expect(response.error).toStrictEqual(getErrorMessage("abort"));
237
+ expect(response.status).toBe(0);
238
+ });
239
+
240
+ it("should use the default timeout of 5 seconds", async () => {
241
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
242
+ vi.spyOn(globalThis, "fetch").mockImplementation(pendingFetch);
243
+ const onResolved = vi.fn();
244
+
245
+ const pending = createQuery().send().then(onResolved);
246
+
247
+ await vi.advanceTimersByTimeAsync(4999);
248
+ expect(onResolved).not.toHaveBeenCalled();
249
+
250
+ await vi.advanceTimersByTimeAsync(1);
251
+ await pending;
252
+
253
+ expect(onResolved).toHaveBeenCalledWith(
254
+ expect.objectContaining({ error: getErrorMessage("timeout"), status: 0 }),
255
+ );
256
+ });
257
+
258
+ it("should not time out when the timeout is disabled", async () => {
259
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
260
+ let respond: (response: Response) => void = () => null;
261
+ const spy = vi.spyOn(globalThis, "fetch").mockImplementation((_input, init) => {
262
+ return new Promise<Response>((resolve, reject) => {
263
+ respond = resolve;
264
+ init?.signal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));
265
+ });
266
+ });
267
+
268
+ const pending = createQuery().setOptions({ timeout: 0 }).send();
269
+
270
+ await vi.advanceTimersByTimeAsync(60_000);
271
+ expect((spy.mock.calls[0][1] as RequestInit).signal?.aborted).toBe(false);
272
+
273
+ respond(Response.json({ json: "late" }));
274
+ const response = await pending;
275
+
276
+ expect(response.data).toBe("late");
277
+ expect(response.error).toBeNull();
278
+ });
279
+
280
+ it("should clear the timeout after the response has arrived", async () => {
281
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
282
+ const spy = mockFetch(Response.json({ json: "ok" }));
283
+
284
+ const pending = createQuery().setOptions({ timeout: 10 }).send();
285
+ await vi.advanceTimersByTimeAsync(1);
286
+ const response = await pending;
287
+ await vi.advanceTimersByTimeAsync(1000);
288
+
289
+ expect(response.data).toBe("ok");
290
+ expect((spy.mock.calls[0][1] as RequestInit).signal?.aborted).toBe(false);
291
+ });
292
+
293
+ it("should not report an abort after the response has arrived", async () => {
294
+ mockFetch(Response.json({ json: "ok" }));
295
+ const request = createQuery();
296
+
297
+ const response = await request.send();
298
+ request.abort();
299
+
300
+ expect(response.data).toBe("ok");
301
+ expect(response.error).toBeNull();
302
+ });
303
+ });
304
+
305
+ describe("when passing the adapter options", () => {
306
+ const getInit = (spy: { mock: { calls: unknown[][] } }) => spy.mock.calls[0][1] as RequestInit;
307
+
308
+ it("should pass the options to fetch", async () => {
309
+ const spy = mockFetch(Response.json({ json: "ok" }));
310
+
311
+ await createQuery().setOptions({ credentials: "include", cache: "no-store", keepalive: true }).send();
312
+
313
+ expect(getInit(spy)).toMatchObject({ credentials: "include", cache: "no-store", keepalive: true });
314
+ });
315
+
316
+ it("should not pass the timeout to fetch", async () => {
317
+ const spy = mockFetch(Response.json({ json: "ok" }));
318
+
319
+ await createQuery().setOptions({ timeout: 100 }).send();
320
+
321
+ expect(getInit(spy)).not.toHaveProperty("timeout");
322
+ });
323
+
324
+ it("should not let the options replace the transport fields", async () => {
325
+ const spy = mockFetch(Response.json({ json: "ok" }));
326
+ const foreignSignal = new AbortController().signal;
327
+
328
+ // Fields outside of the options type can still come from untyped code
329
+ const foreignOptions = {
330
+ timeout: 1000,
331
+ method: "DELETE",
332
+ headers: { "x-foreign": "1" },
333
+ body: "foreign",
334
+ signal: foreignSignal,
335
+ };
336
+
337
+ await createQuery().setOptions(foreignOptions).send();
338
+
339
+ const init = getInit(spy);
340
+ expect(init.method).toBe("POST");
341
+ expect(init.headers).toStrictEqual({ "Content-Type": "application/json" });
342
+ expect(init.body).toBe("{}");
343
+ expect(init.signal).not.toBe(foreignSignal);
344
+ });
345
+ });
346
+ });