@hyper-fetch/hono 9.8.1 → 9.9.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 +1 -0
- 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/responses/responses.sdk.spec.ts +149 -0
- package/__tests__/features/responses/responses.types.spec.ts +107 -0
- package/__tests__/utils/inputs.app.ts +57 -0
- package/__tests__/utils/paths.app.ts +31 -0
- package/__tests__/utils/responses.app.ts +54 -0
- package/__tests__/utils/server.ts +18 -0
- package/dist/hono.types.d.ts +49 -10
- package/dist/hono.types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/hono.types.ts +90 -26
- package/vite.config.ts +5 -0
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { getCookie } from "hono/cookie";
|
|
3
|
+
import { validator } from "hono/validator";
|
|
4
|
+
|
|
5
|
+
const parseTitle = (value: unknown): { title: string; draft?: boolean } => {
|
|
6
|
+
if (typeof value === "object" && value !== null && "title" in value && typeof value.title === "string") {
|
|
7
|
+
const draft = "draft" in value && typeof value.draft === "boolean" ? value.draft : undefined;
|
|
8
|
+
return draft === undefined ? { title: value.title } : { title: value.title, draft };
|
|
9
|
+
}
|
|
10
|
+
throw new Error("Invalid post");
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A Hono app with every validator target: `json`, `query` with arrays, `form`, `header`, `cookie`
|
|
15
|
+
* and `param`, a route that combines several, and a validator that answers with its own error.
|
|
16
|
+
*/
|
|
17
|
+
export const inputsApp = new Hono()
|
|
18
|
+
.post("/posts", validator("json", parseTitle), (c) => c.json(c.req.valid("json"), 201))
|
|
19
|
+
.get(
|
|
20
|
+
"/search",
|
|
21
|
+
validator("query", (value) => value),
|
|
22
|
+
(c) => c.json({ query: c.req.valid("query"), tags: c.req.queries("tags") ?? [] }),
|
|
23
|
+
)
|
|
24
|
+
.post(
|
|
25
|
+
"/upload",
|
|
26
|
+
validator("form", (value) => value),
|
|
27
|
+
(c) => {
|
|
28
|
+
const { title } = c.req.valid("form");
|
|
29
|
+
return c.json({
|
|
30
|
+
title: typeof title === "string" ? title : null,
|
|
31
|
+
contentType: c.req.header("content-type") ?? null,
|
|
32
|
+
});
|
|
33
|
+
},
|
|
34
|
+
)
|
|
35
|
+
.get(
|
|
36
|
+
"/whoami",
|
|
37
|
+
validator("header", (value) => ({ requestId: value["x-request-id"] ?? null })),
|
|
38
|
+
validator("cookie", (value) => ({ session: value.session ?? null })),
|
|
39
|
+
(c) => c.json({ ...c.req.valid("header"), ...c.req.valid("cookie"), raw: getCookie(c, "session") ?? null }),
|
|
40
|
+
)
|
|
41
|
+
.put(
|
|
42
|
+
"/posts/:postId",
|
|
43
|
+
validator("param", (value) => ({ postId: Number(value.postId) })),
|
|
44
|
+
validator("json", parseTitle),
|
|
45
|
+
validator("query", (value) => ({ notify: value.notify === "true" })),
|
|
46
|
+
(c) => c.json({ ...c.req.valid("param"), ...c.req.valid("json"), ...c.req.valid("query") }),
|
|
47
|
+
)
|
|
48
|
+
.post(
|
|
49
|
+
"/strict",
|
|
50
|
+
validator("json", (value, c) => {
|
|
51
|
+
if (typeof value !== "object" || value === null || !("name" in value)) {
|
|
52
|
+
return c.json({ error: "Name is required" as const }, 400);
|
|
53
|
+
}
|
|
54
|
+
return { name: String(value.name) };
|
|
55
|
+
}),
|
|
56
|
+
(c) => c.json({ name: c.req.valid("json").name }, 200),
|
|
57
|
+
);
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { appendTrailingSlash } from "hono/trailing-slash";
|
|
3
|
+
|
|
4
|
+
const files = new Hono().get("/:fileId?", (c) => c.json({ fileId: c.req.param("fileId") ?? null }));
|
|
5
|
+
|
|
6
|
+
const sharedReads = new Hono().get("/", (c) => c.json({ read: true as const }));
|
|
7
|
+
const sharedWrites = new Hono().post("/", (c) => c.json({ written: true as const }));
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A Hono app with every kind of path segment: optional and regex params, wildcards, `.all()`,
|
|
11
|
+
* `app.on()` with several methods or paths, paths without a leading slash or with a trailing
|
|
12
|
+
* slash (served through `appendTrailingSlash()`), two routers on one path, and a deeply nested route.
|
|
13
|
+
*/
|
|
14
|
+
export const pathsApp = new Hono()
|
|
15
|
+
.use("/slash", appendTrailingSlash())
|
|
16
|
+
.route("/files", files)
|
|
17
|
+
.get("/versions/:major/:minor?/:patch?", (c) => c.json(c.req.param()))
|
|
18
|
+
.get("/posts/:postId{[0-9]+}", (c) => c.json({ postId: c.req.param("postId") }))
|
|
19
|
+
.get("/archive/:year{[0-9]{4}}/:slug", (c) => c.json(c.req.param()))
|
|
20
|
+
.get("/assets/*", (c) => c.json({ path: c.req.path }))
|
|
21
|
+
.all("/echo", (c) => c.json({ method: c.req.method }))
|
|
22
|
+
.on(["PUT", "PATCH"], "/items/:itemId", (c) => c.json({ method: c.req.method, itemId: c.req.param("itemId") }))
|
|
23
|
+
.on("GET", ["/health", "/status"], (c) => c.json({ up: true as const }))
|
|
24
|
+
.get("plain", (c) => c.json({ plain: true as const }))
|
|
25
|
+
.get("/slash/", (c) => c.json({ slash: true as const }))
|
|
26
|
+
.route("/shared", sharedReads)
|
|
27
|
+
.route("/shared", sharedWrites)
|
|
28
|
+
.get("/l1/l2/l3/l4/l5/l6/l7/l8/l9/l10/l11/:leaf", (c) => c.json({ leaf: c.req.param("leaf") }));
|
|
29
|
+
|
|
30
|
+
/** Optional params on the root path resolve to the top level. */
|
|
31
|
+
export const rootOptionalApp = new Hono().get("/:lang?", (c) => c.json({ lang: c.req.param("lang") ?? null }));
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { validator } from "hono/validator";
|
|
3
|
+
|
|
4
|
+
export interface Result {
|
|
5
|
+
ok: boolean;
|
|
6
|
+
note?: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Lets a test pick the branch a handler takes with `?flag=yes`. */
|
|
10
|
+
const flag = validator("query", (value) => ({ flag: value.flag === "yes" }));
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A Hono app with every kind of handler output: JSON primitives, `null`, `{}`, dates, interfaces,
|
|
14
|
+
* unions, several statuses, a middleware that answers early, `c.text()`, `c.body()`,
|
|
15
|
+
* `c.redirect()`, `c.newResponse()` and `c.notFound()`.
|
|
16
|
+
*/
|
|
17
|
+
export const responsesApp = new Hono()
|
|
18
|
+
.get("/json/string", (c) => c.json("a-string"))
|
|
19
|
+
.get("/json/number", (c) => c.json(37))
|
|
20
|
+
.get("/json/boolean", (c) => c.json(true))
|
|
21
|
+
.get("/json/null", (c) => c.json(null))
|
|
22
|
+
.get("/json/empty", (c) => c.json({}))
|
|
23
|
+
.get("/json/date", (c) => c.json({ at: new Date("2024-01-01T00:00:00.000Z") }))
|
|
24
|
+
.get("/json/interface", (c) => {
|
|
25
|
+
const results: Result[] = [{ ok: true }];
|
|
26
|
+
return c.json(results);
|
|
27
|
+
})
|
|
28
|
+
.get("/json/union", flag, (c) => (c.req.valid("query").flag ? c.json({ data: "foo" }) : c.json({ message: "error" })))
|
|
29
|
+
.get("/statuses", flag, (c) => {
|
|
30
|
+
if (c.req.valid("query").flag) {
|
|
31
|
+
return c.json({ message: "Bad request" }, 400);
|
|
32
|
+
}
|
|
33
|
+
return c.json({ data: "foo" }, 200);
|
|
34
|
+
})
|
|
35
|
+
.post(
|
|
36
|
+
"/guarded",
|
|
37
|
+
async (c, next) => {
|
|
38
|
+
if (!c.req.header("authorization")) {
|
|
39
|
+
return c.json({ error: "Unauthorized" as const }, 401);
|
|
40
|
+
}
|
|
41
|
+
await next();
|
|
42
|
+
},
|
|
43
|
+
(c) => c.json({ created: true as const }, 201),
|
|
44
|
+
)
|
|
45
|
+
.get("/text", (c) => c.text("Hello, Hono!"))
|
|
46
|
+
.get("/text/numeric", (c) => c.text("42"))
|
|
47
|
+
.get("/body", (c) => c.body("raw body"))
|
|
48
|
+
.delete("/body/empty", (c) => c.body(null, 204))
|
|
49
|
+
.get("/body/null", (c) => c.body(null))
|
|
50
|
+
.get("/redirect", flag, (c) =>
|
|
51
|
+
c.req.valid("query").flag ? c.redirect("/text") : c.json({ stayed: true as const }, 200),
|
|
52
|
+
)
|
|
53
|
+
.get("/new-response", (c) => c.newResponse("custom", 202))
|
|
54
|
+
.get("/not-found", (c) => c.notFound());
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { serve } from "@hono/node-server";
|
|
2
|
+
import type { ServerType } from "@hono/node-server";
|
|
3
|
+
import type { AddressInfo } from "node:net";
|
|
4
|
+
|
|
5
|
+
type FetchApp = { fetch: (request: Request) => Response | Promise<Response> };
|
|
6
|
+
|
|
7
|
+
/** Serves a Hono app on a free port and resolves with the server and its base URL. */
|
|
8
|
+
export const startServer = (app: FetchApp) =>
|
|
9
|
+
new Promise<{ server: ServerType; url: string }>((resolve) => {
|
|
10
|
+
const server = serve({ fetch: app.fetch, port: 0 }, () => {
|
|
11
|
+
resolve({ server, url: `http://localhost:${(server.address() as AddressInfo).port}` });
|
|
12
|
+
});
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export const stopServer = (server: ServerType) =>
|
|
16
|
+
new Promise<void>((resolve, reject) => {
|
|
17
|
+
server.close((error) => (error ? reject(error) : resolve()));
|
|
18
|
+
});
|
package/dist/hono.types.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ClientInstance, Request } from '@hyper-fetch/core';
|
|
2
2
|
import { HonoBase } from 'hono/hono-base';
|
|
3
|
+
import { METHODS } from 'hono/router';
|
|
3
4
|
type Prettify<T> = {
|
|
4
5
|
[K in keyof T]: T[K];
|
|
5
6
|
} & {};
|
|
@@ -18,17 +19,48 @@ type ExtractJson<T> = "json" extends keyof T ? T["json"] : undefined;
|
|
|
18
19
|
type ExtractQuery<T> = "query" extends keyof T ? T["query"] : undefined;
|
|
19
20
|
/** Hono encodes methods as `$get`, `$post`, ... on every path entry of the schema. */
|
|
20
21
|
type ExtractMethodKeys<T> = Extract<keyof T, `$${string}`>;
|
|
22
|
+
type StandardMethodKey = `$${(typeof METHODS)[number]}`;
|
|
21
23
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
+
* Hono stores `.all()` routes under `$all`, and `ALL` is not a method a client can send. Like Hono's
|
|
25
|
+
* own client, the route gets every standard method instead. A method registered on the same path
|
|
26
|
+
* keeps its own handler.
|
|
24
27
|
*/
|
|
25
|
-
type
|
|
26
|
-
[
|
|
27
|
-
|
|
28
|
-
|
|
28
|
+
type ExpandAllMethod<Methods> = "$all" extends keyof Methods ? Omit<Methods, "$all"> & {
|
|
29
|
+
[M in Exclude<StandardMethodKey, keyof Methods>]: Methods["$all"];
|
|
30
|
+
} : Methods;
|
|
31
|
+
/**
|
|
32
|
+
* Turns the `{ $method: endpoint }` entry of a Hono path into Hyper Fetch `Request`s. The endpoint
|
|
33
|
+
* is the one `createSdk` builds from the accessors, so `:param` segments type `setParams()`.
|
|
34
|
+
*/
|
|
35
|
+
type ConvertMethods<Methods, Endpoint extends string, Client extends ClientInstance> = {
|
|
36
|
+
[K in ExtractMethodKeys<Methods> as K extends `$${infer M extends string}` ? `$${Lowercase<M>}` : never]: Request<ExtractOutput<Methods[K]>, ExtractJson<ExtractInput<Methods[K]>>, ExtractQuery<ExtractInput<Methods[K]>>, undefined, Endpoint, Client>;
|
|
29
37
|
};
|
|
30
38
|
type TrimStartSlash<S extends string> = S extends `/${infer R}` ? R : S;
|
|
39
|
+
/** Skips a regex pattern up to its closing brace, counting the braces nested inside it. */
|
|
40
|
+
type SkipPattern<S extends string, Depth extends unknown[] = []> = S extends `${infer Char}${infer Rest}` ? Char extends "}" ? Depth extends [unknown, ...infer Outer] ? SkipPattern<Rest, Outer> : Rest : Char extends "{" ? SkipPattern<Rest, [...Depth, unknown]> : SkipPattern<Rest, Depth> : S;
|
|
41
|
+
/**
|
|
42
|
+
* Hono restricts a param with a regex, as in `/posts/:id{[0-9]+}`. The client fills the param by its
|
|
43
|
+
* name only, so the pattern is dropped from the path, even when it holds a slash or braces.
|
|
44
|
+
*/
|
|
45
|
+
type StripPatterns<S extends string> = S extends `${infer Head}{${infer Rest}` ? `${Head}${StripPatterns<SkipPattern<Rest>>}` : S;
|
|
31
46
|
type SplitPath<S extends string> = S extends "" ? [] : S extends `${infer Head}/${infer Tail}` ? [Head, ...SplitPath<Tail>] : [S];
|
|
47
|
+
type JoinSegments<Segments extends string[]> = Segments extends [infer Head extends string] ? Head : Segments extends [infer Head extends string, ...infer Rest extends string[]] ? `${Head}/${JoinSegments<Rest>}` : "";
|
|
48
|
+
/**
|
|
49
|
+
* `createSdk` joins the accessors with `/` behind a leading slash, so a Hono path without a leading
|
|
50
|
+
* slash, or with a trailing one, gets the endpoint the request is really sent to.
|
|
51
|
+
*/
|
|
52
|
+
type JoinPath<Segments extends string[]> = `/${JoinSegments<Segments>}`;
|
|
53
|
+
type StripOptionalMarkers<Segments extends string[]> = {
|
|
54
|
+
[I in keyof Segments]: Segments[I] extends `:${infer Param}?` ? `:${Param}` : Segments[I];
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Hono serves `/files/:id?` both at `/files` and at `/files/:id`, and a chain of trailing optional
|
|
58
|
+
* params at every prefix. Hyper Fetch params are always required, so each prefix is its own route.
|
|
59
|
+
*/
|
|
60
|
+
type ExpandOptionalParams<Segments extends string[]> = Segments extends [
|
|
61
|
+
...infer Init extends string[],
|
|
62
|
+
`:${infer Param}?`
|
|
63
|
+
] ? ExpandOptionalParams<Init> | [...StripOptionalMarkers<Init>, `:${Param}`] : Segments;
|
|
32
64
|
type CamelCase<S extends string> = S extends `${infer H}-${infer T}` ? `${H}${Capitalize<CamelCase<T>>}` : S;
|
|
33
65
|
/**
|
|
34
66
|
* `:userId` becomes `$userId` and `google-login` becomes `googleLogin`, matching the accessors
|
|
@@ -41,9 +73,11 @@ type BuildNestedObject<Segments extends readonly string[], Value> = Segments ext
|
|
|
41
73
|
] ? {
|
|
42
74
|
[K in NormalizeSegment<Head>]: BuildNestedObject<Rest, Value>;
|
|
43
75
|
} : Value;
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
76
|
+
/** Distributes over the routes one Hono path expands to. */
|
|
77
|
+
type ConvertRoutes<Methods, Routes extends string[], Client extends ClientInstance> = Routes extends string[] ? BuildNestedObject<Routes, Prettify<ConvertMethods<Methods, JoinPath<Routes>, Client>>> : never;
|
|
78
|
+
type ConvertSchema<Schema extends Record<string, any>, Client extends ClientInstance> = UnionToIntersection<{
|
|
79
|
+
[Path in keyof Schema & string]: ConvertRoutes<ExpandAllMethod<Schema[Path]>, ExpandOptionalParams<SplitPath<TrimStartSlash<StripPatterns<Path>>>>, Client>;
|
|
80
|
+
}[keyof Schema & string]>;
|
|
47
81
|
/**
|
|
48
82
|
* Converts the type of a Hono app into a Hyper Fetch SDK schema for `createSdk`.
|
|
49
83
|
*
|
|
@@ -51,6 +85,11 @@ type NestFlatRecord<R extends Record<string, any>> = Prettify<UnionToIntersectio
|
|
|
51
85
|
* from the Hono route definition and its validators. Path segments become nested properties,
|
|
52
86
|
* `:param` segments become `$param` properties, and kebab-case segments become camelCase.
|
|
53
87
|
*
|
|
88
|
+
* Routes below an optional `:param?` segment appear both without and with the param, and regex
|
|
89
|
+
* params like `:id{[0-9]+}` become plain `$id` properties. The endpoint is the one `createSdk`
|
|
90
|
+
* sends the request to, so a trailing slash and the regex patterns of the Hono path are dropped.
|
|
91
|
+
* An `.all()` route gets every standard method, like in Hono's own client.
|
|
92
|
+
*
|
|
54
93
|
* Pass the type of the app returned by your route chain, including apps mounted with
|
|
55
94
|
* `app.route()` and `basePath()`. Anything that is not a Hono app resolves to `{}`.
|
|
56
95
|
*
|
|
@@ -69,6 +108,6 @@ type NestFlatRecord<R extends Record<string, any>> = Prettify<UnionToIntersectio
|
|
|
69
108
|
* const { data } = await sdk.users.$userId.$get.send({ params: { userId: "1" } });
|
|
70
109
|
* ```
|
|
71
110
|
*/
|
|
72
|
-
export type HonoAppToHyperFetch<App, Client extends ClientInstance = ClientInstance> = App extends HonoBase<any, infer S, any, any> ? Prettify<
|
|
111
|
+
export type HonoAppToHyperFetch<App, Client extends ClientInstance = ClientInstance> = App extends HonoBase<any, infer S, any, any> ? Prettify<ConvertSchema<MergeUnionToRecord<S>, Client>> : {};
|
|
73
112
|
export {};
|
|
74
113
|
//# sourceMappingURL=hono.types.d.ts.map
|
package/dist/hono.types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hono.types.d.ts","sourceRoot":"","sources":["../src/hono.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"hono.types.d.ts","sourceRoot":"","sources":["../src/hono.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,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EAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GACtF,KAAK,CAAC;AAEV,KAAK,aAAa,CAAC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,SAAS,cAAc,IAAI,mBAAmB,CACzG;KACG,IAAI,IAAI,MAAM,MAAM,GAAG,MAAM,GAAG,aAAa,CAC5C,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAC7B,oBAAoB,CAAC,SAAS,CAAC,cAAc,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EACpE,MAAM,CACP;CACF,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,CACzB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAM,MAAM,mBAAmB,CAAC,GAAG,EAAE,MAAM,SAAS,cAAc,GAAG,cAAc,IAGjF,GAAG,SAAS,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,QAAQ,CAAC,aAAa,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyper-fetch/hono",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.9.0",
|
|
4
4
|
"description": "Turn a Hono app type into a fully typed Hyper Fetch SDK schema",
|
|
5
5
|
"author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
|
|
6
6
|
"homepage": "https://hyperfetch.bettertyped.com/",
|