@rexeus/typeweaver-hono 0.0.3 โ†’ 0.1.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,61 +1,133 @@
1
- # @rexeus/typeweaver-hono
1
+ # ๐Ÿงตโœจ @rexeus/typeweaver-hono
2
2
 
3
- TypeWeaver plugin for generating type-safe Hono routers from HTTP operation definitions.
3
+ [![npm version](https://img.shields.io/npm/v/@rexeus/typeweaver-hono.svg)](https://www.npmjs.com/package/@rexeus/typeweaver-hono)
4
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
4
6
 
5
- ## Overview
7
+ Typeweaver is a type-safe HTTP API framework built for API-first development with a focus on
8
+ developer experience. Use typeweaver to specify your HTTP APIs in TypeScript and Zod, and generate
9
+ clients, validators, routers, and more โœจ
6
10
 
7
- This plugin generates Hono router classes that automatically handle request validation, type-safe
8
- routing, and error responses. Each entity gets its own router class extending `TypeweaverHono` with
9
- full TypeScript type inference.
11
+ ## ๐Ÿ“ Hono Plugin
10
12
 
11
- ## Installation
13
+ This plugin generates type-safe Hono routers from your typeweaver API definitions. For each
14
+ resource, it produces a `<ResourceName>Hono` router class that sets up the routes, validates
15
+ requests via the generated validators, and wires your handler methods with full type safety.
12
16
 
13
- ```bash
14
- npm install @rexeus/typeweaver-hono
15
- ```
17
+ ---
16
18
 
17
- ## Usage
19
+ ## ๐Ÿ“ฅ Installation
18
20
 
19
21
  ```bash
20
- # Via CLI
21
- npx typeweaver generate --plugins hono --input ./definitions --output ./generated
22
+ # Install the CLI and the plugin as a dev dependency
23
+ npm install -D @rexeus/typeweaver @rexeus/typeweaver-hono
22
24
 
23
- # Via config file
24
- npx typeweaver generate --config ./typeweaver.config.js
25
+ # Install the runtime as a dependency
26
+ npm install @rexeus/typeweaver-core
25
27
  ```
26
28
 
27
- ```javascript
28
- // typeweaver.config.js
29
- export default {
30
- input: "./api/definitions",
31
- output: "./api/generated",
32
- plugins: ["hono"],
33
- };
34
- ```
29
+ ## ๐Ÿ’ก How to use
35
30
 
36
- ## Example
37
-
38
- ## Features
31
+ ```bash
32
+ npx typeweaver generate --input ./api/definition --output ./api/generated --plugins hono
33
+ ```
39
34
 
40
- - **Type-safe route handlers** - Full TypeScript inference for requests and responses
41
- - **Automatic request validation** - Built-in validation using generated validators
42
- - **Configurable error handling** - Customize validation and error responses
43
- - **Pure Hono compatibility** - Works with all Hono middleware and features
35
+ More on the CLI in [@rexeus/typeweaver](https://github.com/rexeus/typeweaver/tree/main/packages/cli/README.md#๏ธ-cli).
36
+
37
+ ## ๐Ÿ“‚ Generated Output
38
+
39
+ For each resource (e.g., `Todo`) this plugin generates a Hono router class, which handles the
40
+ routing and request validation for all operations of the resource. This Hono router class can then
41
+ be easily integrated into your Hono application.
42
+
43
+ Generated files are like `<ResourceName>Hono.ts` โ€“ e.g. `TodoHono.ts`.
44
+
45
+ ## ๐Ÿš€ Usage
46
+
47
+ Implement your handlers and mount the generated router in a Hono app.
48
+
49
+ ```ts
50
+ // api/user-handlers.ts
51
+ import type { Context } from "hono";
52
+ import { HttpStatusCode } from "@rexeus/typeweaver-core";
53
+ import type { IGetUserRequest, GetUserResponse, UserNotFoundErrorResponse } from "./generated";
54
+ import { GetUserSuccessResponse } from "./generated";
55
+
56
+ export class UserHandlers implements UserApiHandler {
57
+ async handleGetUserRequest(request: IGetUserRequest, context: Context): Promise<GetUserResponse> {
58
+ // Symbolic database fetch
59
+ const databaseResult = {} as any;
60
+ if (!databaseResult) {
61
+ // Will be properly handled by the generated router and returned as a 404 response
62
+ return new UserNotFoundErrorResponse({
63
+ statusCode: HttpStatusCode.NotFound,
64
+ header: { "Content-Type": "application/json" },
65
+ body: { message: "User not found" },
66
+ });
67
+ }
68
+
69
+ return new GetUserSuccessResponse({
70
+ statusCode: HttpStatusCode.OK,
71
+ header: { "Content-Type": "application/json" },
72
+ body: { id: request.param.userId, name: "Jane", email: "jane@example.com" },
73
+ });
74
+ },
75
+ // Implement other operation handlers: handleCreateUserRequest, ...
76
+ }
77
+ ```
44
78
 
45
- ## Configuration Options
79
+ ```ts
80
+ // api/server.ts
81
+ import { serve } from "@hono/node-server";
82
+ import { Hono } from "hono";
83
+ import { UserHono } from "./generated";
84
+ import { UserHandlers } from "./user-handlers";
85
+
86
+ const app = new Hono();
87
+ const userHandlers = new UserHandlers();
88
+
89
+ // Configure the generated router
90
+ const userRouter = new UserHono({
91
+ requestHandlers: userHandlers,
92
+ validateRequests: true, // default, validates requests
93
+ handleValidationErrors: true, // default: returns 400 with issues
94
+ handleHttpResponseErrors: true, // default: returns thrown HttpResponse as-is
95
+ handleUnknownErrors: true, // default: returns 500
96
+ });
46
97
 
47
- ```typescript
48
- new ProjectHono({
49
- requestHandlers: handlers,
98
+ // Mount the router into your Hono app
99
+ app.route("/", userRouter);
50
100
 
51
- // Optional configurations, for example:
52
- validateRequests: false, // Disable automatic validation
53
- handleValidationErrors: false, // Let validation errors bubble up
54
- handleHttpResponseErrors: true, // Handle thrown HttpResponse errors
55
- handleUnknownErrors: customHandler, // Custom error handler function
101
+ serve({ fetch: app.fetch, port: 3000 }, () => {
102
+ console.log("Hono server listening on http://localhost:3000");
56
103
  });
57
104
  ```
58
105
 
59
- ## License
60
-
61
- ISC ยฉ Dennis Wentzien 2025
106
+ ### โš™๏ธ Configuration
107
+
108
+ `TypeweaverHonoOptions<RequestHandlers>`
109
+
110
+ - `requestHandlers`: object implementing the generated `<ResourceName>ApiHandler` interface
111
+ - `validateRequests` (default: `true`): enable/disable request validation
112
+ - `handleValidationErrors`: `true` | `false` | `(err, c) => IHttpResponse`,
113
+ - If `true` (default), returns `400 Bad Request` with validation issues in the body
114
+ - If `false`, lets the error propagate
115
+ - If function, calls the function with the error and context, expects an `IHttpResponse` to
116
+ return, so you can customize the response in the way you want
117
+ - `handleHttpResponseErrors`: `true` | `false` | `(err, c) => IHttpResponse`
118
+ - If `true` (default), returns thrown `HttpResponse` as-is, they will be sent as the response
119
+ - If `false`, lets the error propagate, which will likely result in a `500 Internal Server Error`
120
+ - If function, calls the function with the error and context, expects an `IHttpResponse` to
121
+ return, so you can customize the response in the way you want
122
+ - `handleUnknownErrors`: `true` | `false` | `(err, c) => IHttpResponse`
123
+ - If `true` (default), returns `500 Internal Server Error` with a generic message
124
+ - If `false`, lets the error propagate and the Hono app can handle it (e.g., via middleware)
125
+ - If function, calls the function with the error and context, expects an `IHttpResponse` to
126
+ return, so you can customize the response in the way you want
127
+
128
+ You can also pass standard Hono options (e.g. `strict`, `getPath`, etc.) through the same options
129
+ object.
130
+
131
+ ## ๐Ÿ“„ License
132
+
133
+ Apache 2.0 ยฉ Dennis Wentzien 2025
package/dist/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2025 Dennis Wentzien
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/dist/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Copyright 2025 Dennis Wentzien
2
+
3
+ This project is licensed under the Apache License, Version 2.0
4
+ See LICENSE file for details.
package/dist/index.js CHANGED
@@ -1,25 +1,31 @@
1
+ import path$1 from 'path';
2
+ import { fileURLToPath as fileURLToPath$1 } from 'url';
1
3
  import { BasePlugin } from '@rexeus/typeweaver-gen';
2
- import Case from 'case';
3
4
  import path from 'node:path';
4
5
  import { fileURLToPath } from 'node:url';
5
- import { fileURLToPath as fileURLToPath$1 } from 'url';
6
- import path$1 from 'path';
6
+ import { HttpMethod } from '@rexeus/typeweaver-core';
7
+ import Case from 'case';
7
8
 
8
9
  class HonoRouterGenerator {
9
10
  static generate(context) {
10
11
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
11
12
  const templateFile = path.join(__dirname, "templates", "HonoRouter.ejs");
12
- for (const [entityName, operationResources] of Object.entries(
13
+ for (const [entityName, entityResource] of Object.entries(
13
14
  context.resources.entityResources
14
15
  )) {
15
- this.writeHonoRouter(entityName, templateFile, operationResources, context);
16
+ this.writeHonoRouter(
17
+ entityName,
18
+ templateFile,
19
+ entityResource.operations,
20
+ context
21
+ );
16
22
  }
17
23
  }
18
24
  static writeHonoRouter(entityName, templateFile, operationResources, context) {
19
25
  const pascalCaseEntityName = Case.pascal(entityName);
20
26
  const outputDir = path.join(context.outputDir, entityName);
21
27
  const outputPath = path.join(outputDir, `${pascalCaseEntityName}Hono.ts`);
22
- const operations = operationResources.map((resource) => this.createOperationData(resource));
28
+ const operations = operationResources.filter((resource) => resource.definition.method !== HttpMethod.HEAD).map((resource) => this.createOperationData(resource)).sort((a, b) => this.compareRoutes(a, b));
23
29
  const content = context.renderTemplate(templateFile, {
24
30
  coreDir: path.relative(outputDir, context.outputDir),
25
31
  entityName,
@@ -40,6 +46,38 @@ class HonoRouterGenerator {
40
46
  path: resource.definition.path
41
47
  };
42
48
  }
49
+ static compareRoutes(a, b) {
50
+ const aSegments = a.path.split("/").filter((s) => s);
51
+ const bSegments = b.path.split("/").filter((s) => s);
52
+ if (aSegments.length !== bSegments.length) {
53
+ return aSegments.length - bSegments.length;
54
+ }
55
+ for (let i = 0; i < aSegments.length; i++) {
56
+ const aSegment = aSegments[i];
57
+ const bSegment = bSegments[i];
58
+ const aIsParam = aSegment.startsWith(":");
59
+ const bIsParam = bSegment.startsWith(":");
60
+ if (aIsParam !== bIsParam) {
61
+ return aIsParam ? 1 : -1;
62
+ }
63
+ if (aSegment !== bSegment) {
64
+ return aSegment.localeCompare(bSegment);
65
+ }
66
+ }
67
+ return this.getMethodPriority(a.method) - this.getMethodPriority(b.method);
68
+ }
69
+ static getMethodPriority(method) {
70
+ const priorities = {
71
+ GET: 1,
72
+ POST: 2,
73
+ PUT: 3,
74
+ PATCH: 4,
75
+ DELETE: 5,
76
+ OPTIONS: 6,
77
+ HEAD: 7
78
+ };
79
+ return priorities[method] ?? 999;
80
+ }
43
81
  }
44
82
 
45
83
  const __dirname = path$1.dirname(fileURLToPath$1(import.meta.url));
@@ -1,13 +1,19 @@
1
+ /**
2
+ * This file was automatically generated by typeweaver.
3
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
4
+ *
5
+ * @generated by @rexeus/typeweaver
6
+ */
7
+
1
8
  import type {
2
9
  HttpMethod,
3
- IHttpRequest,
4
- IHttpResponse,
10
+ IHttpBody,
5
11
  IHttpHeader,
6
12
  IHttpQuery,
7
- IHttpBody,
13
+ IHttpRequest,
14
+ IHttpResponse,
8
15
  } from "@rexeus/typeweaver-core";
9
16
  import { HttpAdapter } from "./HttpAdapter";
10
- import { normalizeHeaders } from "./normalizeHeaders";
11
17
 
12
18
  /**
13
19
  * Adapter for converting between Fetch API Request/Response objects
@@ -79,11 +85,13 @@ export class FetchApiAdapter extends HttpAdapter<Request, Response> {
79
85
  }
80
86
 
81
87
  private extractHeaders(headers: Headers): IHttpHeader {
88
+ if (!headers) return undefined;
82
89
  const result: Record<string, string | string[]> = {};
83
90
  headers.forEach((value, key) => {
91
+ if (!value) return;
84
92
  this.addMultiValue(result, key, value);
85
93
  });
86
- return normalizeHeaders(result);
94
+ return Object.keys(result).length > 0 ? result : undefined;
87
95
  }
88
96
 
89
97
  private extractQueryParams(url: URL): IHttpQuery {
@@ -1,7 +1,14 @@
1
- import type { Context } from "hono";
1
+ /**
2
+ * This file was automatically generated by typeweaver.
3
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
4
+ *
5
+ * @generated by @rexeus/typeweaver
6
+ */
7
+
2
8
  import type { IHttpRequest, IHttpResponse } from "@rexeus/typeweaver-core";
3
9
  import { FetchApiAdapter } from "./FetchApiAdapter";
4
10
  import { HttpAdapter } from "./HttpAdapter";
11
+ import type { Context } from "hono";
5
12
 
6
13
  /**
7
14
  * Adapter for converting between Hono's Context and the core HTTP types.
@@ -1,3 +1,10 @@
1
+ /**
2
+ * This file was automatically generated by typeweaver.
3
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
4
+ *
5
+ * @generated by @rexeus/typeweaver
6
+ */
7
+
1
8
  import type { IHttpRequest, IHttpResponse } from "@rexeus/typeweaver-core";
2
9
  import type { Context } from "hono";
3
10
 
@@ -1,3 +1,10 @@
1
+ /**
2
+ * This file was automatically generated by typeweaver.
3
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
4
+ *
5
+ * @generated by @rexeus/typeweaver
6
+ */
7
+
1
8
  import type { IHttpRequest, IHttpResponse } from "@rexeus/typeweaver-core";
2
9
 
3
10
  /**
@@ -1,13 +1,20 @@
1
- import { Hono, type Context } from "hono";
2
- import {
3
- HttpResponse,
4
- RequestValidationError,
5
- type IHttpRequest,
6
- type IHttpResponse,
7
- type IRequestValidator,
1
+ /**
2
+ * This file was automatically generated by typeweaver.
3
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
4
+ *
5
+ * @generated by @rexeus/typeweaver
6
+ */
7
+
8
+ import { HttpResponse, RequestValidationError } from "@rexeus/typeweaver-core";
9
+ import { Hono } from "hono";
10
+ import type {
11
+ IHttpRequest,
12
+ IHttpResponse,
13
+ IRequestValidator,
8
14
  } from "@rexeus/typeweaver-core";
9
15
  import { HonoAdapter } from "./HonoAdapter";
10
16
  import type { HonoRequestHandler } from "./HonoRequestHandler";
17
+ import type { Context } from "hono";
11
18
  import type { HonoOptions } from "hono/hono-base";
12
19
  import type { BlankEnv, BlankSchema, Env, Schema } from "hono/types";
13
20
 
@@ -95,9 +102,9 @@ export type TypeweaverHonoOptions<
95
102
  };
96
103
 
97
104
  /**
98
- * Abstract base class for TypeWeaver-generated Hono routers.
105
+ * Abstract base class for typeweaver-generated Hono routers.
99
106
  *
100
- * Extends Hono with TypeWeaver-specific features:
107
+ * Extends Hono with typeweaver-specific features:
101
108
  * - Automatic request validation using generated validators
102
109
  * - Configurable error handling for validation, HTTP, and unknown errors
103
110
  * - Type-safe request/response handling with adapters
@@ -114,7 +121,7 @@ export abstract class TypeweaverHono<
114
121
  HonoBasePath extends string = "/",
115
122
  > extends Hono<HonoEnv, HonoSchema, HonoBasePath> {
116
123
  /**
117
- * Adapter for converting between Hono and TypeWeaver request/response formats.
124
+ * Adapter for converting between Hono and typeweaver request/response formats.
118
125
  */
119
126
  protected readonly adapter = new HonoAdapter();
120
127
 
@@ -142,15 +149,13 @@ export abstract class TypeweaverHono<
142
149
  validation: (error: RequestValidationError): IHttpResponse => ({
143
150
  statusCode: 400,
144
151
  body: {
145
- error: {
146
- code: "VALIDATION_ERROR",
147
- message: error.message,
148
- details: {
149
- headers: error.headerIssues,
150
- body: error.bodyIssues,
151
- query: error.queryIssues,
152
- params: error.pathParamIssues,
153
- },
152
+ code: "VALIDATION_ERROR",
153
+ message: error.message,
154
+ issues: {
155
+ header: error.headerIssues,
156
+ body: error.bodyIssues,
157
+ query: error.queryIssues,
158
+ param: error.pathParamIssues,
154
159
  },
155
160
  },
156
161
  }),
@@ -160,10 +165,8 @@ export abstract class TypeweaverHono<
160
165
  unknown: (): IHttpResponse => ({
161
166
  statusCode: 500,
162
167
  body: {
163
- error: {
164
- code: "INTERNAL_SERVER_ERROR",
165
- message: "An unexpected error occurred.",
166
- },
168
+ code: "INTERNAL_SERVER_ERROR",
169
+ message: "An unexpected error occurred.",
167
170
  },
168
171
  }),
169
172
  };
@@ -209,7 +212,10 @@ export abstract class TypeweaverHono<
209
212
  },
210
213
  };
211
214
 
212
- this.registerErrorHandler();
215
+ // TODO: native onError handler of hono is currently not working in this context
216
+ // -> only validation errors were caught, other errors were not handled
217
+ // -> if this is fixed, the hono onError handler should be used instead of our try/catch logic
218
+ // this.registerErrorHandler();
213
219
  }
214
220
 
215
221
  /**
@@ -219,7 +225,7 @@ export abstract class TypeweaverHono<
219
225
  * @param defaultHandler - Default handler to use when option is true
220
226
  * @returns Resolved handler function or undefined if disabled
221
227
  */
222
- private resolveErrorHandler<T extends Function>(
228
+ private resolveErrorHandler<T extends (...args: any[]) => any>(
223
229
  option: T | boolean | undefined,
224
230
  defaultHandler: T
225
231
  ): T | undefined {
@@ -233,37 +239,64 @@ export abstract class TypeweaverHono<
233
239
  * Processes errors in order: validation, HTTP response, unknown.
234
240
  */
235
241
  protected registerErrorHandler(): void {
236
- this.onError(async (error, context) => {
237
- // Handle validation errors
238
- if (
239
- error instanceof RequestValidationError &&
240
- this.config.errorHandlers.validation
241
- ) {
242
- return this.adapter.toResponse(
243
- await this.config.errorHandlers.validation(error, context)
244
- );
245
- }
242
+ this.onError(this.handleError.bind(this));
243
+ }
244
+
245
+ /**
246
+ * Safely executes an error handler and returns null if it fails.
247
+ * This allows for graceful fallback to the next handler in the chain.
248
+ *
249
+ * @param handlerFn - Function that executes the error handler
250
+ * @returns Response if successful, null if handler throws
251
+ */
252
+ private async safelyExecuteHandler(
253
+ handlerFn: () => Promise<IHttpResponse> | IHttpResponse
254
+ ): Promise<Response | null> {
255
+ try {
256
+ const response = await handlerFn();
257
+ return this.adapter.toResponse(response);
258
+ } catch {
259
+ // Handler execution failed, return null to continue to next handler
260
+ return null;
261
+ }
262
+ }
263
+
264
+ protected async handleError(
265
+ error: unknown,
266
+ context: Context
267
+ ): Promise<Response> {
268
+ // Handle validation errors
269
+ if (
270
+ error instanceof RequestValidationError &&
271
+ this.config.errorHandlers.validation
272
+ ) {
273
+ const response = await this.safelyExecuteHandler(() =>
274
+ this.config.errorHandlers.validation!(error, context)
275
+ );
276
+ if (response) return response;
277
+ }
246
278
 
247
- // Handle HTTP response errors
248
- if (
249
- error instanceof HttpResponse &&
250
- this.config.errorHandlers.httpResponse
251
- ) {
252
- return this.adapter.toResponse(
253
- await this.config.errorHandlers.httpResponse(error, context)
254
- );
255
- }
279
+ // Handle HTTP response errors
280
+ if (
281
+ error instanceof HttpResponse &&
282
+ this.config.errorHandlers.httpResponse
283
+ ) {
284
+ const response = await this.safelyExecuteHandler(() =>
285
+ this.config.errorHandlers.httpResponse!(error, context)
286
+ );
287
+ if (response) return response;
288
+ }
256
289
 
257
- // Handle unknown errors
258
- if (this.config.errorHandlers.unknown) {
259
- return this.adapter.toResponse(
260
- await this.config.errorHandlers.unknown(error, context)
261
- );
262
- }
290
+ // Handle unknown errors
291
+ if (this.config.errorHandlers.unknown) {
292
+ const response = await this.safelyExecuteHandler(() =>
293
+ this.config.errorHandlers.unknown!(error, context)
294
+ );
295
+ if (response) return response;
296
+ }
263
297
 
264
- // Default: re-throw
265
- throw error;
266
- });
298
+ // Default: re-throw
299
+ throw error;
267
300
  }
268
301
 
269
302
  /**
@@ -282,14 +315,18 @@ export abstract class TypeweaverHono<
282
315
  validator: IRequestValidator,
283
316
  handler: HonoRequestHandler<TRequest, TResponse>
284
317
  ): Promise<Response> {
285
- const httpRequest = await this.adapter.toRequest(context);
318
+ try {
319
+ const httpRequest = await this.adapter.toRequest(context);
286
320
 
287
- // Conditionally validate
288
- const validatedRequest = this.config.validateRequests
289
- ? (validator.validate(httpRequest) as TRequest)
290
- : (httpRequest as TRequest);
321
+ // Conditionally validate
322
+ const validatedRequest = this.config.validateRequests
323
+ ? (validator.validate(httpRequest) as TRequest)
324
+ : (httpRequest as TRequest);
291
325
 
292
- const httpResponse = await handler(validatedRequest, context);
293
- return this.adapter.toResponse(httpResponse);
326
+ const httpResponse = await handler(validatedRequest, context);
327
+ return this.adapter.toResponse(httpResponse);
328
+ } catch (error) {
329
+ return this.handleError(error, context);
330
+ }
294
331
  }
295
332
  }
package/dist/lib/index.ts CHANGED
@@ -1,3 +1,10 @@
1
+ /**
2
+ * This file was automatically generated by typeweaver.
3
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
4
+ *
5
+ * @generated by @rexeus/typeweaver
6
+ */
7
+
1
8
  export * from "./TypeweaverHono";
2
9
  export * from "./HonoRequestHandler";
3
10
  export * from "./HonoAdapter";
@@ -1,5 +1,13 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * This file was automatically generated by typeweaver.
4
+ * DO NOT EDIT. Instead, modify the source definition file and generate again.
5
+ *
6
+ * @generated by @rexeus/typeweaver
7
+ */
8
+
1
9
  import type { Context } from "hono";
2
- import { TypeweaverHono, type HonoRequestHandler } from "<%- coreDir %>/lib/hono";
10
+ import { TypeweaverHono, type HonoRequestHandler, type TypeweaverHonoOptions } from "<%- coreDir %>/lib/hono";
3
11
  <% for (const operation of operations) { %>
4
12
  import type { I<%- operation.className %>Request } from "./<%- operation.className %>Request";
5
13
  import { <%- operation.className %>RequestValidator } from "./<%- operation.className %>RequestValidator";
@@ -13,8 +21,8 @@ export type <%- pascalCaseEntityName %>ApiHandler = {
13
21
  };
14
22
 
15
23
  export class <%- pascalCaseEntityName %>Hono extends TypeweaverHono<<%- pascalCaseEntityName %>ApiHandler> {
16
- public constructor(handlers: <%- pascalCaseEntityName %>ApiHandler) {
17
- super({ requestHandlers: handlers });
24
+ public constructor(options: TypeweaverHonoOptions<<%- pascalCaseEntityName %>ApiHandler>) {
25
+ super(options);
18
26
  this.setupRoutes();
19
27
  }
20
28
 
@@ -24,7 +32,7 @@ export class <%- pascalCaseEntityName %>Hono extends TypeweaverHono<<%- pascalCa
24
32
  this.handleRequest(
25
33
  context,
26
34
  new <%- operation.className %>RequestValidator(),
27
- this.requestHandlers.<%- operation.handlerName %>
35
+ this.requestHandlers.<%- operation.handlerName %>.bind(this.requestHandlers)
28
36
  ));
29
37
 
30
38
  <% } %>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rexeus/typeweaver-hono",
3
- "version": "0.0.3",
4
- "description": "Hono router generator plugin for TypeWeaver",
3
+ "version": "0.1.0",
4
+ "description": "Hono router generator plugin for typeweaver",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -14,7 +14,9 @@
14
14
  "files": [
15
15
  "dist",
16
16
  "package.json",
17
- "README.md"
17
+ "README.md",
18
+ "LICENSE",
19
+ "NOTICE"
18
20
  ],
19
21
  "keywords": [
20
22
  "typeweaver",
@@ -24,8 +26,8 @@
24
26
  "api",
25
27
  "http"
26
28
  ],
27
- "author": "Dennis Wentzien <dennis@rexeus.com>",
28
- "license": "ISC",
29
+ "author": "Dennis Wentzien <dw@rexeus.com>",
30
+ "license": "Apache-2.0",
29
31
  "repository": {
30
32
  "type": "git",
31
33
  "url": "git+https://github.com/rexeus/typeweaver.git",
@@ -36,14 +38,15 @@
36
38
  },
37
39
  "homepage": "https://github.com/rexeus/typeweaver#readme",
38
40
  "peerDependencies": {
39
- "hono": "^4.0.0",
40
- "@rexeus/typeweaver-core": "^0.0.3",
41
- "@rexeus/typeweaver-gen": "^0.0.3"
41
+ "hono": "^4.9.7",
42
+ "@rexeus/typeweaver-gen": "^0.1.0",
43
+ "@rexeus/typeweaver-core": "^0.1.0"
42
44
  },
43
45
  "devDependencies": {
44
- "hono": "^4.0.0",
45
- "@rexeus/typeweaver-core": "^0.0.3",
46
- "@rexeus/typeweaver-gen": "^0.0.3"
46
+ "hono": "^4.9.7",
47
+ "test-utils": "file:../test-utils",
48
+ "@rexeus/typeweaver-core": "^0.1.0",
49
+ "@rexeus/typeweaver-gen": "^0.1.0"
47
50
  },
48
51
  "dependencies": {
49
52
  "case": "^1.6.3"
@@ -51,7 +54,8 @@
51
54
  "scripts": {
52
55
  "typecheck": "tsc --noEmit",
53
56
  "format": "prettier --write .",
54
- "build": "pkgroll --clean-dist && cp -r ./src/templates ./dist/templates && cp -r ./src/lib ./dist/lib",
57
+ "build": "pkgroll --clean-dist && cp -r ./src/templates ./dist/templates && cp -r ./src/lib ./dist/lib && cp ../../LICENSE ../../NOTICE ./dist/",
58
+ "test": "vitest --run",
55
59
  "preversion": "npm run build"
56
60
  }
57
61
  }
@@ -1,36 +0,0 @@
1
- import Case from "case";
2
- import type { IHttpHeader } from "@rexeus/typeweaver-core";
3
-
4
- export interface NormalizedHeaders {
5
- [key: string]: string | string[];
6
- }
7
-
8
- export const normalizeHeaders = (
9
- headers: Record<string, string | string[] | undefined> | null
10
- ): IHttpHeader => {
11
- if (!headers) return undefined;
12
-
13
- const result: NormalizedHeaders = {};
14
-
15
- for (const [key, value] of Object.entries(headers)) {
16
- if (value === undefined) continue;
17
-
18
- const processedValue =
19
- typeof value === "string" ? value.split(",").map(v => v.trim()) : value;
20
-
21
- const filteredValue = processedValue.filter(v => v !== "");
22
- if (filteredValue.length === 0) continue;
23
-
24
- const lowerKey = key.toLowerCase();
25
- const headerKey = Case.header(key);
26
-
27
- const finalValue: string | string[] =
28
- filteredValue.length === 1 ? filteredValue[0]! : filteredValue;
29
-
30
- result[lowerKey] = finalValue;
31
- result[headerKey] = finalValue;
32
- result[key] = finalValue;
33
- }
34
-
35
- return Object.keys(result).length > 0 ? result : undefined;
36
- };