@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
package/README.md CHANGED
@@ -1,3 +1,101 @@
1
- # Temporary Holding Version
1
+ # 🛸 Hyper Fetch oRPC
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center">
4
+ <b>oRPC adapter for HyperFetch. Typed procedures with caching, queueing and React hooks.</b>
5
+ </p>
6
+
7
+ <p align="center">
8
+ <a href="https://github.com/BetterTyped/hyper-fetch">
9
+ <img src="https://img.shields.io/github/stars/BetterTyped/hyper-fetch?logo=github&color=118ab2" />
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@hyper-fetch/orpc">
12
+ <img src="https://img.shields.io/npm/v/@hyper-fetch/orpc.svg?logo=npm&color=e76f51" />
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/@hyper-fetch/orpc">
15
+ <img src="https://img.shields.io/npm/dm/@hyper-fetch/orpc.svg?logo=npm&color=2a9d8f" />
16
+ </a>
17
+ <a href="https://bundlephobia.com/package/@hyper-fetch/orpc">
18
+ <img src="https://img.shields.io/bundlephobia/minzip/@hyper-fetch/orpc?color=8338ec" />
19
+ </a>
20
+ <a href="https://github.com/BetterTyped/hyper-fetch/blob/main/License.md">
21
+ <img src="https://img.shields.io/github/license/BetterTyped/hyper-fetch?color=yellow" />
22
+ </a>
23
+ <img src="https://img.shields.io/badge/TypeScript-ready-3178c6?logo=typescript&logoColor=white" />
24
+ <img src="https://img.shields.io/badge/oRPC-v1-000000" />
25
+ </p>
26
+
27
+ ## 📖 About
28
+
29
+ This adapter connects HyperFetch to an oRPC server through the oRPC RPC protocol. Procedures become regular HyperFetch
30
+ requests, with inputs, outputs and defined errors inferred from your router through `createSdk`.
31
+
32
+ ## 🎯 Key Capabilities
33
+
34
+ - 🔮 **End-to-end types** - Inputs, outputs and `.errors()` maps inferred from your router or contract
35
+ - 📅 **Rich types on the wire** - `Date`, `BigInt`, `Map`, `Set`, `URL` and files, encoded by the oRPC serializer
36
+ - 💾 **Cache per input** - `{ id: 1 }` and `{ id: 2 }` are cached, deduplicated and queued separately
37
+ - ⚛️ **React-ready** - Use `useFetch` and `useSubmit` with your procedures
38
+ - 🌐 **GET when you want it** - Opt into cacheable `GET` queries for the procedures your server allows
39
+
40
+ ## 🚀 Quick Start
41
+
42
+ ```bash
43
+ npm install @hyper-fetch/core @hyper-fetch/orpc @orpc/client
44
+ ```
45
+
46
+ ```ts
47
+ import { createClient, createSdk } from "@hyper-fetch/core";
48
+ import { OrpcAdapter } from "@hyper-fetch/orpc";
49
+ import type { OrpcSchema } from "@hyper-fetch/orpc";
50
+
51
+ import type { router } from "./server";
52
+
53
+ const client = createClient({ url: "http://localhost:3000/rpc" }).setAdapter(OrpcAdapter());
54
+ const api = createSdk<typeof client, OrpcSchema<typeof router>>(client, { camelCaseToKebabCase: false });
55
+
56
+ const { data, error } = await api.planet.find.$query.setPayload({ id: 1 }).send();
57
+ ```
58
+
59
+ ## 📚 Documentation
60
+
61
+ - [oRPC Adapter Docs](https://hyperfetch.bettertyped.com/docs/integrations/adapter-orpc/overview)
62
+ - [Getting Started](https://hyperfetch.bettertyped.com/docs/getting-started/quick-start)
63
+ - [API Reference](https://hyperfetch.bettertyped.com/api/)
64
+
65
+ ## 💡 Examples
66
+
67
+ ### Handle a defined error
68
+
69
+ ```ts
70
+ const { data, error } = await api.planet.find.$query.setPayload({ id: 99 }).send();
71
+
72
+ if (error?.defined && error.code === "NOT_FOUND") {
73
+ console.log(`Planet ${error.data.id} does not exist`);
74
+ }
75
+ ```
76
+
77
+ ### Upload a file
78
+
79
+ ```tsx
80
+ import { useSubmit } from "@hyper-fetch/react";
81
+
82
+ const { submit, submitting } = useSubmit(api.planet.uploadImage.$mutation);
83
+
84
+ await submit({ payload: { planetId: 1, image: file } });
85
+ ```
86
+
87
+ ### Contract-first APIs
88
+
89
+ ```ts
90
+ import type { ContractRouterClient } from "@orpc/contract";
91
+
92
+ import type { contract } from "./contract";
93
+
94
+ const api = createSdk<typeof client, OrpcSchema<ContractRouterClient<typeof contract>>>(client, {
95
+ camelCaseToKebabCase: false,
96
+ });
97
+ ```
98
+
99
+ ## License
100
+
101
+ [Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
@@ -0,0 +1,187 @@
1
+ /**
2
+ * @vitest-environment node
3
+ */
4
+ import type { RequestInstance } from "@hyper-fetch/core";
5
+ import { createClient } from "@hyper-fetch/core";
6
+ import { createORPCClient, ORPCError } from "@orpc/client";
7
+ import { RPCLink } from "@orpc/client/fetch";
8
+ import type { RouterClient } from "@orpc/server";
9
+
10
+ import { OrpcAdapter } from "../../src/adapter";
11
+ import type { AppRouter } from "./e2e.orpc-server";
12
+ import { createAppRouter, createE2EOrpcServer } from "./e2e.orpc-server";
13
+
14
+ type WireRequest = { method: string; url: string; contentType: string | null; body: string };
15
+
16
+ /**
17
+ * Every request leaves through `fetch`, so both clients are compared on what they actually send.
18
+ */
19
+ const recordFetch = () => {
20
+ const realFetch = globalThis.fetch;
21
+ const sent: WireRequest[] = [];
22
+
23
+ const spy = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
24
+ const request = new Request(input, init);
25
+ const body = request.method === "GET" ? "" : await request.clone().text();
26
+ sent.push({
27
+ method: request.method,
28
+ url: request.url,
29
+ contentType: request.headers.get("content-type"),
30
+ body,
31
+ });
32
+ return realFetch(request);
33
+ });
34
+
35
+ return { sent, spy };
36
+ };
37
+
38
+ const date = new Date("2024-05-06T07:08:09.010Z");
39
+
40
+ /**
41
+ * Inputs the server validates. Top level falsy inputs like `false` or `""` are left out, because
42
+ * `setPayload` of the core drops them until the core fix from the tRPC adapter lands.
43
+ */
44
+ const inputs: [name: string, procedure: string[], input: unknown][] = [
45
+ ["no input", ["health"], undefined],
46
+ ["a number", ["double"], 21],
47
+ ["a negative float", ["double"], -1.5],
48
+ ["true", ["negate"], true],
49
+ ["unicode", ["shout"], "zażółć 🎡 日本語 & ?=#"],
50
+ ["an object", ["user", "byId"], { id: 1 }],
51
+ ["an optional input", ["user", "list"], { limit: 1 }],
52
+ ["a missing optional input", ["user", "list"], undefined],
53
+ ["special types", ["types", "nextDay"], { date, total: 12_345_678_901_234_567_890n }],
54
+ ];
55
+
56
+ describe("Orpc Adapter [ Conformance ]", () => {
57
+ const { startServer, stopServer } = createE2EOrpcServer(createAppRouter());
58
+
59
+ let baseUrl = "";
60
+
61
+ const createHf = (queryMethod: "GET" | "POST" = "POST") => {
62
+ return createClient({ url: baseUrl, mode: "client" }).setAdapter(OrpcAdapter({ queryMethod }));
63
+ };
64
+
65
+ const createOfficial = (method: "GET" | "POST" = "POST") => {
66
+ return createORPCClient<RouterClient<AppRouter>>(new RPCLink({ url: baseUrl, method }));
67
+ };
68
+
69
+ /** Calls the procedure with the official client, which throws the errors */
70
+ const callOfficial = async (method: "GET" | "POST", procedure: string[], input: unknown) => {
71
+ const official = createOfficial(method) as unknown as Record<string, unknown>;
72
+ const call = procedure.reduce<unknown>((node, key) => (node as Record<string, unknown>)[key], official);
73
+
74
+ try {
75
+ return { data: await (call as (value: unknown) => Promise<unknown>)(input), error: null };
76
+ } catch (error) {
77
+ return { data: null, error: error instanceof ORPCError ? error.toJSON() : error };
78
+ }
79
+ };
80
+
81
+ const callHf = async ({
82
+ method,
83
+ queryMethod,
84
+ procedure,
85
+ input,
86
+ }: {
87
+ method: "QUERY" | "MUTATION";
88
+ queryMethod: "GET" | "POST";
89
+ procedure: string[];
90
+ input: unknown;
91
+ }) => {
92
+ const request: RequestInstance = createHf(queryMethod).createRequest<{ response: unknown; payload: unknown }>()({
93
+ endpoint: procedure.join("/"),
94
+ method,
95
+ });
96
+ const response = await request.send({ payload: input });
97
+ return { data: response.data, error: response.error };
98
+ };
99
+
100
+ beforeAll(async () => {
101
+ baseUrl = `${await startServer()}/rpc`;
102
+ });
103
+
104
+ afterEach(() => {
105
+ vi.restoreAllMocks();
106
+ });
107
+
108
+ afterAll(async () => {
109
+ await stopServer();
110
+ });
111
+
112
+ describe("when sending with POST", () => {
113
+ it.each(inputs)("should match the official client for %s", async (_name, procedure, input) => {
114
+ const { sent } = recordFetch();
115
+
116
+ const official = await callOfficial("POST", procedure, input);
117
+ const query = await callHf({ method: "QUERY", queryMethod: "POST", procedure, input });
118
+ const mutation = await callHf({ method: "MUTATION", queryMethod: "POST", procedure, input });
119
+
120
+ expect(sent).toHaveLength(3);
121
+ expect(sent[1]).toStrictEqual(sent[0]);
122
+ expect(sent[2]).toStrictEqual(sent[0]);
123
+ expect(query).toStrictEqual(official);
124
+ expect(mutation).toStrictEqual(official);
125
+ });
126
+ });
127
+
128
+ describe("when sending with GET", () => {
129
+ it.each(inputs)("should match the official client for %s", async (_name, procedure, input) => {
130
+ const { sent } = recordFetch();
131
+
132
+ const official = await callOfficial("GET", procedure, input);
133
+ const query = await callHf({ method: "QUERY", queryMethod: "GET", procedure, input });
134
+
135
+ expect(sent).toHaveLength(2);
136
+ expect(sent[0].method).toBe("GET");
137
+ expect(sent[1]).toStrictEqual(sent[0]);
138
+ expect(query).toStrictEqual(official);
139
+ });
140
+
141
+ it("should fall back to POST for a long input like the official client", async () => {
142
+ const { sent } = recordFetch();
143
+ const input = "a".repeat(3000);
144
+
145
+ const official = await callOfficial("GET", ["shout"], input);
146
+ const query = await callHf({ method: "QUERY", queryMethod: "GET", procedure: ["shout"], input });
147
+
148
+ expect(sent.map(({ method }) => method)).toStrictEqual(["POST", "POST"]);
149
+ expect(sent[1]).toStrictEqual(sent[0]);
150
+ expect(query).toStrictEqual(official);
151
+ });
152
+ });
153
+
154
+ describe("when the procedure fails", () => {
155
+ it.each([
156
+ ["a defined error", ["user", "byId"], { id: 99 }],
157
+ ["a common error", ["fail"], { code: "CONFLICT" }],
158
+ ["a custom error", ["fail"], { code: "OUT_OF_STOCK", status: 418 }],
159
+ ["a crash", ["crash"], undefined],
160
+ ["an invalid input", ["double"], "not a number"],
161
+ ["an invalid output", ["badOutput"], undefined],
162
+ ["a middleware error", ["me"], undefined],
163
+ ])("should return the same error as the official client for %s", async (_name, procedure, input) => {
164
+ const official = await callOfficial("POST", procedure, input);
165
+ const query = await callHf({ method: "QUERY", queryMethod: "POST", procedure, input });
166
+
167
+ expect(official.error).not.toBeNull();
168
+ expect(query).toStrictEqual(official);
169
+ });
170
+ });
171
+
172
+ describe("when sending files", () => {
173
+ it("should send the same multipart body as the official client", async () => {
174
+ const { sent } = recordFetch();
175
+ const input = { name: "Notes", file: new File(["content"], "notes.txt", { type: "text/plain" }) };
176
+
177
+ const official = await callOfficial("GET", ["types", "upload"], input);
178
+ const query = await callHf({ method: "QUERY", queryMethod: "GET", procedure: ["types", "upload"], input });
179
+
180
+ expect(sent.map(({ method }) => method)).toStrictEqual(["POST", "POST"]);
181
+ // The multipart boundary is random, everything around it has to match
182
+ const [officialBoundary, hfBoundary] = sent.map(({ contentType }) => contentType?.split("boundary=")[1] ?? "");
183
+ expect(sent[1].body.replaceAll(hfBoundary, "")).toBe(sent[0].body.replaceAll(officialBoundary, ""));
184
+ expect(query).toStrictEqual(official);
185
+ });
186
+ });
187
+ });
@@ -0,0 +1,163 @@
1
+ import type { AnyRouter } from "@orpc/server";
2
+ import { ORPCError, os } from "@orpc/server";
3
+ import { RPCHandler } from "@orpc/server/node";
4
+ import { createServer } from "http";
5
+ import type { AddressInfo } from "net";
6
+ import { z } from "zod";
7
+
8
+ export type User = { id: number; name: string };
9
+
10
+ export type RecordedRequest = { method?: string; url?: string; contentType?: string };
11
+
12
+ type Context = { authorization?: string };
13
+
14
+ const users: User[] = [
15
+ { id: 1, name: "John" },
16
+ { id: 2, name: "Jane" },
17
+ ];
18
+
19
+ /**
20
+ * Lets a test hold a procedure open for as long as it needs, without relying on timers.
21
+ */
22
+ export const createGate = () => {
23
+ let markStarted = () => {};
24
+ let release = () => {};
25
+
26
+ const started = new Promise<void>((resolve) => {
27
+ markStarted = resolve;
28
+ });
29
+ const released = new Promise<void>((resolve) => {
30
+ release = resolve;
31
+ });
32
+
33
+ return { started, released, markStarted, release };
34
+ };
35
+
36
+ export type Gate = ReturnType<typeof createGate>;
37
+
38
+ const DAY = 24 * 60 * 60 * 1000;
39
+
40
+ export const createAppRouter = (getGate: () => Gate = createGate) => {
41
+ const base = os.$context<Context>();
42
+
43
+ const authed = base.middleware(({ context, next }) => {
44
+ if (context.authorization !== "Bearer token") {
45
+ throw new ORPCError("UNAUTHORIZED", { message: "Missing token" });
46
+ }
47
+ return next({ context: { user: "admin" } });
48
+ });
49
+
50
+ return {
51
+ health: base.handler(() => "ok" as const),
52
+ double: base.input(z.number()).handler(({ input }) => input * 2),
53
+ negate: base.input(z.boolean()).handler(({ input }) => !input),
54
+ shout: base.input(z.string()).handler(({ input }) => input.toUpperCase()),
55
+ noop: base.handler(() => {}),
56
+ held: base.handler(async () => {
57
+ const gate = getGate();
58
+ gate.markStarted();
59
+ await gate.released;
60
+ return "released";
61
+ }),
62
+ fail: base.input(z.object({ code: z.string(), status: z.number().optional() })).handler(({ input }) => {
63
+ throw new ORPCError(input.code, { status: input.status, message: `Failed with ${input.code}` });
64
+ }),
65
+ crash: base.handler(() => {
66
+ throw new Error("Unexpected crash");
67
+ }),
68
+ badOutput: base.output(z.object({ id: z.number() })).handler(() => ({ id: "1" }) as unknown as { id: number }),
69
+ me: base.use(authed).handler(({ context }) => context.user),
70
+ ticks: base.handler(async function* ticks() {
71
+ yield 1;
72
+ }),
73
+ user: {
74
+ byId: base
75
+ .route({ method: "GET" })
76
+ .input(z.object({ id: z.number() }))
77
+ .errors({ NOT_FOUND: { message: "User not found", data: z.object({ id: z.number() }) } })
78
+ .handler(({ input, errors }) => {
79
+ const user = users.find(({ id }) => id === input.id);
80
+ if (!user) {
81
+ throw errors.NOT_FOUND({ data: { id: input.id } });
82
+ }
83
+ return user;
84
+ }),
85
+ list: base
86
+ .input(z.object({ limit: z.number().optional() }).optional())
87
+ .handler(({ input }) => users.slice(0, input?.limit ?? users.length)),
88
+ create: base.input(z.object({ name: z.string() })).handler(({ input }): User => ({ id: 3, name: input.name })),
89
+ },
90
+ types: {
91
+ nextDay: base.input(z.object({ date: z.date(), total: z.bigint() })).handler(({ input }) => ({
92
+ date: new Date(input.date.getTime() + DAY),
93
+ total: input.total * 2n,
94
+ tags: new Set(["a", "b"]),
95
+ scores: new Map([["a", 1]]),
96
+ sparse: [1, undefined],
97
+ site: new URL("https://orpc.dev/docs"),
98
+ notANumber: Number.NaN,
99
+ pattern: /orpc/gi,
100
+ })),
101
+ upload: base.input(z.object({ name: z.string(), file: z.instanceof(Blob) })).handler(async ({ input }) => ({
102
+ name: input.name,
103
+ fileName: input.file instanceof File ? input.file.name : "blob",
104
+ size: input.file.size,
105
+ text: await input.file.text(),
106
+ })),
107
+ epoch: base.handler(() => ({ at: new Date(0), tags: new Set(["a"]) })),
108
+ download: base.handler(() => ({
109
+ file: new File(["hello"], "hello.txt", { type: "text/plain" }),
110
+ createdAt: new Date("2024-01-01T00:00:00.000Z"),
111
+ })),
112
+ },
113
+ };
114
+ };
115
+
116
+ export type AppRouter = ReturnType<typeof createAppRouter>;
117
+
118
+ /**
119
+ * Real oRPC server listening on a random local port.
120
+ */
121
+ export const createE2EOrpcServer = (
122
+ router: AnyRouter,
123
+ {
124
+ prefix = "/rpc",
125
+ handlerOptions,
126
+ }: { prefix?: `/${string}`; handlerOptions?: { strictGetMethodPluginEnabled?: boolean } } = {},
127
+ ) => {
128
+ const requests: RecordedRequest[] = [];
129
+ const handler = new RPCHandler<Context>(router, handlerOptions);
130
+
131
+ const server = createServer(async (req, res) => {
132
+ requests.push({ method: req.method, url: req.url, contentType: req.headers["content-type"] });
133
+
134
+ const { matched } = await handler.handle(req, res, {
135
+ prefix,
136
+ context: { authorization: req.headers.authorization },
137
+ });
138
+
139
+ if (!matched) {
140
+ res.statusCode = 404;
141
+ res.end("No procedure matched");
142
+ }
143
+ });
144
+
145
+ const startServer = () => {
146
+ return new Promise<string>((resolve, reject) => {
147
+ server.once("error", reject);
148
+ server.listen(0, "127.0.0.1", () => {
149
+ const { port } = server.address() as AddressInfo;
150
+ resolve(`http://127.0.0.1:${port}`);
151
+ });
152
+ });
153
+ };
154
+
155
+ const stopServer = () => {
156
+ return new Promise<void>((resolve, reject) => {
157
+ server.close((error) => (error ? reject(error) : resolve()));
158
+ server.closeAllConnections();
159
+ });
160
+ };
161
+
162
+ return { startServer, stopServer, requests };
163
+ };