@ts-kizuna/hono 1.49.5

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/LICENSE.MD ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sondre Ørland
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # @ts-kizuna/hono
2
+
3
+ `@ts-kizuna/hono` connects a ts-kizuna API to a Hono application. Hono runs on Cloudflare Workers, Deno, Bun, Node.js, and other runtimes.
4
+
5
+ **Requires Hono >= 4.**
6
+
7
+ ## Installation
8
+
9
+ ```sh
10
+ pnpm add @ts-kizuna/hono hono
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { Hono } from 'hono';
17
+ import { KizunaServer } from '@ts-kizuna/hono';
18
+ import { contract } from './contract';
19
+ import { router } from './router';
20
+
21
+ const server = new KizunaServer(contract);
22
+
23
+ const api = server.api({
24
+ router,
25
+ });
26
+
27
+ const app = new Hono();
28
+ api.mount(app);
29
+
30
+ export default app;
31
+ ```
32
+
33
+ ## Documentation
34
+
35
+ [Hono adapter](https://ts-kizuna.com/docs/adapters/hono)
package/dist/index.cjs ADDED
@@ -0,0 +1,121 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _ts_kizuna_core_adapter = require("@ts-kizuna/core/adapter");
3
+ //#region src/server.ts
4
+ const honoAdapter = (0, _ts_kizuna_core_adapter.createAdapter)({
5
+ buildHandlerContext: (_adapterRequest, { c }) => ({ c }),
6
+ respond: (result, { c, formatError }) => {
7
+ if (result.kind === "handler-error") throw result.error;
8
+ if (result.kind === "raw-response") return result.response;
9
+ const rendered = (0, _ts_kizuna_core_adapter.renderJsonResult)(result, formatError, c.req.raw);
10
+ if (rendered.body === void 0) return c.body(null, rendered.status, rendered.headers);
11
+ if (rendered.raw) return c.body(rendered.body, rendered.status, rendered.headers);
12
+ return c.json(rendered.body, rendered.status, rendered.headers);
13
+ }
14
+ });
15
+ /**
16
+ * Mount a ts-kizuna API onto a Hono app.
17
+ *
18
+ * @example
19
+ * const app = new Hono();
20
+ * api.mount(app);
21
+ */
22
+ function mountHono(api, app, options) {
23
+ const guards = api[_ts_kizuna_core_adapter.GUARDS_META];
24
+ const schemes = api[_ts_kizuna_core_adapter.SCHEMES_META];
25
+ const requestContext = api[_ts_kizuna_core_adapter.REQUEST_CONTEXT_META];
26
+ const pluginExports = (0, _ts_kizuna_core_adapter.pluginExportsOf)(api);
27
+ const jobsMeta = api[_ts_kizuna_core_adapter.JOBS_META];
28
+ const jobRunner = (0, _ts_kizuna_core_adapter.jobRunnerFrom)(jobsMeta);
29
+ const mountRoute = (routeKey, route, lane, resolvedRouter) => {
30
+ const method = route.method.toLowerCase();
31
+ const kizunaHandler = async (c) => {
32
+ const url = new URL(c.req.url);
33
+ const adapterRequest = {
34
+ request: c.req.raw,
35
+ method: c.req.method,
36
+ resolution: {
37
+ kind: "pre-resolved",
38
+ routeKey,
39
+ route,
40
+ params: c.req.param()
41
+ },
42
+ query: Object.fromEntries(url.searchParams),
43
+ headers: (0, _ts_kizuna_core_adapter.headersToObject)(c.req.raw.headers),
44
+ readBody: (r) => (0, _ts_kizuna_core_adapter.parseFetchBody)(c.req.raw, r)
45
+ };
46
+ return honoAdapter.handle({
47
+ routes: lane,
48
+ router: resolvedRouter,
49
+ request: adapterRequest,
50
+ responseContext: {
51
+ c,
52
+ formatError: options?.formatError
53
+ },
54
+ guards,
55
+ schemes,
56
+ requestContext,
57
+ pluginExports,
58
+ jobs: jobRunner,
59
+ responseValidation: options?.responseValidation
60
+ });
61
+ };
62
+ app.on(method, route.path, kizunaHandler);
63
+ };
64
+ const mountLane = (lane, resolvedRouter) => {
65
+ for (const { routeKey, route } of honoAdapter.eachRoute(lane, resolvedRouter)) mountRoute(routeKey, route, lane, resolvedRouter);
66
+ };
67
+ mountLane(api.routes, api[_ts_kizuna_core_adapter.ROUTER_META]);
68
+ mountLane((0, _ts_kizuna_core_adapter.pluginRoutesOf)(api), (0, _ts_kizuna_core_adapter.pluginRouterOf)(api));
69
+ if (jobsMeta) {
70
+ const routes = (0, _ts_kizuna_core_adapter.jobRoutes)(jobsMeta);
71
+ const router = (0, _ts_kizuna_core_adapter.jobRouter)(jobsMeta);
72
+ for (const [routeKey, route] of Object.entries(routes)) mountRoute(routeKey, route, routes, router);
73
+ }
74
+ }
75
+ const createServerSurface = (contract, options) => {
76
+ (0, _ts_kizuna_core_adapter.warnUnsupportedJobOptions)(contract.jobs, options?.jobTransport);
77
+ return {
78
+ guard: (_name, run) => run,
79
+ requestContext: (_name, run) => run,
80
+ router: (groupOrRouter, groupRouter) => groupRouter ?? groupOrRouter,
81
+ jobs: (handlers) => handlers,
82
+ api: ({ jobs, ...parts }) => {
83
+ const api = Object.assign((0, _ts_kizuna_core_adapter.assembleApi)(contract, parts), { [_ts_kizuna_core_adapter.JOBS_META]: contract.jobs ? {
84
+ jobs: contract.jobs,
85
+ handlers: jobs ?? {},
86
+ config: contract.jobsConfig,
87
+ transport: options?.jobTransport,
88
+ onError: options?.onJobError
89
+ } : void 0 });
90
+ return Object.assign(api, { mount: (app, mountOptions) => mountHono(api, app, mountOptions) });
91
+ }
92
+ };
93
+ };
94
+ /**
95
+ * Turn a contract into a server handle: the serving counterpart to `Kizuna`.
96
+ * Keep the instance and use `server.guard` to define guards, `server.router`
97
+ * to write typed handlers, and `server.api` to assemble them.
98
+ *
99
+ * @example
100
+ * const server = new KizunaServer(contract);
101
+ *
102
+ * const requireUser = server.guard('user', ({ bearer, deny }) => {
103
+ * const session = bearer && sessions.get(bearer.token);
104
+ * return session ? { userId: session.userId } : deny(401, 'Unauthorized');
105
+ * });
106
+ *
107
+ * export const api = server.api({
108
+ * router,
109
+ * guards: {
110
+ * user: requireUser,
111
+ * },
112
+ * });
113
+ */
114
+ var KizunaServer = class {
115
+ constructor(contract, options) {
116
+ Object.assign(this, createServerSurface(contract, options));
117
+ }
118
+ };
119
+ //#endregion
120
+ exports.KizunaServer = KizunaServer;
121
+ exports.mountHono = mountHono;
@@ -0,0 +1,182 @@
1
+ import { Context, Env, Hono } from "hono";
2
+ import { ApiWithRouter, ContractPlugins, ErrorFormatter, GUARDS_META, GuardDenial, GuardDeny, GuardParams, GuardRun, HandlersFromAuth, JOBS_META, Jobs, PluginArgs, PluginImplementations, REQUEST_CONTEXT_META, RequestContextRun, RequestContextValues, RouteDefinition, RouteHandler as RouteHandler$1, Router as Router$1, Routes, SCHEMES_META, ServerOptions } from "@ts-kizuna/core/adapter";
3
+ import { z } from "zod";
4
+ import { Contract, CredentialOf, GuardSuccess, JobHandlers, JobsArg, RequestContextHeaderValues, RequestContextSchema, SecurityScheme, TagOptions } from "@ts-kizuna/core";
5
+
6
+ //#region src/server.d.ts
7
+ type HonoApi<R extends Routes = Routes> = ApiWithRouter<R> & {
8
+ readonly [GUARDS_META]?: unknown;
9
+ readonly [SCHEMES_META]?: unknown;
10
+ readonly [REQUEST_CONTEXT_META]?: unknown;
11
+ readonly [JOBS_META]?: unknown;
12
+ /**
13
+ * Register every contract route on a Hono app.
14
+ */
15
+ mount: <E extends Env = Env>(app: Hono<E>, options?: HonoOptions) => void;
16
+ };
17
+ interface HonoHandlerContext<E extends Env = Env> {
18
+ c: Context<E>;
19
+ }
20
+ /**
21
+ * The handler type for a single route, typed against its contract definition.
22
+ */
23
+ type RouteHandler<R extends RouteDefinition, E extends Env = Env> = RouteHandler$1<R, HonoHandlerContext<E>>;
24
+ /**
25
+ * The handler tree for a contract or route group, typed against it. Preserves
26
+ * Hono's {@link Env} generic for the handler context. Routes secured by the
27
+ * contract's `auth` map additionally receive each required identity's context
28
+ * in their handler args, under `auth`, keyed by the identity's name.
29
+ */
30
+ type Router<C, E extends Env = Env> = C extends Contract<infer R, infer _Tags, infer _Codes, infer Schemes, infer Auth, infer RequestContext, infer Plugins, infer J> ? HandlersFromAuth<R, HonoHandlerContext<E> & RequestContextValues<RequestContext> & PluginArgs<Plugins> & JobsArg<J>, Schemes, Auth> : C extends Routes ? Router$1<C, HonoHandlerContext<E>> : never;
31
+ /**
32
+ * The handler for each of a contract's scheduled jobs, typed against it. Each
33
+ * receives only the job's `input`, so the same handler can be run in process.
34
+ */
35
+ type JobsRouter<C> = C extends Contract<infer _R, infer _Tags, infer _Codes, infer _Schemes, infer _Auth, infer _RequestContext, infer _Plugins, infer J> ? JobHandlers<J> : never;
36
+ /**
37
+ * The handlers for a group named on the contract, or for a bare route group.
38
+ * Both forms resolve through one signature: a second candidate of the same
39
+ * arity costs zero-argument handlers their contextual type.
40
+ */
41
+ type GroupRouter<Source, GroupOrRoutes, E extends Env> = GroupOrRoutes extends string ? Router<Source, E>[Extract<GroupOrRoutes, keyof Router<Source, E>>] : Router<GroupOrRoutes, E>;
42
+ interface HonoOptions {
43
+ /**
44
+ * Validate handler return values against the routes' response schemas.
45
+ * Mismatches surface as 500 errors. Intended for development; disable in
46
+ * production.
47
+ *
48
+ * @default false
49
+ */
50
+ responseValidation?: boolean;
51
+ /**
52
+ * Reshape error (status >= 400) response bytes before they are sent. See
53
+ * {@link ErrorFormatter}.
54
+ */
55
+ formatError?: ErrorFormatter<Request>;
56
+ }
57
+ /**
58
+ * A guard per identity, keyed by name. Each receives the handler context, a
59
+ * `deny` helper, and the matched route's required scopes, and returns that
60
+ * identity's {@link GuardSuccess} (its context and access fields) or a `deny(...)`
61
+ * result. Keying by name lets each guard's return be typed against its own
62
+ * identity, so access values narrow without an annotation. An
63
+ * authentication-only identity (no context, no access) returns nothing on
64
+ * success, or `deny(...)`.
65
+ */
66
+ type GuardFns<Schemes extends Record<string, SecurityScheme>, Params, E extends Env> = { [Name in keyof Schemes]: (args: HonoHandlerContext<E> & CredentialOf<Schemes[Name]> & {
67
+ params: Params;
68
+ deny: GuardDeny;
69
+ scopes: string[];
70
+ }) => [keyof GuardSuccess<Schemes[Name]>] extends [never] ? void | GuardDenial | Promise<void | GuardDenial> : GuardSuccess<Schemes[Name]> | GuardDenial | Promise<GuardSuccess<Schemes[Name]> | GuardDenial> };
71
+ /**
72
+ * One guard per identity declared on the contract.
73
+ */
74
+ type GuardsForSchemes<Schemes extends Record<string, SecurityScheme>, E extends Env> = { [Name in keyof Schemes]: GuardRun<HonoHandlerContext<E>> };
75
+ /**
76
+ * The resolver functions for the request context schemas declared on `kizuna`,
77
+ * keyed by name. Each runs on every route and returns its schema's value.
78
+ */
79
+ type RequestResolverFns<RequestContext extends Record<string, RequestContextSchema>, E extends Env> = { [Name in keyof RequestContext]: (args: HonoHandlerContext<E> & {
80
+ params: Record<string, string>;
81
+ headers: RequestContextHeaderValues<RequestContext[Name]>;
82
+ }) => z.output<RequestContext[Name]['context']> | Promise<z.output<RequestContext[Name]['context']>> };
83
+ /**
84
+ * Mount a ts-kizuna API onto a Hono app.
85
+ *
86
+ * @example
87
+ * const app = new Hono();
88
+ * api.mount(app);
89
+ */
90
+ declare function mountHono<E extends Env = Env>(api: HonoApi, app: Hono<E>, options?: HonoOptions): void;
91
+ type ServerContract<R extends Routes, Schemes extends Record<string, SecurityScheme>, Auth, RequestContext extends Record<string, RequestContextSchema>, Plugins extends ContractPlugins, J extends Jobs = Jobs> = Contract<R, Record<string, TagOptions>, string, Schemes, Auth, RequestContext, Plugins, J>;
92
+ interface Server<R extends Routes, Schemes extends Record<string, SecurityScheme>, Auth, RequestContext extends Record<string, RequestContextSchema>, Plugins extends ContractPlugins, E extends Env = Env, J extends Jobs = Jobs> {
93
+ /**
94
+ * Define a guard for one of the contract's identities. It runs before the
95
+ * handlers of every route whose `auth` entry requires the identity, and
96
+ * receives the credential its method extracted (`bearer`, `apiKey`, or
97
+ * `basic`, `null` when absent). Return the identity's context and access
98
+ * fields to allow the request, or call `deny(status, detail)`.
99
+ */
100
+ guard<const Name extends Extract<keyof Schemes, string>>(name: Name, run: GuardFns<Schemes, GuardParams<R, Auth, Name>, E>[Name]): GuardRun<HonoHandlerContext<E>>;
101
+ /**
102
+ * Define a request context resolver declared on the contract. It runs on
103
+ * every route, public ones included, and never denies.
104
+ */
105
+ requestContext<const Name extends Extract<keyof RequestContext, string>>(name: Name, run: RequestResolverFns<RequestContext, E>[Name]): RequestContextRun<HonoHandlerContext<E>>;
106
+ /**
107
+ * Write typed handlers for the contract or one of its route groups.
108
+ */
109
+ router: {
110
+ <const GroupOrRoutes extends Extract<keyof Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, E>, string> | Routes>(group: GroupOrRoutes, router: GroupRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, GroupOrRoutes, E>): GroupRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, GroupOrRoutes, E>;
111
+ (router: Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, E>): Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, E>;
112
+ };
113
+ /**
114
+ * Write a handler for each of the contract's jobs.
115
+ *
116
+ * Pass a `transport` to say where a queued job goes. Without one, `queue`
117
+ * runs the job in this process and it is lost on a crash.
118
+ *
119
+ * @example
120
+ * export const jobs = server.jobs({
121
+ * sendDigests: async () => ({
122
+ * status: 200,
123
+ * body: {
124
+ * sent: await sendPendingDigests(),
125
+ * },
126
+ * }),
127
+ * });
128
+ */
129
+ jobs(handlers: JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>): JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>;
130
+ /**
131
+ * Assemble the router, guards, and job handlers into the api object.
132
+ */
133
+ api(options: {
134
+ router: Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, E>;
135
+ } & (string extends keyof Schemes ? {
136
+ guards?: undefined;
137
+ } : {
138
+ guards: NoInfer<GuardsForSchemes<Schemes, E>>;
139
+ }) & (string extends keyof J ? {
140
+ jobs?: undefined;
141
+ } : {
142
+ jobs: NoInfer<JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>>;
143
+ }) & (string extends keyof RequestContext ? {
144
+ requestContext?: undefined;
145
+ } : {
146
+ requestContext: NoInfer<{ [Name in keyof RequestContext]: RequestContextRun<HonoHandlerContext<E>> }>;
147
+ }) & (string extends keyof Plugins ? {
148
+ plugins?: undefined;
149
+ } : {
150
+ plugins: PluginImplementations<Plugins, HonoHandlerContext<E>>;
151
+ })): HonoApi<R>;
152
+ }
153
+ /**
154
+ * Turn a contract into a server handle: the serving counterpart to `Kizuna`.
155
+ * Keep the instance and use `server.guard` to define guards, `server.router`
156
+ * to write typed handlers, and `server.api` to assemble them.
157
+ *
158
+ * @example
159
+ * const server = new KizunaServer(contract);
160
+ *
161
+ * const requireUser = server.guard('user', ({ bearer, deny }) => {
162
+ * const session = bearer && sessions.get(bearer.token);
163
+ * return session ? { userId: session.userId } : deny(401, 'Unauthorized');
164
+ * });
165
+ *
166
+ * export const api = server.api({
167
+ * router,
168
+ * guards: {
169
+ * user: requireUser,
170
+ * },
171
+ * });
172
+ */
173
+ declare class KizunaServer<const R extends Routes, Schemes extends Record<string, SecurityScheme>, Auth, RequestContext extends Record<string, RequestContextSchema>, Plugins extends ContractPlugins, E extends Env = Env, J extends Jobs = Jobs> implements Server<R, Schemes, Auth, RequestContext, Plugins, E, J> {
174
+ readonly guard: Server<R, Schemes, Auth, RequestContext, Plugins, E, J>['guard'];
175
+ readonly requestContext: Server<R, Schemes, Auth, RequestContext, Plugins, E, J>['requestContext'];
176
+ readonly router: Server<R, Schemes, Auth, RequestContext, Plugins, E, J>['router'];
177
+ readonly jobs: Server<R, Schemes, Auth, RequestContext, Plugins, E, J>['jobs'];
178
+ readonly api: Server<R, Schemes, Auth, RequestContext, Plugins, E, J>['api'];
179
+ constructor(contract: ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, options?: ServerOptions);
180
+ }
181
+ //#endregion
182
+ export { HonoApi, HonoHandlerContext, HonoOptions, JobsRouter, KizunaServer, RouteHandler, Router, Server, mountHono };
@@ -0,0 +1,182 @@
1
+ import { ApiWithRouter, ContractPlugins, ErrorFormatter, GUARDS_META, GuardDenial, GuardDeny, GuardParams, GuardRun, HandlersFromAuth, JOBS_META, Jobs, PluginArgs, PluginImplementations, REQUEST_CONTEXT_META, RequestContextRun, RequestContextValues, RouteDefinition, RouteHandler as RouteHandler$1, Router as Router$1, Routes, SCHEMES_META, ServerOptions } from "@ts-kizuna/core/adapter";
2
+ import { Context, Env, Hono } from "hono";
3
+ import { z } from "zod";
4
+ import { Contract, CredentialOf, GuardSuccess, JobHandlers, JobsArg, RequestContextHeaderValues, RequestContextSchema, SecurityScheme, TagOptions } from "@ts-kizuna/core";
5
+
6
+ //#region src/server.d.ts
7
+ type HonoApi<R extends Routes = Routes> = ApiWithRouter<R> & {
8
+ readonly [GUARDS_META]?: unknown;
9
+ readonly [SCHEMES_META]?: unknown;
10
+ readonly [REQUEST_CONTEXT_META]?: unknown;
11
+ readonly [JOBS_META]?: unknown;
12
+ /**
13
+ * Register every contract route on a Hono app.
14
+ */
15
+ mount: <E extends Env = Env>(app: Hono<E>, options?: HonoOptions) => void;
16
+ };
17
+ interface HonoHandlerContext<E extends Env = Env> {
18
+ c: Context<E>;
19
+ }
20
+ /**
21
+ * The handler type for a single route, typed against its contract definition.
22
+ */
23
+ type RouteHandler<R extends RouteDefinition, E extends Env = Env> = RouteHandler$1<R, HonoHandlerContext<E>>;
24
+ /**
25
+ * The handler tree for a contract or route group, typed against it. Preserves
26
+ * Hono's {@link Env} generic for the handler context. Routes secured by the
27
+ * contract's `auth` map additionally receive each required identity's context
28
+ * in their handler args, under `auth`, keyed by the identity's name.
29
+ */
30
+ type Router<C, E extends Env = Env> = C extends Contract<infer R, infer _Tags, infer _Codes, infer Schemes, infer Auth, infer RequestContext, infer Plugins, infer J> ? HandlersFromAuth<R, HonoHandlerContext<E> & RequestContextValues<RequestContext> & PluginArgs<Plugins> & JobsArg<J>, Schemes, Auth> : C extends Routes ? Router$1<C, HonoHandlerContext<E>> : never;
31
+ /**
32
+ * The handler for each of a contract's scheduled jobs, typed against it. Each
33
+ * receives only the job's `input`, so the same handler can be run in process.
34
+ */
35
+ type JobsRouter<C> = C extends Contract<infer _R, infer _Tags, infer _Codes, infer _Schemes, infer _Auth, infer _RequestContext, infer _Plugins, infer J> ? JobHandlers<J> : never;
36
+ /**
37
+ * The handlers for a group named on the contract, or for a bare route group.
38
+ * Both forms resolve through one signature: a second candidate of the same
39
+ * arity costs zero-argument handlers their contextual type.
40
+ */
41
+ type GroupRouter<Source, GroupOrRoutes, E extends Env> = GroupOrRoutes extends string ? Router<Source, E>[Extract<GroupOrRoutes, keyof Router<Source, E>>] : Router<GroupOrRoutes, E>;
42
+ interface HonoOptions {
43
+ /**
44
+ * Validate handler return values against the routes' response schemas.
45
+ * Mismatches surface as 500 errors. Intended for development; disable in
46
+ * production.
47
+ *
48
+ * @default false
49
+ */
50
+ responseValidation?: boolean;
51
+ /**
52
+ * Reshape error (status >= 400) response bytes before they are sent. See
53
+ * {@link ErrorFormatter}.
54
+ */
55
+ formatError?: ErrorFormatter<Request>;
56
+ }
57
+ /**
58
+ * A guard per identity, keyed by name. Each receives the handler context, a
59
+ * `deny` helper, and the matched route's required scopes, and returns that
60
+ * identity's {@link GuardSuccess} (its context and access fields) or a `deny(...)`
61
+ * result. Keying by name lets each guard's return be typed against its own
62
+ * identity, so access values narrow without an annotation. An
63
+ * authentication-only identity (no context, no access) returns nothing on
64
+ * success, or `deny(...)`.
65
+ */
66
+ type GuardFns<Schemes extends Record<string, SecurityScheme>, Params, E extends Env> = { [Name in keyof Schemes]: (args: HonoHandlerContext<E> & CredentialOf<Schemes[Name]> & {
67
+ params: Params;
68
+ deny: GuardDeny;
69
+ scopes: string[];
70
+ }) => [keyof GuardSuccess<Schemes[Name]>] extends [never] ? void | GuardDenial | Promise<void | GuardDenial> : GuardSuccess<Schemes[Name]> | GuardDenial | Promise<GuardSuccess<Schemes[Name]> | GuardDenial> };
71
+ /**
72
+ * One guard per identity declared on the contract.
73
+ */
74
+ type GuardsForSchemes<Schemes extends Record<string, SecurityScheme>, E extends Env> = { [Name in keyof Schemes]: GuardRun<HonoHandlerContext<E>> };
75
+ /**
76
+ * The resolver functions for the request context schemas declared on `kizuna`,
77
+ * keyed by name. Each runs on every route and returns its schema's value.
78
+ */
79
+ type RequestResolverFns<RequestContext extends Record<string, RequestContextSchema>, E extends Env> = { [Name in keyof RequestContext]: (args: HonoHandlerContext<E> & {
80
+ params: Record<string, string>;
81
+ headers: RequestContextHeaderValues<RequestContext[Name]>;
82
+ }) => z.output<RequestContext[Name]['context']> | Promise<z.output<RequestContext[Name]['context']>> };
83
+ /**
84
+ * Mount a ts-kizuna API onto a Hono app.
85
+ *
86
+ * @example
87
+ * const app = new Hono();
88
+ * api.mount(app);
89
+ */
90
+ declare function mountHono<E extends Env = Env>(api: HonoApi, app: Hono<E>, options?: HonoOptions): void;
91
+ type ServerContract<R extends Routes, Schemes extends Record<string, SecurityScheme>, Auth, RequestContext extends Record<string, RequestContextSchema>, Plugins extends ContractPlugins, J extends Jobs = Jobs> = Contract<R, Record<string, TagOptions>, string, Schemes, Auth, RequestContext, Plugins, J>;
92
+ interface Server<R extends Routes, Schemes extends Record<string, SecurityScheme>, Auth, RequestContext extends Record<string, RequestContextSchema>, Plugins extends ContractPlugins, E extends Env = Env, J extends Jobs = Jobs> {
93
+ /**
94
+ * Define a guard for one of the contract's identities. It runs before the
95
+ * handlers of every route whose `auth` entry requires the identity, and
96
+ * receives the credential its method extracted (`bearer`, `apiKey`, or
97
+ * `basic`, `null` when absent). Return the identity's context and access
98
+ * fields to allow the request, or call `deny(status, detail)`.
99
+ */
100
+ guard<const Name extends Extract<keyof Schemes, string>>(name: Name, run: GuardFns<Schemes, GuardParams<R, Auth, Name>, E>[Name]): GuardRun<HonoHandlerContext<E>>;
101
+ /**
102
+ * Define a request context resolver declared on the contract. It runs on
103
+ * every route, public ones included, and never denies.
104
+ */
105
+ requestContext<const Name extends Extract<keyof RequestContext, string>>(name: Name, run: RequestResolverFns<RequestContext, E>[Name]): RequestContextRun<HonoHandlerContext<E>>;
106
+ /**
107
+ * Write typed handlers for the contract or one of its route groups.
108
+ */
109
+ router: {
110
+ <const GroupOrRoutes extends Extract<keyof Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, E>, string> | Routes>(group: GroupOrRoutes, router: GroupRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, GroupOrRoutes, E>): GroupRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, GroupOrRoutes, E>;
111
+ (router: Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, E>): Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, E>;
112
+ };
113
+ /**
114
+ * Write a handler for each of the contract's jobs.
115
+ *
116
+ * Pass a `transport` to say where a queued job goes. Without one, `queue`
117
+ * runs the job in this process and it is lost on a crash.
118
+ *
119
+ * @example
120
+ * export const jobs = server.jobs({
121
+ * sendDigests: async () => ({
122
+ * status: 200,
123
+ * body: {
124
+ * sent: await sendPendingDigests(),
125
+ * },
126
+ * }),
127
+ * });
128
+ */
129
+ jobs(handlers: JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>): JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>;
130
+ /**
131
+ * Assemble the router, guards, and job handlers into the api object.
132
+ */
133
+ api(options: {
134
+ router: Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, E>;
135
+ } & (string extends keyof Schemes ? {
136
+ guards?: undefined;
137
+ } : {
138
+ guards: NoInfer<GuardsForSchemes<Schemes, E>>;
139
+ }) & (string extends keyof J ? {
140
+ jobs?: undefined;
141
+ } : {
142
+ jobs: NoInfer<JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>>;
143
+ }) & (string extends keyof RequestContext ? {
144
+ requestContext?: undefined;
145
+ } : {
146
+ requestContext: NoInfer<{ [Name in keyof RequestContext]: RequestContextRun<HonoHandlerContext<E>> }>;
147
+ }) & (string extends keyof Plugins ? {
148
+ plugins?: undefined;
149
+ } : {
150
+ plugins: PluginImplementations<Plugins, HonoHandlerContext<E>>;
151
+ })): HonoApi<R>;
152
+ }
153
+ /**
154
+ * Turn a contract into a server handle: the serving counterpart to `Kizuna`.
155
+ * Keep the instance and use `server.guard` to define guards, `server.router`
156
+ * to write typed handlers, and `server.api` to assemble them.
157
+ *
158
+ * @example
159
+ * const server = new KizunaServer(contract);
160
+ *
161
+ * const requireUser = server.guard('user', ({ bearer, deny }) => {
162
+ * const session = bearer && sessions.get(bearer.token);
163
+ * return session ? { userId: session.userId } : deny(401, 'Unauthorized');
164
+ * });
165
+ *
166
+ * export const api = server.api({
167
+ * router,
168
+ * guards: {
169
+ * user: requireUser,
170
+ * },
171
+ * });
172
+ */
173
+ declare class KizunaServer<const R extends Routes, Schemes extends Record<string, SecurityScheme>, Auth, RequestContext extends Record<string, RequestContextSchema>, Plugins extends ContractPlugins, E extends Env = Env, J extends Jobs = Jobs> implements Server<R, Schemes, Auth, RequestContext, Plugins, E, J> {
174
+ readonly guard: Server<R, Schemes, Auth, RequestContext, Plugins, E, J>['guard'];
175
+ readonly requestContext: Server<R, Schemes, Auth, RequestContext, Plugins, E, J>['requestContext'];
176
+ readonly router: Server<R, Schemes, Auth, RequestContext, Plugins, E, J>['router'];
177
+ readonly jobs: Server<R, Schemes, Auth, RequestContext, Plugins, E, J>['jobs'];
178
+ readonly api: Server<R, Schemes, Auth, RequestContext, Plugins, E, J>['api'];
179
+ constructor(contract: ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, options?: ServerOptions);
180
+ }
181
+ //#endregion
182
+ export { HonoApi, HonoHandlerContext, HonoOptions, JobsRouter, KizunaServer, RouteHandler, Router, Server, mountHono };
package/dist/index.mjs ADDED
@@ -0,0 +1,119 @@
1
+ import { GUARDS_META, JOBS_META, REQUEST_CONTEXT_META, ROUTER_META, SCHEMES_META, assembleApi, createAdapter, headersToObject, jobRouter, jobRoutes, jobRunnerFrom, parseFetchBody, pluginExportsOf, pluginRouterOf, pluginRoutesOf, renderJsonResult, warnUnsupportedJobOptions } from "@ts-kizuna/core/adapter";
2
+ //#region src/server.ts
3
+ const honoAdapter = createAdapter({
4
+ buildHandlerContext: (_adapterRequest, { c }) => ({ c }),
5
+ respond: (result, { c, formatError }) => {
6
+ if (result.kind === "handler-error") throw result.error;
7
+ if (result.kind === "raw-response") return result.response;
8
+ const rendered = renderJsonResult(result, formatError, c.req.raw);
9
+ if (rendered.body === void 0) return c.body(null, rendered.status, rendered.headers);
10
+ if (rendered.raw) return c.body(rendered.body, rendered.status, rendered.headers);
11
+ return c.json(rendered.body, rendered.status, rendered.headers);
12
+ }
13
+ });
14
+ /**
15
+ * Mount a ts-kizuna API onto a Hono app.
16
+ *
17
+ * @example
18
+ * const app = new Hono();
19
+ * api.mount(app);
20
+ */
21
+ function mountHono(api, app, options) {
22
+ const guards = api[GUARDS_META];
23
+ const schemes = api[SCHEMES_META];
24
+ const requestContext = api[REQUEST_CONTEXT_META];
25
+ const pluginExports = pluginExportsOf(api);
26
+ const jobsMeta = api[JOBS_META];
27
+ const jobRunner = jobRunnerFrom(jobsMeta);
28
+ const mountRoute = (routeKey, route, lane, resolvedRouter) => {
29
+ const method = route.method.toLowerCase();
30
+ const kizunaHandler = async (c) => {
31
+ const url = new URL(c.req.url);
32
+ const adapterRequest = {
33
+ request: c.req.raw,
34
+ method: c.req.method,
35
+ resolution: {
36
+ kind: "pre-resolved",
37
+ routeKey,
38
+ route,
39
+ params: c.req.param()
40
+ },
41
+ query: Object.fromEntries(url.searchParams),
42
+ headers: headersToObject(c.req.raw.headers),
43
+ readBody: (r) => parseFetchBody(c.req.raw, r)
44
+ };
45
+ return honoAdapter.handle({
46
+ routes: lane,
47
+ router: resolvedRouter,
48
+ request: adapterRequest,
49
+ responseContext: {
50
+ c,
51
+ formatError: options?.formatError
52
+ },
53
+ guards,
54
+ schemes,
55
+ requestContext,
56
+ pluginExports,
57
+ jobs: jobRunner,
58
+ responseValidation: options?.responseValidation
59
+ });
60
+ };
61
+ app.on(method, route.path, kizunaHandler);
62
+ };
63
+ const mountLane = (lane, resolvedRouter) => {
64
+ for (const { routeKey, route } of honoAdapter.eachRoute(lane, resolvedRouter)) mountRoute(routeKey, route, lane, resolvedRouter);
65
+ };
66
+ mountLane(api.routes, api[ROUTER_META]);
67
+ mountLane(pluginRoutesOf(api), pluginRouterOf(api));
68
+ if (jobsMeta) {
69
+ const routes = jobRoutes(jobsMeta);
70
+ const router = jobRouter(jobsMeta);
71
+ for (const [routeKey, route] of Object.entries(routes)) mountRoute(routeKey, route, routes, router);
72
+ }
73
+ }
74
+ const createServerSurface = (contract, options) => {
75
+ warnUnsupportedJobOptions(contract.jobs, options?.jobTransport);
76
+ return {
77
+ guard: (_name, run) => run,
78
+ requestContext: (_name, run) => run,
79
+ router: (groupOrRouter, groupRouter) => groupRouter ?? groupOrRouter,
80
+ jobs: (handlers) => handlers,
81
+ api: ({ jobs, ...parts }) => {
82
+ const api = Object.assign(assembleApi(contract, parts), { [JOBS_META]: contract.jobs ? {
83
+ jobs: contract.jobs,
84
+ handlers: jobs ?? {},
85
+ config: contract.jobsConfig,
86
+ transport: options?.jobTransport,
87
+ onError: options?.onJobError
88
+ } : void 0 });
89
+ return Object.assign(api, { mount: (app, mountOptions) => mountHono(api, app, mountOptions) });
90
+ }
91
+ };
92
+ };
93
+ /**
94
+ * Turn a contract into a server handle: the serving counterpart to `Kizuna`.
95
+ * Keep the instance and use `server.guard` to define guards, `server.router`
96
+ * to write typed handlers, and `server.api` to assemble them.
97
+ *
98
+ * @example
99
+ * const server = new KizunaServer(contract);
100
+ *
101
+ * const requireUser = server.guard('user', ({ bearer, deny }) => {
102
+ * const session = bearer && sessions.get(bearer.token);
103
+ * return session ? { userId: session.userId } : deny(401, 'Unauthorized');
104
+ * });
105
+ *
106
+ * export const api = server.api({
107
+ * router,
108
+ * guards: {
109
+ * user: requireUser,
110
+ * },
111
+ * });
112
+ */
113
+ var KizunaServer = class {
114
+ constructor(contract, options) {
115
+ Object.assign(this, createServerSurface(contract, options));
116
+ }
117
+ };
118
+ //#endregion
119
+ export { KizunaServer, mountHono };
package/package.json ADDED
@@ -0,0 +1,73 @@
1
+ {
2
+ "name": "@ts-kizuna/hono",
3
+ "version": "1.49.5",
4
+ "description": "Hono adapter for ts-kizuna",
5
+ "keywords": [
6
+ "ts-kizuna",
7
+ "typescript",
8
+ "zod",
9
+ "openapi",
10
+ "contract-first",
11
+ "type-safe",
12
+ "rest",
13
+ "api",
14
+ "hono",
15
+ "adapter",
16
+ "server"
17
+ ],
18
+ "license": "MIT",
19
+ "homepage": "https://ts-kizuna.com/docs/adapters/hono",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/ts-kizuna/kizuna.git",
23
+ "directory": "packages/hono"
24
+ },
25
+ "bugs": "https://github.com/ts-kizuna/kizuna/issues",
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "engines": {
29
+ "node": ">=24"
30
+ },
31
+ "main": "./dist/index.cjs",
32
+ "module": "./dist/index.mjs",
33
+ "types": "./dist/index.d.mts",
34
+ "exports": {
35
+ ".": {
36
+ "import": {
37
+ "types": "./dist/index.d.mts",
38
+ "default": "./dist/index.mjs"
39
+ },
40
+ "require": {
41
+ "types": "./dist/index.d.cts",
42
+ "default": "./dist/index.cjs"
43
+ }
44
+ }
45
+ },
46
+ "kizuna": {
47
+ "entries": {
48
+ ".": "server"
49
+ }
50
+ },
51
+ "files": [
52
+ "dist"
53
+ ],
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "peerDependencies": {
58
+ "hono": "^4.0.0",
59
+ "zod": "^4.0.0",
60
+ "@ts-kizuna/core": "1.49.5"
61
+ },
62
+ "devDependencies": {
63
+ "hono": "^4.7.0",
64
+ "tsdown": "^0.21.0",
65
+ "typescript": "^5.6.3",
66
+ "zod": "^4.0.0",
67
+ "@ts-kizuna/core": "1.49.5"
68
+ },
69
+ "scripts": {
70
+ "build": "tsdown src/index.ts --format esm,cjs --dts --clean --external @ts-kizuna/core --external hono --external zod",
71
+ "typecheck": "tsc --noEmit"
72
+ }
73
+ }