@ts-kizuna/express 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,37 @@
1
+ # @ts-kizuna/express
2
+
3
+ `@ts-kizuna/express` connects a ts-kizuna API to an Express 5 application. It handles routing, request validation, body parsing, and error formatting, all driven by your contract.
4
+
5
+ **Requires Express >= 5.**
6
+
7
+ ## Installation
8
+
9
+ ```sh
10
+ pnpm add @ts-kizuna/express express
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import express from 'express';
17
+ import { KizunaServer } from '@ts-kizuna/express';
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 = express();
28
+ app.use(express.json());
29
+
30
+ api.mount(app);
31
+
32
+ app.listen(3000);
33
+ ```
34
+
35
+ ## Documentation
36
+
37
+ [Express adapter](https://ts-kizuna.com/docs/adapters/express)
package/dist/index.cjs ADDED
@@ -0,0 +1,157 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let express = require("express");
3
+ let node_stream = require("node:stream");
4
+ let _ts_kizuna_core_adapter = require("@ts-kizuna/core/adapter");
5
+ //#region src/server.ts
6
+ /**
7
+ * Write a web `Response` to a node response. Plugins answer in web terms to stay
8
+ * adapter-agnostic, so the translation belongs here.
9
+ */
10
+ const writeWebResponse = async (response, res) => {
11
+ if (!(response instanceof globalThis.Response)) return;
12
+ res.status(response.status);
13
+ response.headers.forEach((value, name) => res.setHeader(name, value));
14
+ if (!response.body) {
15
+ res.end();
16
+ return;
17
+ }
18
+ node_stream.Readable.fromWeb(response.body).pipe(res);
19
+ };
20
+ const adapter = (0, _ts_kizuna_core_adapter.createAdapter)({
21
+ buildHandlerContext: (adapterRequest, { res }) => ({
22
+ req: adapterRequest.request,
23
+ res
24
+ }),
25
+ respond: (result, { res, next, formatError }) => {
26
+ if (result.kind === "handler-error") {
27
+ next(result.error);
28
+ return;
29
+ }
30
+ if (result.kind === "raw-response") {
31
+ writeWebResponse(result.response, res);
32
+ return;
33
+ }
34
+ if (res.headersSent) return;
35
+ if (result.kind === "not-found" || result.kind === "method-not-allowed") {
36
+ next();
37
+ return;
38
+ }
39
+ const rendered = (0, _ts_kizuna_core_adapter.renderJsonResult)(result, formatError, res.req);
40
+ for (const [key, value] of Object.entries(rendered.headers)) res.setHeader(key, value);
41
+ if (rendered.body === void 0) res.status(rendered.status).end();
42
+ else if (rendered.raw) {
43
+ const body = rendered.body;
44
+ res.status(rendered.status).send(typeof body === "string" || Buffer.isBuffer(body) ? body : Buffer.from(body));
45
+ } else res.status(rendered.status).json(rendered.body);
46
+ }
47
+ });
48
+ /**
49
+ * Mount a ts-kizuna API onto an Express app.
50
+ *
51
+ * @example
52
+ * api.mount(app);
53
+ */
54
+ function mountExpress(api, app, options) {
55
+ const guards = api[_ts_kizuna_core_adapter.GUARDS_META];
56
+ const schemes = api[_ts_kizuna_core_adapter.SCHEMES_META];
57
+ const requestContext = api[_ts_kizuna_core_adapter.REQUEST_CONTEXT_META];
58
+ const pluginExports = (0, _ts_kizuna_core_adapter.pluginExportsOf)(api);
59
+ const jobsMeta = api[_ts_kizuna_core_adapter.JOBS_META];
60
+ const jobRunner = (0, _ts_kizuna_core_adapter.jobRunnerFrom)(jobsMeta);
61
+ const expressRouter = (0, express.Router)();
62
+ const mountRoute = (routeKey, route, routes, router) => {
63
+ expressRouter[route.method.toLowerCase()](route.path, (req, _res, next) => {
64
+ req.kizunaRoute = route;
65
+ next();
66
+ }, async (req, res, next) => {
67
+ const adapterRequest = {
68
+ request: req,
69
+ method: req.method,
70
+ resolution: {
71
+ kind: "pre-resolved",
72
+ routeKey,
73
+ route,
74
+ params: req.params
75
+ },
76
+ query: req.query,
77
+ headers: req.headers,
78
+ readBody: () => req.body
79
+ };
80
+ await adapter.handle({
81
+ routes,
82
+ router,
83
+ request: adapterRequest,
84
+ responseContext: {
85
+ res,
86
+ next,
87
+ formatError: options?.formatError
88
+ },
89
+ guards,
90
+ schemes,
91
+ requestContext,
92
+ pluginExports,
93
+ jobs: jobRunner,
94
+ responseValidation: options?.responseValidation
95
+ });
96
+ });
97
+ };
98
+ const mountLane = (routes, router) => {
99
+ for (const { routeKey, route } of adapter.eachRoute(routes, router)) mountRoute(routeKey, route, routes, router);
100
+ };
101
+ mountLane(api.routes, api[_ts_kizuna_core_adapter.ROUTER_META]);
102
+ mountLane((0, _ts_kizuna_core_adapter.pluginRoutesOf)(api), (0, _ts_kizuna_core_adapter.pluginRouterOf)(api));
103
+ if (jobsMeta) {
104
+ const routes = (0, _ts_kizuna_core_adapter.jobRoutes)(jobsMeta);
105
+ const router = (0, _ts_kizuna_core_adapter.jobRouter)(jobsMeta);
106
+ for (const [routeKey, route] of Object.entries(routes)) mountRoute(routeKey, route, routes, router);
107
+ }
108
+ app.use(expressRouter);
109
+ return expressRouter;
110
+ }
111
+ const createServerSurface = (contract, options) => {
112
+ (0, _ts_kizuna_core_adapter.warnUnsupportedJobOptions)(contract.jobs, options?.jobTransport);
113
+ return {
114
+ guard: (_name, run) => run,
115
+ requestContext: (_name, run) => run,
116
+ router: (groupOrRouter, groupRouter) => groupRouter ?? groupOrRouter,
117
+ jobs: (handlers) => handlers,
118
+ api: ({ jobs, ...parts }) => {
119
+ const api = Object.assign((0, _ts_kizuna_core_adapter.assembleApi)(contract, parts), { [_ts_kizuna_core_adapter.JOBS_META]: contract.jobs ? {
120
+ jobs: contract.jobs,
121
+ handlers: jobs ?? {},
122
+ config: contract.jobsConfig,
123
+ transport: options?.jobTransport,
124
+ onError: options?.onJobError
125
+ } : void 0 });
126
+ return Object.assign(api, { mount: (app, mountOptions) => mountExpress(api, app, mountOptions) });
127
+ }
128
+ };
129
+ };
130
+ /**
131
+ * Turn a contract into a server handle: the serving counterpart to `Kizuna`.
132
+ * Keep the instance and use `server.guard` to define guards, `server.router`
133
+ * to write typed handlers, and `server.api` to assemble them.
134
+ *
135
+ * @example
136
+ * const server = new KizunaServer(contract);
137
+ *
138
+ * const requireUser = server.guard('user', ({ bearer, deny }) => {
139
+ * const session = bearer && sessions.get(bearer.token);
140
+ * return session ? { userId: session.userId } : deny(401, 'Unauthorized');
141
+ * });
142
+ *
143
+ * export const api = server.api({
144
+ * router,
145
+ * guards: {
146
+ * user: requireUser,
147
+ * },
148
+ * });
149
+ */
150
+ var KizunaServer = class {
151
+ constructor(contract, options) {
152
+ Object.assign(this, createServerSurface(contract, options));
153
+ }
154
+ };
155
+ //#endregion
156
+ exports.KizunaServer = KizunaServer;
157
+ exports.mountExpress = mountExpress;
@@ -0,0 +1,193 @@
1
+ import { Request, Response, Router as Router$1 } from "express";
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$2, 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 ExpressApi<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 an Express app or router.
14
+ */
15
+ mount: (app: AppLike, options?: ExpressOptions) => Router$1;
16
+ };
17
+ /**
18
+ * The Express request and response passed to each handler.
19
+ */
20
+ interface ExpressHandlerContext {
21
+ req: Request;
22
+ res: Response;
23
+ }
24
+ /**
25
+ * The handler for a single route, typed against its contract definition.
26
+ */
27
+ type RouteHandler<R extends RouteDefinition> = RouteHandler$1<R, ExpressHandlerContext>;
28
+ /**
29
+ * The handler tree for a contract or route group, typed against it. Routes
30
+ * secured by the contract's `auth` map additionally receive each required
31
+ * identity's context in their handler args, under `auth`, keyed by the identity's name.
32
+ */
33
+ type Router<C> = C extends Contract<infer R, infer _Tags, infer _Codes, infer Schemes, infer Auth, infer RequestContext, infer Plugins, infer J> ? HandlersFromAuth<R, ExpressHandlerContext & RequestContextValues<RequestContext> & PluginArgs<Plugins> & JobsArg<J>, Schemes, Auth> : C extends Routes ? Router$2<C, ExpressHandlerContext> : never;
34
+ /**
35
+ * The handler for each of a contract's scheduled jobs, typed against it. Each
36
+ * receives only the job's `input`, so the same handler can be run in process.
37
+ */
38
+ 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;
39
+ /**
40
+ * The handlers for a group named on the contract, or for a bare route group.
41
+ * Both forms resolve through one signature: a second candidate of the same
42
+ * arity costs zero-argument handlers their contextual type.
43
+ */
44
+ type GroupRouter<Source, GroupOrRoutes> = GroupOrRoutes extends string ? Router<Source>[Extract<GroupOrRoutes, keyof Router<Source>>] : Router<GroupOrRoutes>;
45
+ declare global {
46
+ namespace Express {
47
+ interface Request {
48
+ kizunaRoute?: RouteDefinition;
49
+ }
50
+ }
51
+ }
52
+ interface ExpressOptions {
53
+ /**
54
+ * Validate handler return values against the route's response schemas.
55
+ * Mismatches surface as 500 errors. Enable in development.
56
+ *
57
+ * @default false
58
+ */
59
+ responseValidation?: boolean;
60
+ /**
61
+ * Reshape error (status >= 400) response bytes before they are sent. See
62
+ * {@link ErrorFormatter}.
63
+ */
64
+ formatError?: ErrorFormatter<Request>;
65
+ }
66
+ /**
67
+ * A guard per identity, keyed by name. Each receives the handler context, a
68
+ * `deny` helper, and the matched route's required scopes, and returns that
69
+ * identity's {@link GuardSuccess} (its context and access fields) or a `deny(...)`
70
+ * result. Keying by name lets each guard's return be typed against its own
71
+ * identity, so access values narrow without an annotation. An
72
+ * authentication-only identity (no context, no access) returns nothing on
73
+ * success, or `deny(...)`.
74
+ */
75
+ type GuardFns<Schemes extends Record<string, SecurityScheme>, Params> = { [Name in keyof Schemes]: (args: ExpressHandlerContext & CredentialOf<Schemes[Name]> & {
76
+ params: Params;
77
+ deny: GuardDeny;
78
+ scopes: string[];
79
+ }) => [keyof GuardSuccess<Schemes[Name]>] extends [never] ? void | GuardDenial | Promise<void | GuardDenial> : GuardSuccess<Schemes[Name]> | GuardDenial | Promise<GuardSuccess<Schemes[Name]> | GuardDenial> };
80
+ /**
81
+ * One guard per identity declared on the contract.
82
+ */
83
+ type GuardsForSchemes<Schemes extends Record<string, SecurityScheme>> = { [Name in keyof Schemes]: GuardRun<ExpressHandlerContext> };
84
+ /**
85
+ * The resolver functions for the request context schemas declared on `kizuna`,
86
+ * keyed by name. Each runs on every route and returns its schema's value.
87
+ */
88
+ type RequestResolverFns<RequestContext extends Record<string, RequestContextSchema>> = { [Name in keyof RequestContext]: (args: ExpressHandlerContext & {
89
+ params: Record<string, string>;
90
+ headers: RequestContextHeaderValues<RequestContext[Name]>;
91
+ }) => z.output<RequestContext[Name]['context']> | Promise<z.output<RequestContext[Name]['context']>> };
92
+ interface AppLike {
93
+ use: (router: Router$1) => unknown;
94
+ }
95
+ /**
96
+ * Mount a ts-kizuna API onto an Express app.
97
+ *
98
+ * @example
99
+ * api.mount(app);
100
+ */
101
+ declare function mountExpress(api: ExpressApi, app: AppLike, options?: ExpressOptions): Router$1;
102
+ 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>;
103
+ interface Server<R extends Routes, Schemes extends Record<string, SecurityScheme>, Auth, RequestContext extends Record<string, RequestContextSchema>, Plugins extends ContractPlugins, J extends Jobs = Jobs> {
104
+ /**
105
+ * Define a guard for one of the contract's identities. It runs before the
106
+ * handlers of every route whose `auth` entry requires the identity, and
107
+ * receives the credential its method extracted (`bearer`, `apiKey`, or
108
+ * `basic`, `null` when absent). Return the identity's context and access
109
+ * fields to allow the request, or call `deny(status, detail)`.
110
+ */
111
+ guard<const Name extends Extract<keyof Schemes, string>>(name: Name, run: GuardFns<Schemes, GuardParams<R, Auth, Name>>[Name]): GuardRun<ExpressHandlerContext>;
112
+ /**
113
+ * Define a request context resolver declared on the contract. It runs on
114
+ * every route, public ones included, and never denies.
115
+ */
116
+ requestContext<const Name extends Extract<keyof RequestContext, string>>(name: Name, run: RequestResolverFns<RequestContext>[Name]): RequestContextRun<ExpressHandlerContext>;
117
+ /**
118
+ * Write typed handlers for the contract or one of its route groups.
119
+ */
120
+ router: {
121
+ <const GroupOrRoutes extends Extract<keyof Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>, string> | Routes>(group: GroupOrRoutes, router: GroupRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, GroupOrRoutes>): GroupRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, GroupOrRoutes>;
122
+ (router: Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>): Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>;
123
+ };
124
+ /**
125
+ * Write a handler for each of the contract's jobs.
126
+ *
127
+ * Pass a `transport` to say where a queued job goes. Without one, `queue`
128
+ * runs the job in this process and it is lost on a crash.
129
+ *
130
+ * @example
131
+ * export const jobs = server.jobs({
132
+ * sendDigests: async () => ({
133
+ * status: 200,
134
+ * body: {
135
+ * sent: await sendPendingDigests(),
136
+ * },
137
+ * }),
138
+ * });
139
+ */
140
+ jobs(handlers: JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>): JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>;
141
+ /**
142
+ * Assemble the router, guards, and job handlers into the api object.
143
+ */
144
+ api(options: {
145
+ router: Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>;
146
+ } & (string extends keyof Schemes ? {
147
+ guards?: undefined;
148
+ } : {
149
+ guards: NoInfer<GuardsForSchemes<Schemes>>;
150
+ }) & (string extends keyof J ? {
151
+ jobs?: undefined;
152
+ } : {
153
+ jobs: NoInfer<JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>>;
154
+ }) & (string extends keyof RequestContext ? {
155
+ requestContext?: undefined;
156
+ } : {
157
+ requestContext: NoInfer<{ [Name in keyof RequestContext]: RequestContextRun<ExpressHandlerContext> }>;
158
+ }) & (string extends keyof Plugins ? {
159
+ plugins?: undefined;
160
+ } : {
161
+ plugins: PluginImplementations<Plugins, ExpressHandlerContext>;
162
+ })): ExpressApi<R>;
163
+ }
164
+ /**
165
+ * Turn a contract into a server handle: the serving counterpart to `Kizuna`.
166
+ * Keep the instance and use `server.guard` to define guards, `server.router`
167
+ * to write typed handlers, and `server.api` to assemble them.
168
+ *
169
+ * @example
170
+ * const server = new KizunaServer(contract);
171
+ *
172
+ * const requireUser = server.guard('user', ({ bearer, deny }) => {
173
+ * const session = bearer && sessions.get(bearer.token);
174
+ * return session ? { userId: session.userId } : deny(401, 'Unauthorized');
175
+ * });
176
+ *
177
+ * export const api = server.api({
178
+ * router,
179
+ * guards: {
180
+ * user: requireUser,
181
+ * },
182
+ * });
183
+ */
184
+ declare class KizunaServer<const R extends Routes, Schemes extends Record<string, SecurityScheme>, Auth, RequestContext extends Record<string, RequestContextSchema>, Plugins extends ContractPlugins, J extends Jobs = Jobs> implements Server<R, Schemes, Auth, RequestContext, Plugins, J> {
185
+ readonly guard: Server<R, Schemes, Auth, RequestContext, Plugins, J>['guard'];
186
+ readonly requestContext: Server<R, Schemes, Auth, RequestContext, Plugins, J>['requestContext'];
187
+ readonly router: Server<R, Schemes, Auth, RequestContext, Plugins, J>['router'];
188
+ readonly jobs: Server<R, Schemes, Auth, RequestContext, Plugins, J>['jobs'];
189
+ readonly api: Server<R, Schemes, Auth, RequestContext, Plugins, J>['api'];
190
+ constructor(contract: ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, options?: ServerOptions);
191
+ }
192
+ //#endregion
193
+ export { AppLike, ExpressApi, ExpressHandlerContext, ExpressOptions, JobsRouter, KizunaServer, RouteHandler, Router, Server, mountExpress };
@@ -0,0 +1,193 @@
1
+ import { Request, Response, Router as Router$1 } from "express";
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$2, 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 ExpressApi<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 an Express app or router.
14
+ */
15
+ mount: (app: AppLike, options?: ExpressOptions) => Router$1;
16
+ };
17
+ /**
18
+ * The Express request and response passed to each handler.
19
+ */
20
+ interface ExpressHandlerContext {
21
+ req: Request;
22
+ res: Response;
23
+ }
24
+ /**
25
+ * The handler for a single route, typed against its contract definition.
26
+ */
27
+ type RouteHandler<R extends RouteDefinition> = RouteHandler$1<R, ExpressHandlerContext>;
28
+ /**
29
+ * The handler tree for a contract or route group, typed against it. Routes
30
+ * secured by the contract's `auth` map additionally receive each required
31
+ * identity's context in their handler args, under `auth`, keyed by the identity's name.
32
+ */
33
+ type Router<C> = C extends Contract<infer R, infer _Tags, infer _Codes, infer Schemes, infer Auth, infer RequestContext, infer Plugins, infer J> ? HandlersFromAuth<R, ExpressHandlerContext & RequestContextValues<RequestContext> & PluginArgs<Plugins> & JobsArg<J>, Schemes, Auth> : C extends Routes ? Router$2<C, ExpressHandlerContext> : never;
34
+ /**
35
+ * The handler for each of a contract's scheduled jobs, typed against it. Each
36
+ * receives only the job's `input`, so the same handler can be run in process.
37
+ */
38
+ 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;
39
+ /**
40
+ * The handlers for a group named on the contract, or for a bare route group.
41
+ * Both forms resolve through one signature: a second candidate of the same
42
+ * arity costs zero-argument handlers their contextual type.
43
+ */
44
+ type GroupRouter<Source, GroupOrRoutes> = GroupOrRoutes extends string ? Router<Source>[Extract<GroupOrRoutes, keyof Router<Source>>] : Router<GroupOrRoutes>;
45
+ declare global {
46
+ namespace Express {
47
+ interface Request {
48
+ kizunaRoute?: RouteDefinition;
49
+ }
50
+ }
51
+ }
52
+ interface ExpressOptions {
53
+ /**
54
+ * Validate handler return values against the route's response schemas.
55
+ * Mismatches surface as 500 errors. Enable in development.
56
+ *
57
+ * @default false
58
+ */
59
+ responseValidation?: boolean;
60
+ /**
61
+ * Reshape error (status >= 400) response bytes before they are sent. See
62
+ * {@link ErrorFormatter}.
63
+ */
64
+ formatError?: ErrorFormatter<Request>;
65
+ }
66
+ /**
67
+ * A guard per identity, keyed by name. Each receives the handler context, a
68
+ * `deny` helper, and the matched route's required scopes, and returns that
69
+ * identity's {@link GuardSuccess} (its context and access fields) or a `deny(...)`
70
+ * result. Keying by name lets each guard's return be typed against its own
71
+ * identity, so access values narrow without an annotation. An
72
+ * authentication-only identity (no context, no access) returns nothing on
73
+ * success, or `deny(...)`.
74
+ */
75
+ type GuardFns<Schemes extends Record<string, SecurityScheme>, Params> = { [Name in keyof Schemes]: (args: ExpressHandlerContext & CredentialOf<Schemes[Name]> & {
76
+ params: Params;
77
+ deny: GuardDeny;
78
+ scopes: string[];
79
+ }) => [keyof GuardSuccess<Schemes[Name]>] extends [never] ? void | GuardDenial | Promise<void | GuardDenial> : GuardSuccess<Schemes[Name]> | GuardDenial | Promise<GuardSuccess<Schemes[Name]> | GuardDenial> };
80
+ /**
81
+ * One guard per identity declared on the contract.
82
+ */
83
+ type GuardsForSchemes<Schemes extends Record<string, SecurityScheme>> = { [Name in keyof Schemes]: GuardRun<ExpressHandlerContext> };
84
+ /**
85
+ * The resolver functions for the request context schemas declared on `kizuna`,
86
+ * keyed by name. Each runs on every route and returns its schema's value.
87
+ */
88
+ type RequestResolverFns<RequestContext extends Record<string, RequestContextSchema>> = { [Name in keyof RequestContext]: (args: ExpressHandlerContext & {
89
+ params: Record<string, string>;
90
+ headers: RequestContextHeaderValues<RequestContext[Name]>;
91
+ }) => z.output<RequestContext[Name]['context']> | Promise<z.output<RequestContext[Name]['context']>> };
92
+ interface AppLike {
93
+ use: (router: Router$1) => unknown;
94
+ }
95
+ /**
96
+ * Mount a ts-kizuna API onto an Express app.
97
+ *
98
+ * @example
99
+ * api.mount(app);
100
+ */
101
+ declare function mountExpress(api: ExpressApi, app: AppLike, options?: ExpressOptions): Router$1;
102
+ 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>;
103
+ interface Server<R extends Routes, Schemes extends Record<string, SecurityScheme>, Auth, RequestContext extends Record<string, RequestContextSchema>, Plugins extends ContractPlugins, J extends Jobs = Jobs> {
104
+ /**
105
+ * Define a guard for one of the contract's identities. It runs before the
106
+ * handlers of every route whose `auth` entry requires the identity, and
107
+ * receives the credential its method extracted (`bearer`, `apiKey`, or
108
+ * `basic`, `null` when absent). Return the identity's context and access
109
+ * fields to allow the request, or call `deny(status, detail)`.
110
+ */
111
+ guard<const Name extends Extract<keyof Schemes, string>>(name: Name, run: GuardFns<Schemes, GuardParams<R, Auth, Name>>[Name]): GuardRun<ExpressHandlerContext>;
112
+ /**
113
+ * Define a request context resolver declared on the contract. It runs on
114
+ * every route, public ones included, and never denies.
115
+ */
116
+ requestContext<const Name extends Extract<keyof RequestContext, string>>(name: Name, run: RequestResolverFns<RequestContext>[Name]): RequestContextRun<ExpressHandlerContext>;
117
+ /**
118
+ * Write typed handlers for the contract or one of its route groups.
119
+ */
120
+ router: {
121
+ <const GroupOrRoutes extends Extract<keyof Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>, string> | Routes>(group: GroupOrRoutes, router: GroupRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, GroupOrRoutes>): GroupRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, GroupOrRoutes>;
122
+ (router: Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>): Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>;
123
+ };
124
+ /**
125
+ * Write a handler for each of the contract's jobs.
126
+ *
127
+ * Pass a `transport` to say where a queued job goes. Without one, `queue`
128
+ * runs the job in this process and it is lost on a crash.
129
+ *
130
+ * @example
131
+ * export const jobs = server.jobs({
132
+ * sendDigests: async () => ({
133
+ * status: 200,
134
+ * body: {
135
+ * sent: await sendPendingDigests(),
136
+ * },
137
+ * }),
138
+ * });
139
+ */
140
+ jobs(handlers: JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>): JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>;
141
+ /**
142
+ * Assemble the router, guards, and job handlers into the api object.
143
+ */
144
+ api(options: {
145
+ router: Router<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>;
146
+ } & (string extends keyof Schemes ? {
147
+ guards?: undefined;
148
+ } : {
149
+ guards: NoInfer<GuardsForSchemes<Schemes>>;
150
+ }) & (string extends keyof J ? {
151
+ jobs?: undefined;
152
+ } : {
153
+ jobs: NoInfer<JobsRouter<ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>>>;
154
+ }) & (string extends keyof RequestContext ? {
155
+ requestContext?: undefined;
156
+ } : {
157
+ requestContext: NoInfer<{ [Name in keyof RequestContext]: RequestContextRun<ExpressHandlerContext> }>;
158
+ }) & (string extends keyof Plugins ? {
159
+ plugins?: undefined;
160
+ } : {
161
+ plugins: PluginImplementations<Plugins, ExpressHandlerContext>;
162
+ })): ExpressApi<R>;
163
+ }
164
+ /**
165
+ * Turn a contract into a server handle: the serving counterpart to `Kizuna`.
166
+ * Keep the instance and use `server.guard` to define guards, `server.router`
167
+ * to write typed handlers, and `server.api` to assemble them.
168
+ *
169
+ * @example
170
+ * const server = new KizunaServer(contract);
171
+ *
172
+ * const requireUser = server.guard('user', ({ bearer, deny }) => {
173
+ * const session = bearer && sessions.get(bearer.token);
174
+ * return session ? { userId: session.userId } : deny(401, 'Unauthorized');
175
+ * });
176
+ *
177
+ * export const api = server.api({
178
+ * router,
179
+ * guards: {
180
+ * user: requireUser,
181
+ * },
182
+ * });
183
+ */
184
+ declare class KizunaServer<const R extends Routes, Schemes extends Record<string, SecurityScheme>, Auth, RequestContext extends Record<string, RequestContextSchema>, Plugins extends ContractPlugins, J extends Jobs = Jobs> implements Server<R, Schemes, Auth, RequestContext, Plugins, J> {
185
+ readonly guard: Server<R, Schemes, Auth, RequestContext, Plugins, J>['guard'];
186
+ readonly requestContext: Server<R, Schemes, Auth, RequestContext, Plugins, J>['requestContext'];
187
+ readonly router: Server<R, Schemes, Auth, RequestContext, Plugins, J>['router'];
188
+ readonly jobs: Server<R, Schemes, Auth, RequestContext, Plugins, J>['jobs'];
189
+ readonly api: Server<R, Schemes, Auth, RequestContext, Plugins, J>['api'];
190
+ constructor(contract: ServerContract<R, Schemes, Auth, RequestContext, Plugins, J>, options?: ServerOptions);
191
+ }
192
+ //#endregion
193
+ export { AppLike, ExpressApi, ExpressHandlerContext, ExpressOptions, JobsRouter, KizunaServer, RouteHandler, Router, Server, mountExpress };
package/dist/index.mjs ADDED
@@ -0,0 +1,155 @@
1
+ import { Router } from "express";
2
+ import { Readable } from "node:stream";
3
+ import { GUARDS_META, JOBS_META, REQUEST_CONTEXT_META, ROUTER_META, SCHEMES_META, assembleApi, createAdapter, jobRouter, jobRoutes, jobRunnerFrom, pluginExportsOf, pluginRouterOf, pluginRoutesOf, renderJsonResult, warnUnsupportedJobOptions } from "@ts-kizuna/core/adapter";
4
+ //#region src/server.ts
5
+ /**
6
+ * Write a web `Response` to a node response. Plugins answer in web terms to stay
7
+ * adapter-agnostic, so the translation belongs here.
8
+ */
9
+ const writeWebResponse = async (response, res) => {
10
+ if (!(response instanceof globalThis.Response)) return;
11
+ res.status(response.status);
12
+ response.headers.forEach((value, name) => res.setHeader(name, value));
13
+ if (!response.body) {
14
+ res.end();
15
+ return;
16
+ }
17
+ Readable.fromWeb(response.body).pipe(res);
18
+ };
19
+ const adapter = createAdapter({
20
+ buildHandlerContext: (adapterRequest, { res }) => ({
21
+ req: adapterRequest.request,
22
+ res
23
+ }),
24
+ respond: (result, { res, next, formatError }) => {
25
+ if (result.kind === "handler-error") {
26
+ next(result.error);
27
+ return;
28
+ }
29
+ if (result.kind === "raw-response") {
30
+ writeWebResponse(result.response, res);
31
+ return;
32
+ }
33
+ if (res.headersSent) return;
34
+ if (result.kind === "not-found" || result.kind === "method-not-allowed") {
35
+ next();
36
+ return;
37
+ }
38
+ const rendered = renderJsonResult(result, formatError, res.req);
39
+ for (const [key, value] of Object.entries(rendered.headers)) res.setHeader(key, value);
40
+ if (rendered.body === void 0) res.status(rendered.status).end();
41
+ else if (rendered.raw) {
42
+ const body = rendered.body;
43
+ res.status(rendered.status).send(typeof body === "string" || Buffer.isBuffer(body) ? body : Buffer.from(body));
44
+ } else res.status(rendered.status).json(rendered.body);
45
+ }
46
+ });
47
+ /**
48
+ * Mount a ts-kizuna API onto an Express app.
49
+ *
50
+ * @example
51
+ * api.mount(app);
52
+ */
53
+ function mountExpress(api, app, options) {
54
+ const guards = api[GUARDS_META];
55
+ const schemes = api[SCHEMES_META];
56
+ const requestContext = api[REQUEST_CONTEXT_META];
57
+ const pluginExports = pluginExportsOf(api);
58
+ const jobsMeta = api[JOBS_META];
59
+ const jobRunner = jobRunnerFrom(jobsMeta);
60
+ const expressRouter = Router();
61
+ const mountRoute = (routeKey, route, routes, router) => {
62
+ expressRouter[route.method.toLowerCase()](route.path, (req, _res, next) => {
63
+ req.kizunaRoute = route;
64
+ next();
65
+ }, async (req, res, next) => {
66
+ const adapterRequest = {
67
+ request: req,
68
+ method: req.method,
69
+ resolution: {
70
+ kind: "pre-resolved",
71
+ routeKey,
72
+ route,
73
+ params: req.params
74
+ },
75
+ query: req.query,
76
+ headers: req.headers,
77
+ readBody: () => req.body
78
+ };
79
+ await adapter.handle({
80
+ routes,
81
+ router,
82
+ request: adapterRequest,
83
+ responseContext: {
84
+ res,
85
+ next,
86
+ formatError: options?.formatError
87
+ },
88
+ guards,
89
+ schemes,
90
+ requestContext,
91
+ pluginExports,
92
+ jobs: jobRunner,
93
+ responseValidation: options?.responseValidation
94
+ });
95
+ });
96
+ };
97
+ const mountLane = (routes, router) => {
98
+ for (const { routeKey, route } of adapter.eachRoute(routes, router)) mountRoute(routeKey, route, routes, router);
99
+ };
100
+ mountLane(api.routes, api[ROUTER_META]);
101
+ mountLane(pluginRoutesOf(api), pluginRouterOf(api));
102
+ if (jobsMeta) {
103
+ const routes = jobRoutes(jobsMeta);
104
+ const router = jobRouter(jobsMeta);
105
+ for (const [routeKey, route] of Object.entries(routes)) mountRoute(routeKey, route, routes, router);
106
+ }
107
+ app.use(expressRouter);
108
+ return expressRouter;
109
+ }
110
+ const createServerSurface = (contract, options) => {
111
+ warnUnsupportedJobOptions(contract.jobs, options?.jobTransport);
112
+ return {
113
+ guard: (_name, run) => run,
114
+ requestContext: (_name, run) => run,
115
+ router: (groupOrRouter, groupRouter) => groupRouter ?? groupOrRouter,
116
+ jobs: (handlers) => handlers,
117
+ api: ({ jobs, ...parts }) => {
118
+ const api = Object.assign(assembleApi(contract, parts), { [JOBS_META]: contract.jobs ? {
119
+ jobs: contract.jobs,
120
+ handlers: jobs ?? {},
121
+ config: contract.jobsConfig,
122
+ transport: options?.jobTransport,
123
+ onError: options?.onJobError
124
+ } : void 0 });
125
+ return Object.assign(api, { mount: (app, mountOptions) => mountExpress(api, app, mountOptions) });
126
+ }
127
+ };
128
+ };
129
+ /**
130
+ * Turn a contract into a server handle: the serving counterpart to `Kizuna`.
131
+ * Keep the instance and use `server.guard` to define guards, `server.router`
132
+ * to write typed handlers, and `server.api` to assemble them.
133
+ *
134
+ * @example
135
+ * const server = new KizunaServer(contract);
136
+ *
137
+ * const requireUser = server.guard('user', ({ bearer, deny }) => {
138
+ * const session = bearer && sessions.get(bearer.token);
139
+ * return session ? { userId: session.userId } : deny(401, 'Unauthorized');
140
+ * });
141
+ *
142
+ * export const api = server.api({
143
+ * router,
144
+ * guards: {
145
+ * user: requireUser,
146
+ * },
147
+ * });
148
+ */
149
+ var KizunaServer = class {
150
+ constructor(contract, options) {
151
+ Object.assign(this, createServerSurface(contract, options));
152
+ }
153
+ };
154
+ //#endregion
155
+ export { KizunaServer, mountExpress };
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "@ts-kizuna/express",
3
+ "version": "1.49.5",
4
+ "description": "Express 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
+ "express",
15
+ "adapter",
16
+ "server"
17
+ ],
18
+ "license": "MIT",
19
+ "homepage": "https://ts-kizuna.com/docs/adapters/express",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/ts-kizuna/kizuna.git",
23
+ "directory": "packages/express"
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
+ "express": "^5.0.0",
59
+ "zod": "^4.0.0",
60
+ "@ts-kizuna/core": "1.49.5"
61
+ },
62
+ "devDependencies": {
63
+ "@types/express": "^5.0.0",
64
+ "express": "^5.0.0",
65
+ "tsdown": "^0.21.0",
66
+ "typescript": "^5.6.3",
67
+ "zod": "^4.0.0",
68
+ "@ts-kizuna/core": "1.49.5"
69
+ },
70
+ "scripts": {
71
+ "build": "tsdown src/index.ts --format esm,cjs --dts --clean --external @ts-kizuna/core --external express --external zod",
72
+ "typecheck": "tsc --noEmit"
73
+ }
74
+ }