@hyper-fetch/hono 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.
package/README.md CHANGED
@@ -1,3 +1,128 @@
1
- # Temporary Holding Version
1
+ # ðŸŊ Hyper Fetch Hono
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>Call your Hono backend from a fully typed HyperFetch SDK. No codegen, no duplicated types.</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" alt="GitHub stars" />
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@hyper-fetch/hono">
12
+ <img src="https://img.shields.io/npm/v/@hyper-fetch/hono?logo=npm&color=e76f51" alt="npm version" />
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/@hyper-fetch/hono">
15
+ <img src="https://img.shields.io/npm/dm/@hyper-fetch/hono?logo=npm" alt="npm downloads" />
16
+ </a>
17
+ <a href="https://bundlephobia.com/package/@hyper-fetch/hono">
18
+ <img src="https://img.shields.io/bundlephobia/minzip/@hyper-fetch/hono?color=64BC4B" alt="bundle size" />
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" alt="license" />
22
+ </a>
23
+ <a href="https://github.com/BetterTyped/hyper-fetch">
24
+ <img src="https://img.shields.io/badge/typescript-%23007ACC.svg?logo=typescript&logoColor=white" alt="TypeScript" />
25
+ </a>
26
+ <a href="https://hono.dev/">
27
+ <img src="https://img.shields.io/badge/hono-E36002?logo=hono&logoColor=white" alt="Hono" />
28
+ </a>
29
+ </p>
30
+
31
+ ## 📖 About
32
+
33
+ `@hyper-fetch/hono` turns the type of a Hono app into a HyperFetch SDK schema. Your frontend calls the backend through
34
+ `createSdk` with response, payload, query and param types read straight from your Hono routes and validators. It ships
35
+ types only, so nothing from your server ends up in the client bundle.
36
+
37
+ ## ðŸŽŊ Key Capabilities
38
+
39
+ - 🔗 **Backend types, frontend calls** - Change a Hono route and every SDK call that uses it fails to compile
40
+ - 🧭 **Paths become properties** - `/users/:userId/posts` is `sdk.users.$userId.posts.$get`, with typed `setParams()`
41
+ - 🛂 **Validators drive the payload** - `json` and `query` validators type `setPayload()` and `setQueryParams()`
42
+ - ðŸ§Đ **Mounted routers included** - `app.route()` and `basePath()` prefixes land in the endpoint and the nesting
43
+ - ðŸŠķ **Zero runtime** - A single type export, so it adds no code to your bundle
44
+ - ⚡ **Every HyperFetch feature** - Cache, retries, deduplication, offline and React hooks work on every route
45
+
46
+ ## 🚀 Quick Start
47
+
48
+ ```bash
49
+ npm install @hyper-fetch/core @hyper-fetch/hono
50
+ ```
51
+
52
+ ```ts
53
+ // backend
54
+ import { Hono } from "hono";
55
+ import type { HonoAppToHyperFetch } from "@hyper-fetch/hono";
56
+
57
+ const app = new Hono().get("/users/:userId", (c) => c.json({ id: c.req.param("userId"), name: "Ann" }));
58
+
59
+ export type AppSchema = HonoAppToHyperFetch<typeof app>;
60
+ ```
61
+
62
+ ```ts
63
+ // frontend
64
+ import { createClient, createSdk } from "@hyper-fetch/core";
65
+ import type { AppSchema } from "@my-app/backend";
66
+
67
+ const client = createClient({ url: "https://api.example.com" });
68
+ const sdk = createSdk<typeof client, AppSchema>(client);
69
+
70
+ const { data } = await sdk.users.$userId.$get.setParams({ userId: "1" }).send();
71
+ ```
72
+
73
+ ## 📚 Documentation
74
+
75
+ - [Hono Integration Docs](https://hyperfetch.bettertyped.com/docs/integrations/hono/overview)
76
+ - [SDK Guide](https://hyperfetch.bettertyped.com/docs/core/sdk)
77
+ - [Getting Started](https://hyperfetch.bettertyped.com/docs/getting-started/quick-start)
78
+
79
+ ## ðŸ’Ą Examples
80
+
81
+ ### Mounted routers with validators
82
+
83
+ ```ts
84
+ import { Hono } from "hono";
85
+ import { validator } from "hono/validator";
86
+ import type { HonoAppToHyperFetch } from "@hyper-fetch/hono";
87
+
88
+ const users = new Hono()
89
+ .get("/", (c) => c.json([{ id: "1", name: "Ann" }]))
90
+ .post(
91
+ "/",
92
+ validator("json", (value: { name: string }) => value),
93
+ (c) => c.json({ id: "2", name: c.req.valid("json").name }, 201),
94
+ );
95
+
96
+ const auth = new Hono().get("/google-login", (c) => c.json({ authUrl: "https://accounts.example.com" }));
97
+
98
+ const app = new Hono().route("/users", users).route("/auth", auth);
99
+
100
+ export type AppSchema = HonoAppToHyperFetch<typeof app>;
101
+ ```
102
+
103
+ ```ts
104
+ const sdk = createSdk<typeof client, AppSchema>(client);
105
+
106
+ await sdk.users.$post.setPayload({ name: "Bob" }).send();
107
+ // kebab-case paths become camelCase properties: GET /auth/google-login
108
+ await sdk.auth.googleLogin.$get.send();
109
+ ```
110
+
111
+ ### React hooks on a Hono route
112
+
113
+ ```tsx
114
+ import { useFetch } from "@hyper-fetch/react";
115
+
116
+ import { sdk } from "./api";
117
+
118
+ export const UserName = ({ userId }: { userId: string }) => {
119
+ const { data, loading } = useFetch(sdk.users.$userId.$get.setParams({ userId }));
120
+
121
+ if (loading) return <p>Loading...</p>;
122
+ return <p>{data?.name}</p>;
123
+ };
124
+ ```
125
+
126
+ ## License
127
+
128
+ [Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
@@ -0,0 +1,112 @@
1
+ import { serve } from "@hono/node-server";
2
+ import type { ServerType } from "@hono/node-server";
3
+ import { createClient, createSdk } from "@hyper-fetch/core";
4
+ import type { AddressInfo } from "node:net";
5
+
6
+ import type { HonoAppToHyperFetch } from "../../../src";
7
+ import { app } from "../../utils/app";
8
+
9
+ type Schema = HonoAppToHyperFetch<typeof app>;
10
+
11
+ const startServer = () =>
12
+ new Promise<ServerType>((resolve) => {
13
+ const server = serve({ fetch: app.fetch, port: 0 }, () => resolve(server));
14
+ });
15
+
16
+ const stopServer = (server: ServerType) =>
17
+ new Promise<void>((resolve, reject) => {
18
+ server.close((error) => (error ? reject(error) : resolve()));
19
+ });
20
+
21
+ describe("HonoAppToHyperFetch [ Requests against a Hono server ]", () => {
22
+ let server: ServerType;
23
+ let url: string;
24
+
25
+ const createAppSdk = () => {
26
+ const client = createClient({ url });
27
+ return createSdk<typeof client, Schema>(client);
28
+ };
29
+
30
+ beforeAll(async () => {
31
+ server = await startServer();
32
+ url = `http://localhost:${(server.address() as AddressInfo).port}`;
33
+ });
34
+
35
+ afterAll(async () => {
36
+ await stopServer(server);
37
+ });
38
+
39
+ it("should send a GET to a mounted route", async () => {
40
+ const sdk = createAppSdk();
41
+
42
+ const { data, error, status } = await sdk.users.$get.send();
43
+
44
+ expect(status).toBe(200);
45
+ expect(error).toBeNull();
46
+ expect(data).toStrictEqual([{ id: "1", name: "Ann" }]);
47
+ });
48
+
49
+ it("should send to the root route", async () => {
50
+ const sdk = createAppSdk();
51
+
52
+ const { data } = await sdk.$get.send();
53
+
54
+ expect(data).toStrictEqual({ ok: true });
55
+ });
56
+
57
+ it("should fill :param segments from setParams", async () => {
58
+ const sdk = createAppSdk();
59
+
60
+ const { data } = await sdk.users.$userId.$get.setParams({ userId: "42" }).send();
61
+
62
+ expect(data).toStrictEqual({ id: "42", name: "Ann" });
63
+ });
64
+
65
+ it("should send the payload as the JSON body the validator reads", async () => {
66
+ const sdk = createAppSdk();
67
+
68
+ const { data, status } = await sdk.users.$post.setPayload({ name: "Bob" }).send();
69
+
70
+ expect(status).toBe(201);
71
+ expect(data).toStrictEqual({ id: "2", name: "Bob" });
72
+ });
73
+
74
+ it("should send query params the validator reads", async () => {
75
+ const sdk = createAppSdk();
76
+
77
+ const { data } = await sdk.users.$userId.posts.$get.setParams({ userId: "7" }).setQueryParams({ page: "3" }).send();
78
+
79
+ expect(data).toStrictEqual({ userId: "7", page: "3" });
80
+ });
81
+
82
+ it("should resolve camelCase accessors to the kebab-case Hono path", async () => {
83
+ const sdk = createAppSdk();
84
+ const request = sdk.auth.googleLogin.$get;
85
+
86
+ const { data } = await request.send();
87
+
88
+ expect(request.endpoint).toBe("/auth/google-login");
89
+ expect(data).toStrictEqual({ authUrl: "https://accounts.example.com" });
90
+ });
91
+
92
+ it("should send the HTTP method named by the key", async () => {
93
+ const sdk = createAppSdk();
94
+ const request = sdk.auth.session.$delete;
95
+
96
+ const { data } = await request.send();
97
+
98
+ expect(request.method).toBe("DELETE");
99
+ expect(data).toStrictEqual({ loggedOut: true });
100
+ });
101
+
102
+ it("should resolve an error status through the response", async () => {
103
+ const sdk = createAppSdk();
104
+
105
+ const { data, error, status, success } = await sdk.users.$userId.$get.setParams({ userId: "missing" }).send();
106
+
107
+ expect(success).toBe(false);
108
+ expect(status).toBe(404);
109
+ expect(data).toBeNull();
110
+ expect(error).toStrictEqual({ message: "User not found" });
111
+ });
112
+ });
@@ -0,0 +1,163 @@
1
+ import { createClient, createSdk } from "@hyper-fetch/core";
2
+ import type {
3
+ Client,
4
+ ClientInstance,
5
+ ExtractClientType,
6
+ ExtractEndpointType,
7
+ ExtractGlobalErrorType,
8
+ ExtractLocalErrorType,
9
+ ExtractPayloadType,
10
+ ExtractQueryParamsType,
11
+ ExtractResponseType,
12
+ HttpAdapterType,
13
+ } from "@hyper-fetch/core";
14
+ import { Hono } from "hono";
15
+ import { expectTypeOf } from "vitest";
16
+
17
+ import type { HonoAppToHyperFetch } from "../../../src";
18
+ import type { User, apiApp, app } from "../../utils/app";
19
+
20
+ type Schema = HonoAppToHyperFetch<typeof app>;
21
+
22
+ describe("HonoAppToHyperFetch [ Schema shape ]", () => {
23
+ it("should nest mounted routes under their path segments", () => {
24
+ expectTypeOf<keyof Schema>().toEqualTypeOf<"$get" | "users" | "auth">();
25
+ expectTypeOf<keyof Schema["users"]>().toEqualTypeOf<"$get" | "$post" | "$userId">();
26
+ expectTypeOf<keyof Schema["users"]["$userId"]>().toEqualTypeOf<"$get" | "posts">();
27
+ expectTypeOf<keyof Schema["auth"]>().toEqualTypeOf<"googleLogin" | "session">();
28
+ expect(true).toBe(true);
29
+ });
30
+
31
+ it("should turn :param segments into $param keys and keep the Hono path as the endpoint", () => {
32
+ expectTypeOf<ExtractEndpointType<Schema["users"]["$userId"]["$get"]>>().toEqualTypeOf<"/users/:userId">();
33
+ expectTypeOf<
34
+ ExtractEndpointType<Schema["users"]["$userId"]["posts"]["$get"]>
35
+ >().toEqualTypeOf<"/users/:userId/posts">();
36
+ expect(true).toBe(true);
37
+ });
38
+
39
+ it("should camelCase kebab-case segments and keep the kebab-case endpoint", () => {
40
+ expectTypeOf<ExtractEndpointType<Schema["auth"]["googleLogin"]["$get"]>>().toEqualTypeOf<"/auth/google-login">();
41
+ expect(true).toBe(true);
42
+ });
43
+
44
+ it("should put a route registered on / at the top level", () => {
45
+ expectTypeOf<ExtractEndpointType<Schema["$get"]>>().toEqualTypeOf<"/">();
46
+ expectTypeOf<ExtractResponseType<Schema["$get"]>>().toEqualTypeOf<{ ok: true }>();
47
+ expect(true).toBe(true);
48
+ });
49
+
50
+ it("should prefix endpoints with the app basePath", () => {
51
+ type ApiSchema = HonoAppToHyperFetch<typeof apiApp>;
52
+
53
+ expectTypeOf<keyof ApiSchema>().toEqualTypeOf<"api">();
54
+ expectTypeOf<ExtractEndpointType<ApiSchema["api"]["users"]["$get"]>>().toEqualTypeOf<"/api/users">();
55
+ expect(true).toBe(true);
56
+ });
57
+
58
+ it("should lowercase the method keys", () => {
59
+ const methods = new Hono().on("PATCH", "/users", (c) => c.json({ patched: true }));
60
+ type MethodsSchema = HonoAppToHyperFetch<typeof methods>;
61
+
62
+ expectTypeOf<keyof MethodsSchema["users"]>().toEqualTypeOf<"$patch">();
63
+ expect(true).toBe(true);
64
+ });
65
+
66
+ it("should resolve to an empty schema for anything that is not a Hono app", () => {
67
+ expectTypeOf<HonoAppToHyperFetch<{ routes: [] }>>().toEqualTypeOf<{}>();
68
+ expectTypeOf<HonoAppToHyperFetch<new () => Hono>>().toEqualTypeOf<{}>();
69
+ expect(true).toBe(true);
70
+ });
71
+
72
+ it("should reject routes the app does not define", () => {
73
+ // @ts-expect-error - no DELETE handler on /users
74
+ type MissingMethod = Schema["users"]["$delete"];
75
+ // @ts-expect-error - no /posts router is mounted
76
+ type MissingRoute = Schema["posts"];
77
+
78
+ expectTypeOf<MissingMethod>().toBeAny();
79
+ expectTypeOf<MissingRoute>().toBeAny();
80
+ expect(true).toBe(true);
81
+ });
82
+ });
83
+
84
+ describe("HonoAppToHyperFetch [ Request types ]", () => {
85
+ it("should take the response from the handler output", () => {
86
+ expectTypeOf<ExtractResponseType<Schema["users"]["$get"]>>().toEqualTypeOf<User[]>();
87
+ expectTypeOf<ExtractResponseType<Schema["auth"]["session"]["$delete"]>>().toEqualTypeOf<{ loggedOut: true }>();
88
+ expect(true).toBe(true);
89
+ });
90
+
91
+ it("should union the outputs of every status a handler returns", () => {
92
+ expectTypeOf<ExtractResponseType<Schema["users"]["$userId"]["$get"]>>().toEqualTypeOf<User | { message: string }>();
93
+ expect(true).toBe(true);
94
+ });
95
+
96
+ it("should take the payload from the json validator", () => {
97
+ expectTypeOf<ExtractPayloadType<Schema["users"]["$post"]>>().toEqualTypeOf<{ name: string }>();
98
+ expectTypeOf<ExtractPayloadType<Schema["users"]["$get"]>>().toEqualTypeOf<undefined>();
99
+ expect(true).toBe(true);
100
+ });
101
+
102
+ it("should take the query params from the query validator", () => {
103
+ expectTypeOf<ExtractQueryParamsType<Schema["users"]["$userId"]["posts"]["$get"]>>().toEqualTypeOf<{
104
+ page: string | string[];
105
+ }>();
106
+ expectTypeOf<ExtractQueryParamsType<Schema["users"]["$get"]>>().toEqualTypeOf<undefined>();
107
+ expect(true).toBe(true);
108
+ });
109
+
110
+ it("should leave the local error undefined", () => {
111
+ expectTypeOf<ExtractLocalErrorType<Schema["users"]["$get"]>>().toEqualTypeOf<undefined>();
112
+ expect(true).toBe(true);
113
+ });
114
+
115
+ it("should default the client to ClientInstance and accept a custom one", () => {
116
+ type AppClient = Client<{ code: string }, HttpAdapterType>;
117
+ type TypedSchema = HonoAppToHyperFetch<typeof app, AppClient>;
118
+
119
+ expectTypeOf<ExtractClientType<Schema["users"]["$get"]>>().toEqualTypeOf<ClientInstance>();
120
+ expectTypeOf<ExtractClientType<TypedSchema["users"]["$get"]>>().toEqualTypeOf<AppClient>();
121
+ expect(true).toBe(true);
122
+ });
123
+ });
124
+
125
+ describe("HonoAppToHyperFetch [ createSdk ]", () => {
126
+ const client = createClient({ url: "http://localhost" });
127
+ const sdk = createSdk<typeof client, Schema>(client);
128
+
129
+ it("should inject the SDK client into every request", () => {
130
+ expectTypeOf<ExtractClientType<typeof sdk.users.$get>>().toEqualTypeOf<typeof client>();
131
+ expect(true).toBe(true);
132
+ });
133
+
134
+ it("should apply the client's global error to every route", () => {
135
+ type ApiError = { message: string; code: string };
136
+ const errorClient = createClient<{ error: ApiError }>({ url: "http://localhost" });
137
+ const errorSdk = createSdk<typeof errorClient, Schema>(errorClient);
138
+
139
+ expectTypeOf<ExtractGlobalErrorType<typeof errorSdk.users.$get>>().toEqualTypeOf<ApiError>();
140
+ expect(true).toBe(true);
141
+ });
142
+
143
+ it("should type params from the Hono path", () => {
144
+ sdk.users.$userId.$get.setParams({ userId: "1" });
145
+ // @ts-expect-error - the Hono path names the param userId
146
+ sdk.users.$userId.$get.setParams({ id: "1" });
147
+ expect(true).toBe(true);
148
+ });
149
+
150
+ it("should type the payload from the json validator", () => {
151
+ sdk.users.$post.setPayload({ name: "Ann" });
152
+ // @ts-expect-error - the validator requires a string name
153
+ sdk.users.$post.setPayload({ name: 1 });
154
+ expect(true).toBe(true);
155
+ });
156
+
157
+ it("should type the query params from the query validator", () => {
158
+ sdk.users.$userId.posts.$get.setQueryParams({ page: "2" });
159
+ // @ts-expect-error - the validator reads page, not limit
160
+ sdk.users.$userId.posts.$get.setQueryParams({ limit: "2" });
161
+ expect(true).toBe(true);
162
+ });
163
+ });
@@ -0,0 +1,11 @@
1
+ {
2
+ "extends": "../tsconfig.json",
3
+ "compilerOptions": {
4
+ "noEmit": true,
5
+ "noUnusedLocals": false,
6
+ "noUnusedParameters": false,
7
+ "types": ["vitest/globals", "@types/node"]
8
+ },
9
+ "include": ["**/*.ts", "**/*.tsx", "../../../global.d.ts", "../../../vitest.d.ts"],
10
+ "exclude": ["node_modules"]
11
+ }
@@ -0,0 +1,42 @@
1
+ import { Hono } from "hono";
2
+ import { validator } from "hono/validator";
3
+
4
+ export type User = { id: string; name: string };
5
+
6
+ const parseNewUser = (value: unknown): { name: string } => {
7
+ if (typeof value === "object" && value !== null && "name" in value && typeof value.name === "string") {
8
+ return { name: value.name };
9
+ }
10
+ throw new Error("Invalid user");
11
+ };
12
+
13
+ const parsePostsQuery = (value: Record<string, string | string[]>): { page: string } => {
14
+ const { page } = value;
15
+ return { page: typeof page === "string" ? page : "1" };
16
+ };
17
+
18
+ const users = new Hono()
19
+ .get("/", (c) => c.json<User[]>([{ id: "1", name: "Ann" }]))
20
+ .post("/", validator("json", parseNewUser), (c) => c.json<User>({ id: "2", name: c.req.valid("json").name }, 201))
21
+ .get("/:userId", (c) => {
22
+ const userId = c.req.param("userId");
23
+ if (userId === "missing") {
24
+ return c.json({ message: "User not found" }, 404);
25
+ }
26
+ return c.json<User>({ id: userId, name: "Ann" });
27
+ })
28
+ .get("/:userId/posts", validator("query", parsePostsQuery), (c) =>
29
+ c.json({ userId: c.req.param("userId"), page: c.req.valid("query").page }),
30
+ );
31
+
32
+ const auth = new Hono()
33
+ .get("/google-login", (c) => c.json({ authUrl: "https://accounts.example.com" }))
34
+ .delete("/session", (c) => c.json({ loggedOut: true }));
35
+
36
+ /** A Hono app with mounted routers, params, kebab-case paths, a JSON validator and a query validator. */
37
+ export const app = new Hono()
38
+ .get("/", (c) => c.json({ ok: true }))
39
+ .route("/users", users)
40
+ .route("/auth", auth);
41
+
42
+ export const apiApp = new Hono().basePath("/api").route("/users", users);
@@ -0,0 +1,74 @@
1
+ import { ClientInstance, Request } from '@hyper-fetch/core';
2
+ import { HonoBase } from 'hono/hono-base';
3
+ type Prettify<T> = {
4
+ [K in keyof T]: T[K];
5
+ } & {};
6
+ type UnionToIntersection<U> = (U extends any ? (arg: U) => void : never) extends (arg: infer I) => void ? I : never;
7
+ /**
8
+ * `app.route()` returns a union of schemas. Merge it into one record keyed by path so that two
9
+ * routers registering methods on the same path end up on the same entry.
10
+ */
11
+ type UnionKeys<U> = U extends any ? keyof U : never;
12
+ type MergeUnionToRecord<U> = {
13
+ [K in UnionKeys<U> & string]: UnionToIntersection<U extends any ? (K extends keyof U ? U[K] : never) : never>;
14
+ };
15
+ type ExtractInput<T> = "input" extends keyof T ? T["input"] : undefined;
16
+ type ExtractOutput<T> = "output" extends keyof T ? T["output"] : undefined;
17
+ type ExtractJson<T> = "json" extends keyof T ? T["json"] : undefined;
18
+ type ExtractQuery<T> = "query" extends keyof T ? T["query"] : undefined;
19
+ /** Hono encodes methods as `$get`, `$post`, ... on every path entry of the schema. */
20
+ type ExtractMethodKeys<T> = Extract<keyof T, `$${string}`>;
21
+ /**
22
+ * Turns every `path -> { $method: endpoint }` entry of a Hono schema into a Hyper Fetch `Request`.
23
+ * The full Hono path is kept as the endpoint, so `:param` segments type `setParams()`.
24
+ */
25
+ type ConvertToRequest<Schema extends Record<string, any>, Client extends ClientInstance> = {
26
+ [Path in keyof Schema]: {
27
+ [K in ExtractMethodKeys<Schema[Path]> as K extends `$${infer M extends string}` ? `$${Lowercase<M>}` : never]: Request<ExtractOutput<Schema[Path][K]>, ExtractJson<ExtractInput<Schema[Path][K]>>, ExtractQuery<ExtractInput<Schema[Path][K]>>, undefined, Path extends string ? Path : never, Client>;
28
+ };
29
+ };
30
+ type TrimStartSlash<S extends string> = S extends `/${infer R}` ? R : S;
31
+ type SplitPath<S extends string> = S extends "" ? [] : S extends `${infer Head}/${infer Tail}` ? [Head, ...SplitPath<Tail>] : [S];
32
+ type CamelCase<S extends string> = S extends `${infer H}-${infer T}` ? `${H}${Capitalize<CamelCase<T>>}` : S;
33
+ /**
34
+ * `:userId` becomes `$userId` and `google-login` becomes `googleLogin`, matching the accessors
35
+ * `createSdk` resolves back to the endpoint at runtime.
36
+ */
37
+ type NormalizeSegment<S extends string> = S extends `:${infer P}` ? `$${P}` : CamelCase<S>;
38
+ type BuildNestedObject<Segments extends readonly string[], Value> = Segments extends [
39
+ infer Head extends string,
40
+ ...infer Rest extends string[]
41
+ ] ? {
42
+ [K in NormalizeSegment<Head>]: BuildNestedObject<Rest, Value>;
43
+ } : Value;
44
+ type NestFlatRecord<R extends Record<string, any>> = Prettify<UnionToIntersection<{
45
+ [P in keyof R & string]: BuildNestedObject<SplitPath<TrimStartSlash<P>>, R[P]>;
46
+ }[keyof R & string]>>;
47
+ /**
48
+ * Converts the type of a Hono app into a Hyper Fetch SDK schema for `createSdk`.
49
+ *
50
+ * Every route becomes a `Request` whose response, JSON payload, query params and endpoint come
51
+ * from the Hono route definition and its validators. Path segments become nested properties,
52
+ * `:param` segments become `$param` properties, and kebab-case segments become camelCase.
53
+ *
54
+ * Pass the type of the app returned by your route chain, including apps mounted with
55
+ * `app.route()` and `basePath()`. Anything that is not a Hono app resolves to `{}`.
56
+ *
57
+ * @typeParam App - The Hono app type, usually `typeof app`.
58
+ * @typeParam Client - The client the requests belong to. `createSdk` injects its own client, so
59
+ * this is only needed when the schema is used outside of `createSdk`.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * // backend
64
+ * const app = new Hono().get("/users/:userId", (c) => c.json({ id: c.req.param("userId") }));
65
+ * export type AppSchema = HonoAppToHyperFetch<typeof app>;
66
+ *
67
+ * // frontend
68
+ * const sdk = createSdk<typeof client, AppSchema>(client);
69
+ * const { data } = await sdk.users.$userId.$get.send({ params: { userId: "1" } });
70
+ * ```
71
+ */
72
+ export type HonoAppToHyperFetch<App, Client extends ClientInstance = ClientInstance> = App extends HonoBase<any, infer S, any, any> ? Prettify<NestFlatRecord<ConvertToRequest<MergeUnionToRecord<S>, Client>>> : {};
73
+ export {};
74
+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C,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GACzE,EAAE,CAAC"}
@@ -0,0 +1,2 @@
1
+ export type { HonoAppToHyperFetch } from './hono.types';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.mjs ADDED
File without changes
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@hyper-fetch/hono",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "9.8.0",
4
+ "description": "Turn a Hono app type into a fully typed Hyper Fetch SDK schema",
5
+ "author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
6
+ "homepage": "https://hyperfetch.bettertyped.com/",
7
+ "license": "Apache-2.0",
8
+ "main": "dist/index.mjs",
9
+ "module": "dist/index.mjs",
10
+ "types": "dist/index.d.ts",
11
+ "source": "src/index.ts",
12
+ "sideEffects": false,
13
+ "exports": {
14
+ ".": {
15
+ "types": {
16
+ "import": "./dist/index.d.ts"
17
+ },
18
+ "default": {
19
+ "require": "./dist/index.mjs",
20
+ "import": "./dist/index.mjs"
21
+ }
22
+ }
23
+ },
24
+ "scripts": {
25
+ "test": "vitest run",
26
+ "start": "pnpm build && npx run-when-changed --watch 'src/**/*.ts' --exec 'pnpm build'",
27
+ "build": "vite build",
28
+ "lint": "oxlint .",
29
+ "format": "oxfmt --write .",
30
+ "typecheck": "tsgo --noEmit --emitDeclarationOnly false && tsgo --noEmit -p __tests__/tsconfig.json",
31
+ "tests": "pnpm lint-staged"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public",
35
+ "registry": "https://registry.npmjs.org/"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/BetterTyped/hyper-fetch.git",
40
+ "directory": "packages/hono"
41
+ },
42
+ "bugs": {
43
+ "url": "https://github.com/BetterTyped/hyper-fetch/issues"
44
+ },
45
+ "peerDependencies": {
46
+ "@hyper-fetch/core": "*",
47
+ "hono": ">=4"
48
+ },
49
+ "lint-staged": {
50
+ "*.{js,jsx,ts,tsx}": [
51
+ "vitest related --run --passWithNoTests"
52
+ ]
53
+ },
54
+ "keywords": [
55
+ "hono",
56
+ "sdk",
57
+ "rpc",
58
+ "type-safe",
59
+ "hyper fetch"
60
+ ],
61
+ "devDependencies": {
62
+ "@hono/node-server": "^2.1.9",
63
+ "hono": "^4.13.19"
64
+ }
65
+ }
package/project.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "name": "hono",
3
+ "$schema": "../../node_modules/nx/schemas/project-schema.json"
4
+ }
@@ -0,0 +1,116 @@
1
+ import type { ClientInstance, Request } from "@hyper-fetch/core";
2
+ import type { HonoBase } from "hono/hono-base";
3
+
4
+ type Prettify<T> = {
5
+ [K in keyof T]: T[K];
6
+ } & {};
7
+
8
+ type UnionToIntersection<U> = (U extends any ? (arg: U) => void : never) extends (arg: infer I) => void ? I : never;
9
+
10
+ /* -------------------------------------------------------------------------------------------------
11
+ * Hono schema -> flat record of requests
12
+ * -----------------------------------------------------------------------------------------------*/
13
+
14
+ /**
15
+ * `app.route()` returns a union of schemas. Merge it into one record keyed by path so that two
16
+ * routers registering methods on the same path end up on the same entry.
17
+ */
18
+ type UnionKeys<U> = U extends any ? keyof U : never;
19
+
20
+ type MergeUnionToRecord<U> = {
21
+ [K in UnionKeys<U> & string]: UnionToIntersection<U extends any ? (K extends keyof U ? U[K] : never) : never>;
22
+ };
23
+
24
+ type ExtractInput<T> = "input" extends keyof T ? T["input"] : undefined;
25
+ type ExtractOutput<T> = "output" extends keyof T ? T["output"] : undefined;
26
+ type ExtractJson<T> = "json" extends keyof T ? T["json"] : undefined;
27
+ type ExtractQuery<T> = "query" extends keyof T ? T["query"] : undefined;
28
+
29
+ /** Hono encodes methods as `$get`, `$post`, ... on every path entry of the schema. */
30
+ type ExtractMethodKeys<T> = Extract<keyof T, `$${string}`>;
31
+
32
+ /**
33
+ * Turns every `path -> { $method: endpoint }` entry of a Hono schema into a Hyper Fetch `Request`.
34
+ * The full Hono path is kept as the endpoint, so `:param` segments type `setParams()`.
35
+ */
36
+ type ConvertToRequest<Schema extends Record<string, any>, Client extends ClientInstance> = {
37
+ [Path in keyof Schema]: {
38
+ [K in ExtractMethodKeys<Schema[Path]> as K extends `$${infer M extends string}`
39
+ ? `$${Lowercase<M>}`
40
+ : never]: Request<
41
+ ExtractOutput<Schema[Path][K]>,
42
+ ExtractJson<ExtractInput<Schema[Path][K]>>,
43
+ ExtractQuery<ExtractInput<Schema[Path][K]>>,
44
+ undefined,
45
+ Path extends string ? Path : never,
46
+ Client
47
+ >;
48
+ };
49
+ };
50
+
51
+ /* -------------------------------------------------------------------------------------------------
52
+ * Flat record -> nested SDK schema
53
+ * -----------------------------------------------------------------------------------------------*/
54
+
55
+ type TrimStartSlash<S extends string> = S extends `/${infer R}` ? R : S;
56
+
57
+ type SplitPath<S extends string> = S extends ""
58
+ ? []
59
+ : S extends `${infer Head}/${infer Tail}`
60
+ ? [Head, ...SplitPath<Tail>]
61
+ : [S];
62
+
63
+ type CamelCase<S extends string> = S extends `${infer H}-${infer T}` ? `${H}${Capitalize<CamelCase<T>>}` : S;
64
+
65
+ /**
66
+ * `:userId` becomes `$userId` and `google-login` becomes `googleLogin`, matching the accessors
67
+ * `createSdk` resolves back to the endpoint at runtime.
68
+ */
69
+ type NormalizeSegment<S extends string> = S extends `:${infer P}` ? `$${P}` : CamelCase<S>;
70
+
71
+ type BuildNestedObject<Segments extends readonly string[], Value> = Segments extends [
72
+ infer Head extends string,
73
+ ...infer Rest extends string[],
74
+ ]
75
+ ? { [K in NormalizeSegment<Head>]: BuildNestedObject<Rest, Value> }
76
+ : Value;
77
+
78
+ type NestFlatRecord<R extends Record<string, any>> = Prettify<
79
+ UnionToIntersection<
80
+ {
81
+ [P in keyof R & string]: BuildNestedObject<SplitPath<TrimStartSlash<P>>, R[P]>;
82
+ }[keyof R & string]
83
+ >
84
+ >;
85
+
86
+ /**
87
+ * Converts the type of a Hono app into a Hyper Fetch SDK schema for `createSdk`.
88
+ *
89
+ * Every route becomes a `Request` whose response, JSON payload, query params and endpoint come
90
+ * from the Hono route definition and its validators. Path segments become nested properties,
91
+ * `:param` segments become `$param` properties, and kebab-case segments become camelCase.
92
+ *
93
+ * Pass the type of the app returned by your route chain, including apps mounted with
94
+ * `app.route()` and `basePath()`. Anything that is not a Hono app resolves to `{}`.
95
+ *
96
+ * @typeParam App - The Hono app type, usually `typeof app`.
97
+ * @typeParam Client - The client the requests belong to. `createSdk` injects its own client, so
98
+ * this is only needed when the schema is used outside of `createSdk`.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * // backend
103
+ * const app = new Hono().get("/users/:userId", (c) => c.json({ id: c.req.param("userId") }));
104
+ * export type AppSchema = HonoAppToHyperFetch<typeof app>;
105
+ *
106
+ * // frontend
107
+ * const sdk = createSdk<typeof client, AppSchema>(client);
108
+ * const { data } = await sdk.users.$userId.$get.send({ params: { userId: "1" } });
109
+ * ```
110
+ */
111
+ export type HonoAppToHyperFetch<App, Client extends ClientInstance = ClientInstance> =
112
+ // Match `HonoBase` with all four generics: `.route()` returns `HonoBase<E, S, BasePath, CurrentPath>`,
113
+ // so matching against `Hono<E, S, BasePath>` fails to infer the schema and resolves to `{}`.
114
+ App extends HonoBase<any, infer S, any, any>
115
+ ? Prettify<NestFlatRecord<ConvertToRequest<MergeUnionToRecord<S>, Client>>>
116
+ : {};
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export type { HonoAppToHyperFetch } from "./hono.types";
package/tsconfig.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "rootDir": "."
5
+ },
6
+ "exclude": ["node_modules", "dist", "vite.config.ts", "__tests__"]
7
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,31 @@
1
+ /// <reference types="vitest/config" />
2
+ import path from "path";
3
+ import { defineConfig } from "vite";
4
+ import dts from "vite-plugin-dts";
5
+ import tsconfigPaths from "vite-tsconfig-paths";
6
+
7
+ import { getRollupExternalsFromPackageJson } from "../../scripts/vite-lib-externals-from-package";
8
+
9
+ export default defineConfig({
10
+ build: {
11
+ lib: {
12
+ entry: "src/index.ts",
13
+ fileName: "index",
14
+ formats: ["es"],
15
+ },
16
+ minify: false,
17
+ rollupOptions: {
18
+ external: getRollupExternalsFromPackageJson(__dirname),
19
+ },
20
+ sourcemap: true,
21
+ },
22
+ plugins: [tsconfigPaths(), dts({ entryRoot: "src" })],
23
+ test: {
24
+ alias: {
25
+ "@hyper-fetch/core": path.resolve(__dirname, "../core/src/index.ts"),
26
+ },
27
+ environment: "node",
28
+ globals: true,
29
+ include: ["__tests__/**/*.spec.{ts,tsx}", "src/**/*.spec.{ts,tsx}"],
30
+ },
31
+ });