@sdk-it/hono 0.46.6 → 0.46.8
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 +42 -0
- package/dist/lib/runtime/index.js +62 -27
- package/dist/lib/runtime/index.js.map +2 -2
- package/dist/lib/runtime/validator.d.ts +17 -22
- package/dist/lib/runtime/validator.d.ts.map +1 -1
- package/package.json +7 -3
- package/src/lib/runtime/index.ts +2 -0
- package/src/lib/runtime/output.ts +121 -0
- package/src/lib/runtime/validator.ts +281 -0
package/README.md
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
Hono runtime middleware and response analysis for SDK-IT.
|
|
4
4
|
|
|
5
|
+
`@sdk-it/hono/runtime` is the canonical home for the shared Hono request
|
|
6
|
+
validator. Import it instead of copying its implementation into an application.
|
|
7
|
+
See the [validator comparison and contract](../../docs/architecture/hono-validator.md)
|
|
8
|
+
for the consolidation decisions and consumer migration notes.
|
|
9
|
+
|
|
5
10
|
See [`@sdk-it/typescript`](../typescript/README.md) for OpenAPI-to-TypeScript
|
|
6
11
|
client generation.
|
|
7
12
|
|
|
@@ -88,6 +93,18 @@ Supported enforced content types are:
|
|
|
88
93
|
|
|
89
94
|
Query and path values arrive as strings. Use Zod coercion when the parsed value
|
|
90
95
|
should be a number, boolean, or another non-string type.
|
|
96
|
+
The query string `"null"` stays a string unless a schema explicitly transforms it.
|
|
97
|
+
Malformed JSON throws an HTTP 400 exception with `api/invalid-json` in its cause.
|
|
98
|
+
Malformed content-type headers return 415 with `api/unsupported-media-type`.
|
|
99
|
+
Selecting a body field from JSON null, an array, or a scalar returns 400 with
|
|
100
|
+
`api/invalid-body`; validate these values through a whole-body schema instead.
|
|
101
|
+
|
|
102
|
+
The selector runs once per request. `c.var.input` contains Zod's parsed output,
|
|
103
|
+
including defaults, transformations, and optional keys.
|
|
104
|
+
|
|
105
|
+
Whole-body selection (`select: payload.body`) works at runtime, including for
|
|
106
|
+
array or nullable schemas. For generated OpenAPI, keep direct field selectors;
|
|
107
|
+
whole-body generation is not supported by the current static analyzer.
|
|
91
108
|
|
|
92
109
|
### Validate file uploads
|
|
93
110
|
|
|
@@ -122,6 +139,31 @@ app.post(
|
|
|
122
139
|
);
|
|
123
140
|
```
|
|
124
141
|
|
|
142
|
+
Repeated form fields are preserved: a single `files` field is a `File`, while
|
|
143
|
+
multiple `files` fields are a `File[]`. A field named `files[]` always produces
|
|
144
|
+
an array and is selected with `payload.body['files[]']`. The same rule applies
|
|
145
|
+
to repeated URL-encoded fields. Use a Zod schema matching the accepted shape.
|
|
146
|
+
|
|
147
|
+
### Parse a schema directly
|
|
148
|
+
|
|
149
|
+
`parse` supports any Zod schema, including unions, arrays, async refinements,
|
|
150
|
+
and transformations:
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
import { parse } from '@sdk-it/hono/runtime';
|
|
154
|
+
|
|
155
|
+
const status = await parse(z.enum(['draft', 'published']), rawStatus);
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Failed validation throws `HTTPException(400)`. Its cause contains `code`,
|
|
159
|
+
`detail`, `errors` grouped by field, and `formErrors` for root-level issues.
|
|
160
|
+
Both error collections contain entries
|
|
161
|
+
with `message`, `code`, and a dot-joined `path`. Applications choose how to
|
|
162
|
+
serialize the exception through their Hono error handler.
|
|
163
|
+
The singular `detail` spelling follows
|
|
164
|
+
[Problem Details (RFC 9457)](https://www.rfc-editor.org/rfc/rfc9457.html#section-3.1.4)
|
|
165
|
+
and .NET's `ProblemDetails.Detail`; the application owns the full response format.
|
|
166
|
+
|
|
125
167
|
### Enforce a content type without validation
|
|
126
168
|
|
|
127
169
|
Use `consume` when a route only needs content-type enforcement:
|
|
@@ -80,7 +80,7 @@ function createOutput(contextFn) {
|
|
|
80
80
|
var output = createOutput(() => getContext());
|
|
81
81
|
|
|
82
82
|
// packages/hono/src/lib/runtime/validator.ts
|
|
83
|
-
import {
|
|
83
|
+
import { safeParse } from "fast-content-type-parse";
|
|
84
84
|
import { createMiddleware } from "hono/factory";
|
|
85
85
|
import { HTTPException } from "hono/http-exception";
|
|
86
86
|
import z from "zod";
|
|
@@ -97,7 +97,7 @@ function validate(expectedContentTypeOrSelector, selector) {
|
|
|
97
97
|
message: "Unsupported Media Type",
|
|
98
98
|
cause: {
|
|
99
99
|
code: "api/unsupported-media-type",
|
|
100
|
-
|
|
100
|
+
detail: `GET requests cannot have a content type header`
|
|
101
101
|
}
|
|
102
102
|
});
|
|
103
103
|
}
|
|
@@ -108,40 +108,57 @@ function validate(expectedContentTypeOrSelector, selector) {
|
|
|
108
108
|
let body = null;
|
|
109
109
|
switch (contentType?.type) {
|
|
110
110
|
case "application/json":
|
|
111
|
-
|
|
111
|
+
try {
|
|
112
|
+
body = await c.req.json();
|
|
113
|
+
} catch {
|
|
114
|
+
throw new HTTPException(400, {
|
|
115
|
+
message: "Invalid JSON body",
|
|
116
|
+
cause: {
|
|
117
|
+
code: "api/invalid-json",
|
|
118
|
+
detail: "Request body must be valid JSON."
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
}
|
|
112
122
|
break;
|
|
113
123
|
case "application/x-www-form-urlencoded":
|
|
114
124
|
case "multipart/form-data":
|
|
115
|
-
body = await c.req.parseBody();
|
|
125
|
+
body = await c.req.parseBody({ all: true });
|
|
116
126
|
break;
|
|
117
127
|
default:
|
|
118
128
|
body = {};
|
|
119
129
|
}
|
|
130
|
+
const selectedBody = body !== null && typeof body === "object" && !Array.isArray(body) ? body : new Proxy(
|
|
131
|
+
{},
|
|
132
|
+
{
|
|
133
|
+
get() {
|
|
134
|
+
throw new HTTPException(400, {
|
|
135
|
+
message: "Invalid request body",
|
|
136
|
+
cause: {
|
|
137
|
+
code: "api/invalid-body",
|
|
138
|
+
detail: "Request body must be an object when selecting fields."
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
);
|
|
120
144
|
const payload = {
|
|
121
|
-
body,
|
|
145
|
+
body: selectedBody,
|
|
122
146
|
query: c.req.query(),
|
|
123
147
|
queries: c.req.queries(),
|
|
124
148
|
params: c.req.param(),
|
|
125
|
-
headers:
|
|
126
|
-
Object.entries(c.req.header()).map(([k, v]) => [k, v ?? ""])
|
|
127
|
-
)
|
|
149
|
+
headers: c.req.header()
|
|
128
150
|
};
|
|
129
151
|
const config = _selector(payload);
|
|
130
152
|
const schema = z.object(
|
|
131
|
-
Object.
|
|
132
|
-
(
|
|
133
|
-
acc[key] = value.against;
|
|
134
|
-
return acc;
|
|
135
|
-
},
|
|
136
|
-
{}
|
|
153
|
+
Object.fromEntries(
|
|
154
|
+
Object.entries(config).map(([key, value]) => [key, value.against])
|
|
137
155
|
)
|
|
138
156
|
);
|
|
139
|
-
const input = Object.
|
|
140
|
-
(
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
{}
|
|
157
|
+
const input = Object.fromEntries(
|
|
158
|
+
Object.entries(config).map(([key, value]) => [
|
|
159
|
+
key,
|
|
160
|
+
value.select === selectedBody ? body : value.select
|
|
161
|
+
])
|
|
145
162
|
);
|
|
146
163
|
const parsed = await parse(schema, input);
|
|
147
164
|
c.set("input", parsed);
|
|
@@ -151,16 +168,21 @@ function validate(expectedContentTypeOrSelector, selector) {
|
|
|
151
168
|
async function parse(schema, input) {
|
|
152
169
|
const result = await schema.safeParseAsync(input);
|
|
153
170
|
if (!result.success) {
|
|
171
|
+
const { fieldErrors, formErrors } = z.flattenError(
|
|
172
|
+
result.error,
|
|
173
|
+
(issue) => ({
|
|
174
|
+
message: issue.message,
|
|
175
|
+
code: issue.code,
|
|
176
|
+
path: issue.path.join(".")
|
|
177
|
+
})
|
|
178
|
+
);
|
|
154
179
|
const error = new HTTPException(400, {
|
|
155
180
|
message: "Validation failed",
|
|
156
181
|
cause: {
|
|
157
182
|
code: "api/validation-failed",
|
|
158
183
|
detail: "The input data is invalid",
|
|
159
|
-
errors:
|
|
160
|
-
|
|
161
|
-
code: issue.code,
|
|
162
|
-
path: issue.path.join(".")
|
|
163
|
-
})).fieldErrors
|
|
184
|
+
errors: fieldErrors,
|
|
185
|
+
formErrors
|
|
164
186
|
}
|
|
165
187
|
});
|
|
166
188
|
throw error;
|
|
@@ -174,13 +196,26 @@ var consume = (contentType) => {
|
|
|
174
196
|
await next();
|
|
175
197
|
});
|
|
176
198
|
};
|
|
199
|
+
function parseContentType(header) {
|
|
200
|
+
const contentType = safeParse(header);
|
|
201
|
+
if (!contentType.type) {
|
|
202
|
+
throw new HTTPException(415, {
|
|
203
|
+
message: "Unsupported Media Type",
|
|
204
|
+
cause: {
|
|
205
|
+
code: "api/unsupported-media-type",
|
|
206
|
+
detail: "Invalid content type header"
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
return contentType;
|
|
211
|
+
}
|
|
177
212
|
function verifyContentType(actual, expected) {
|
|
178
213
|
if (!actual) {
|
|
179
214
|
throw new HTTPException(415, {
|
|
180
215
|
message: "Unsupported Media Type",
|
|
181
216
|
cause: {
|
|
182
217
|
code: "api/unsupported-media-type",
|
|
183
|
-
|
|
218
|
+
detail: "Missing content type header"
|
|
184
219
|
}
|
|
185
220
|
});
|
|
186
221
|
}
|
|
@@ -190,7 +225,7 @@ function verifyContentType(actual, expected) {
|
|
|
190
225
|
message: "Unsupported Media Type",
|
|
191
226
|
cause: {
|
|
192
227
|
code: "api/unsupported-media-type",
|
|
193
|
-
|
|
228
|
+
detail: `Expected content type: ${expected}, but got: ${incomingContentType}`
|
|
194
229
|
}
|
|
195
230
|
});
|
|
196
231
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/runtime/output.ts", "../../../src/lib/runtime/validator.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Context } from 'hono';\nimport { getContext } from 'hono/context-storage';\nimport type {\n ContentfulStatusCode,\n RedirectStatusCode,\n} from 'hono/utils/http-status';\n\ntype Data = any;\nfunction send(\n context: Context,\n value: Data | undefined | null,\n status: ContentfulStatusCode,\n headers?: Readonly<Record<string, string>>,\n) {\n if (value === undefined || value === null) {\n return context.body(null, status, headers);\n }\n const responseHeaders = { ...headers };\n responseHeaders['Content-Type'] ??= 'application/json';\n if (responseHeaders['Content-Type'].includes('application/json')) {\n return context.body(JSON.stringify(value), status, responseHeaders);\n }\n return context.body(value, status, responseHeaders);\n}\n\nexport function createOutput(contextFn: () => Context) {\n return {\n nocontent() {\n const context = contextFn();\n return context.body(null, 204, {});\n },\n ok(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 200, headers);\n },\n created(\n valueOrUri: string | Data,\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n if (typeof valueOrUri === 'string') {\n // If no content is provided, we send null\n return send(contextFn(), value, 201, {\n Location: valueOrUri,\n ...(headers || {}),\n });\n } else {\n // valueOrUri is the data\n return send(contextFn(), valueOrUri, 201, headers);\n }\n },\n redirect(uri: string | URL, statusCode?: unknown) {\n const context = contextFn();\n return context.redirect(\n uri.toString(),\n (statusCode as RedirectStatusCode) ?? undefined,\n );\n },\n attachment(buffer: Buffer, filename: string, mimeType: string) {\n const context = contextFn();\n // https://github.com/honojs/hono/issues/3720\n return context.body(buffer as never, 200, {\n 'Content-Type': mimeType,\n 'Content-Disposition': `attachment; filename=\"${filename}\"`,\n 'Content-Length': buffer.length.toString(),\n });\n },\n badRequest(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 400, headers);\n },\n unauthorized(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 401, headers);\n },\n forbidden(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 403, headers);\n },\n notFound(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 404, headers);\n },\n notImplemented(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 501, headers);\n },\n accepted(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 202, headers);\n },\n conflict(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 409, headers);\n },\n unprocessableEntity(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 422, headers);\n },\n internalServerError(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 500, headers);\n },\n serviceUnavailable(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 503, headers);\n },\n };\n}\n\nexport const output = createOutput(() => getContext());\n", "import { parse as parseContentType } from 'fast-content-type-parse';\nimport type { MiddlewareHandler, ValidationTargets } from 'hono';\nimport { createMiddleware } from 'hono/factory';\nimport { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\ntype ContentType =\n | 'application/json'\n | 'application/x-www-form-urlencoded'\n | 'multipart/form-data'\n | 'text/plain';\n\n// z.ZodType<any> mirrors zod v3's ZodTypeAny: with the default `unknown`\n// output, concrete middlewares stop being assignable to\n// ValidateMiddleware<ValidatorConfig>.\n\ntype ValidatorConfig = Record<\n string,\n { select: unknown; against: z.ZodType<any> }\n>;\n\ntype ExtractInput<T extends ValidatorConfig> = {\n [K in keyof T]: z.infer<T[K]['against']>;\n};\n\ntype HasUndefined<T> = undefined extends T ? true : false;\n\ntype InferTarget<\n T extends ValidatorConfig,\n S,\n Target extends keyof ValidationTargets,\n> = {\n [K in keyof T as T[K]['select'] extends S ? K : never]: HasUndefined<\n z.infer<T[K]['against']>\n > extends true\n ? z.infer<T[K]['against']> | undefined\n : z.infer<T[K]['against']> extends ValidationTargets[Target]\n ? z.infer<T[K]['against']>\n : z.infer<T[K]['against']>;\n};\n\ntype InferIn<T extends ValidatorConfig> = (keyof InferTarget<\n T,\n QuerySelect | QueriesSelect,\n 'query'\n> extends never\n ? never\n : { query: InferTarget<T, QuerySelect | QueriesSelect, 'query'> }) &\n (keyof InferTarget<T, BodySelect, 'json'> extends never\n ? never\n : { json: InferTarget<T, BodySelect, 'json'> }) &\n (keyof InferTarget<T, ParamsSelect, 'param'> extends never\n ? never\n : { param: InferTarget<T, ParamsSelect, 'param'> }) &\n (keyof InferTarget<T, HeadersSelect, 'header'> extends never\n ? never\n : { header: InferTarget<T, HeadersSelect, 'header'> }) &\n (keyof InferTarget<T, CookieSelect, 'cookie'> extends never\n ? never\n : { cookie: InferTarget<T, CookieSelect, 'cookie'> });\n\n// Marker classes\nclass BodySelect {\n #private = 0;\n}\nclass QuerySelect {\n #private = 0;\n}\nclass QueriesSelect {\n #private = 0;\n}\nclass ParamsSelect {\n #private = 0;\n}\nclass HeadersSelect {\n #private = 0;\n}\nclass CookieSelect {\n #private = 0;\n}\n\ntype SelectorFn<T> = (payload: {\n body: Record<string, BodySelect>;\n query: Record<string, QuerySelect>;\n queries: Record<string, QueriesSelect>;\n params: Record<string, ParamsSelect>;\n headers: Record<string, HeadersSelect>;\n}) => T;\ntype ValidateMiddleware<T extends ValidatorConfig> = MiddlewareHandler<\n {\n Variables: {\n input: ExtractInput<T>;\n };\n },\n string,\n { in: InferIn<T> }\n>;\n\nexport function validate<T extends ValidatorConfig>(\n selector: SelectorFn<T>,\n): ValidateMiddleware<T>;\nexport function validate<T extends ValidatorConfig>(\n expectedContentTypeOrSelector: ContentType,\n selector: SelectorFn<T>,\n): ValidateMiddleware<T>;\nexport function validate<T extends ValidatorConfig>(\n expectedContentTypeOrSelector: ContentType | SelectorFn<T>,\n selector?: SelectorFn<T>,\n): ValidateMiddleware<T> {\n const expectedContentType =\n typeof expectedContentTypeOrSelector === 'string'\n ? expectedContentTypeOrSelector\n : undefined;\n const _selector =\n typeof expectedContentTypeOrSelector === 'function'\n ? expectedContentTypeOrSelector\n : selector;\n if (!_selector) {\n throw new Error('Selector function is required');\n }\n\n return createMiddleware(async (c, next) => {\n const ct = c.req.header('content-type');\n if (c.req.method === 'GET' && ct) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n details: `GET requests cannot have a content type header`,\n },\n });\n }\n if (expectedContentType) {\n verifyContentType(ct, expectedContentType);\n }\n\n const contentType = ct ? parseContentType(ct) : null;\n let body: unknown = null;\n\n switch (contentType?.type) {\n case 'application/json':\n body = await c.req.json();\n break;\n case 'application/x-www-form-urlencoded':\n case 'multipart/form-data':\n body = await c.req.parseBody();\n break;\n default:\n body = {};\n }\n\n const payload = {\n body,\n query: c.req.query(),\n queries: c.req.queries(),\n params: c.req.param(),\n headers: Object.fromEntries(\n Object.entries(c.req.header()).map(([k, v]) => [k, v ?? '']),\n ),\n };\n\n const config = _selector(payload as never);\n const schema = z.object(\n Object.entries(config).reduce(\n (acc, [key, value]) => {\n acc[key] = value.against;\n return acc;\n },\n {} as Record<string, z.ZodType>,\n ),\n );\n\n const input = Object.entries(config).reduce(\n (acc, [key, value]) => {\n acc[key] = value.select;\n return acc;\n },\n {} as Record<string, unknown>,\n );\n\n const parsed = await parse(schema, input);\n c.set('input', parsed as ExtractInput<T>);\n await next();\n });\n}\n\nexport async function parse<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n input: unknown,\n) {\n const result = await schema.safeParseAsync(input);\n if (!result.success) {\n const error = new HTTPException(400, {\n message: 'Validation failed',\n cause: {\n code: 'api/validation-failed',\n detail: 'The input data is invalid',\n errors: z.flattenError(result.error, (issue) => ({\n message: issue.message,\n code: issue.code,\n path: issue.path.join('.'),\n })).fieldErrors,\n },\n });\n throw error;\n }\n return result.data;\n}\n\nexport const openapi = validate;\n\nexport const consume = (contentType: ContentType) => {\n return createMiddleware(async (context, next) => {\n verifyContentType(context.req.header('content-type'), contentType);\n await next();\n });\n};\n\nexport function verifyContentType(\n actual: string | undefined,\n expected: ContentType,\n): asserts actual is ContentType {\n if (!actual) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n details: 'Missing content type header',\n },\n });\n }\n const { type: incomingContentType } = parseContentType(actual);\n if (incomingContentType !== expected) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n details: `Expected content type: ${expected}, but got: ${incomingContentType}`,\n },\n });\n }\n}\n"],
|
|
5
|
-
"mappings": ";AACA,SAAS,kBAAkB;AAO3B,SAAS,KACP,SACA,OACA,QACA,SACA;AACA,MAAI,UAAU,UAAa,UAAU,MAAM;AACzC,WAAO,QAAQ,KAAK,MAAM,QAAQ,OAAO;AAAA,EAC3C;AACA,QAAM,kBAAkB,EAAE,GAAG,QAAQ;AACrC,kBAAgB,cAAc,MAAM;AACpC,MAAI,gBAAgB,cAAc,EAAE,SAAS,kBAAkB,GAAG;AAChE,WAAO,QAAQ,KAAK,KAAK,UAAU,KAAK,GAAG,QAAQ,eAAe;AAAA,EACpE;AACA,SAAO,QAAQ,KAAK,OAAO,QAAQ,eAAe;AACpD;AAEO,SAAS,aAAa,WAA0B;AACrD,SAAO;AAAA,IACL,YAAY;AACV,YAAM,UAAU,UAAU;AAC1B,aAAO,QAAQ,KAAK,MAAM,KAAK,CAAC,CAAC;AAAA,IACnC;AAAA,IACA,GAAG,OAAgC,SAAkC;AACnE,aAAO,KAAK,UAAU,GAAG,OAAO,KAAK,OAAO;AAAA,IAC9C;AAAA,IACA,QACE,YACA,OACA,SACA;AACA,UAAI,OAAO,eAAe,UAAU;AAElC,eAAO,KAAK,UAAU,GAAG,OAAO,KAAK;AAAA,UACnC,UAAU;AAAA,UACV,GAAI,WAAW,CAAC;AAAA,QAClB,CAAC;AAAA,MACH,OAAO;AAEL,eAAO,KAAK,UAAU,GAAG,YAAY,KAAK,OAAO;AAAA,MACnD;AAAA,IACF;AAAA,IACA,SAAS,KAAmB,YAAsB;AAChD,YAAM,UAAU,UAAU;AAC1B,aAAO,QAAQ;AAAA,QACb,IAAI,SAAS;AAAA,QACZ,cAAqC;AAAA,MACxC;AAAA,IACF;AAAA,IACA,WAAW,QAAgB,UAAkB,UAAkB;AAC7D,YAAM,UAAU,UAAU;AAE1B,aAAO,QAAQ,KAAK,QAAiB,KAAK;AAAA,QACxC,gBAAgB;AAAA,QAChB,uBAAuB,yBAAyB,QAAQ;AAAA,QACxD,kBAAkB,OAAO,OAAO,SAAS;AAAA,MAC3C,CAAC;AAAA,IACH;AAAA,IACA,WACE,OACA,SACA;AACA,aAAO,KAAK,UAAU,GAAG,OAAO,KAAK,OAAO;AAAA,IAC9C;AAAA,IACA,aACE,OACA,SACA;AACA,aAAO,KAAK,UAAU,GAAG,OAAO,KAAK,OAAO;AAAA,IAC9C;AAAA,IACA,UACE,OACA,SACA;AACA,aAAO,KAAK,UAAU,GAAG,OAAO,KAAK,OAAO;AAAA,IAC9C;AAAA,IACA,SAAS,OAAgC,SAAkC;AACzE,aAAO,KAAK,UAAU,GAAG,OAAO,KAAK,OAAO;AAAA,IAC9C;AAAA,IACA,eACE,OACA,SACA;AACA,aAAO,KAAK,UAAU,GAAG,OAAO,KAAK,OAAO;AAAA,IAC9C;AAAA,IACA,SAAS,OAAgC,SAAkC;AACzE,aAAO,KAAK,UAAU,GAAG,OAAO,KAAK,OAAO;AAAA,IAC9C;AAAA,IACA,SAAS,OAAgC,SAAkC;AACzE,aAAO,KAAK,UAAU,GAAG,OAAO,KAAK,OAAO;AAAA,IAC9C;AAAA,IACA,oBACE,OACA,SACA;AACA,aAAO,KAAK,UAAU,GAAG,OAAO,KAAK,OAAO;AAAA,IAC9C;AAAA,IACA,oBACE,OACA,SACA;AACA,aAAO,KAAK,UAAU,GAAG,OAAO,KAAK,OAAO;AAAA,IAC9C;AAAA,IACA,mBACE,OACA,SACA;AACA,aAAO,KAAK,UAAU,GAAG,OAAO,KAAK,OAAO;AAAA,IAC9C;AAAA,EACF;AACF;AAEO,IAAM,SAAS,aAAa,MAAM,WAAW,CAAC;;;ACxHrD,SAAS,
|
|
4
|
+
"sourcesContent": ["import type { Context } from 'hono';\nimport { getContext } from 'hono/context-storage';\nimport type {\n ContentfulStatusCode,\n RedirectStatusCode,\n} from 'hono/utils/http-status';\n\ntype Data = any;\nfunction send(\n context: Context,\n value: Data | undefined | null,\n status: ContentfulStatusCode,\n headers?: Readonly<Record<string, string>>,\n) {\n if (value === undefined || value === null) {\n return context.body(null, status, headers);\n }\n const responseHeaders = { ...headers };\n responseHeaders['Content-Type'] ??= 'application/json';\n if (responseHeaders['Content-Type'].includes('application/json')) {\n return context.body(JSON.stringify(value), status, responseHeaders);\n }\n return context.body(value, status, responseHeaders);\n}\n\nexport function createOutput(contextFn: () => Context) {\n return {\n nocontent() {\n const context = contextFn();\n return context.body(null, 204, {});\n },\n ok(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 200, headers);\n },\n created(\n valueOrUri: string | Data,\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n if (typeof valueOrUri === 'string') {\n // If no content is provided, we send null\n return send(contextFn(), value, 201, {\n Location: valueOrUri,\n ...(headers || {}),\n });\n } else {\n // valueOrUri is the data\n return send(contextFn(), valueOrUri, 201, headers);\n }\n },\n redirect(uri: string | URL, statusCode?: unknown) {\n const context = contextFn();\n return context.redirect(\n uri.toString(),\n (statusCode as RedirectStatusCode) ?? undefined,\n );\n },\n attachment(buffer: Buffer, filename: string, mimeType: string) {\n const context = contextFn();\n // https://github.com/honojs/hono/issues/3720\n return context.body(buffer as never, 200, {\n 'Content-Type': mimeType,\n 'Content-Disposition': `attachment; filename=\"${filename}\"`,\n 'Content-Length': buffer.length.toString(),\n });\n },\n badRequest(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 400, headers);\n },\n unauthorized(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 401, headers);\n },\n forbidden(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 403, headers);\n },\n notFound(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 404, headers);\n },\n notImplemented(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 501, headers);\n },\n accepted(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 202, headers);\n },\n conflict(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 409, headers);\n },\n unprocessableEntity(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 422, headers);\n },\n internalServerError(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 500, headers);\n },\n serviceUnavailable(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 503, headers);\n },\n };\n}\n\nexport const output = createOutput(() => getContext());\n", "import { safeParse } from 'fast-content-type-parse';\nimport type { MiddlewareHandler, ValidationTargets } from 'hono';\nimport { createMiddleware } from 'hono/factory';\nimport { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\ntype ContentType =\n | 'application/json'\n | 'application/x-www-form-urlencoded'\n | 'multipart/form-data'\n | 'text/plain';\n\n// z.ZodType<any> mirrors zod v3's ZodTypeAny: with the default `unknown`\n// output, concrete middlewares stop being assignable to\n// ValidateMiddleware<ValidatorConfig>.\n\ntype ValidatorConfig = Record<\n string,\n { select: unknown; against: z.ZodType<any> }\n>;\n\ntype ExtractInput<T extends ValidatorConfig> = z.output<\n z.ZodObject<{ [K in keyof T]: T[K]['against'] }>\n>;\n\ntype HasUndefined<T> = undefined extends T ? true : false;\n\ntype InferTarget<\n T extends ValidatorConfig,\n S,\n Target extends keyof ValidationTargets,\n> = {\n [K in keyof T as T[K]['select'] extends S ? K : never]: HasUndefined<\n z.infer<T[K]['against']>\n > extends true\n ? z.infer<T[K]['against']> | undefined\n : z.infer<T[K]['against']> extends ValidationTargets[Target]\n ? z.infer<T[K]['against']>\n : z.infer<T[K]['against']>;\n};\n\ntype InferIn<T extends ValidatorConfig> = (keyof InferTarget<\n T,\n QuerySelect | QueriesSelect,\n 'query'\n> extends never\n ? never\n : { query: InferTarget<T, QuerySelect | QueriesSelect, 'query'> }) &\n (keyof InferTarget<T, BodySelect, 'json'> extends never\n ? never\n : { json: InferTarget<T, BodySelect, 'json'> }) &\n (keyof InferTarget<T, ParamsSelect, 'param'> extends never\n ? never\n : { param: InferTarget<T, ParamsSelect, 'param'> }) &\n (keyof InferTarget<T, HeadersSelect, 'header'> extends never\n ? never\n : { header: InferTarget<T, HeadersSelect, 'header'> }) &\n (keyof InferTarget<T, CookieSelect, 'cookie'> extends never\n ? never\n : { cookie: InferTarget<T, CookieSelect, 'cookie'> });\n\n// Type-only markers distinguish request sources; no marker objects exist at runtime.\ntype Select<Target extends string> = {\n readonly validationTarget: Target;\n};\n\ntype BodySelect = Select<'body'>;\ntype QuerySelect = Select<'query'>;\ntype QueriesSelect = Select<'queries'>;\ntype ParamsSelect = Select<'params'>;\ntype HeadersSelect = Select<'headers'>;\ntype CookieSelect = Select<'cookie'>;\n\ntype SelectorFn<T> = (payload: {\n body: Record<string, BodySelect>;\n query: Record<string, QuerySelect>;\n queries: Record<string, QueriesSelect>;\n params: Record<string, ParamsSelect>;\n headers: Record<string, HeadersSelect>;\n}) => T;\ntype ValidateMiddleware<T extends ValidatorConfig> = MiddlewareHandler<\n {\n Variables: {\n input: ExtractInput<T>;\n };\n },\n string,\n { in: InferIn<T> }\n>;\n\n/** Validate selected request values and expose Zod's parsed output as `c.var.input`. */\nexport function validate<T extends ValidatorConfig>(\n selector: SelectorFn<T>,\n): ValidateMiddleware<T>;\n/** Enforce a content type before validating the selected request values. */\nexport function validate<T extends ValidatorConfig>(\n expectedContentTypeOrSelector: ContentType,\n selector: SelectorFn<T>,\n): ValidateMiddleware<T>;\nexport function validate<T extends ValidatorConfig>(\n expectedContentTypeOrSelector: ContentType | SelectorFn<T>,\n selector?: SelectorFn<T>,\n): ValidateMiddleware<T> {\n const expectedContentType =\n typeof expectedContentTypeOrSelector === 'string'\n ? expectedContentTypeOrSelector\n : undefined;\n const _selector =\n typeof expectedContentTypeOrSelector === 'function'\n ? expectedContentTypeOrSelector\n : selector;\n if (!_selector) {\n throw new Error('Selector function is required');\n }\n\n return createMiddleware(async (c, next) => {\n const ct = c.req.header('content-type');\n if (c.req.method === 'GET' && ct) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: `GET requests cannot have a content type header`,\n },\n });\n }\n if (expectedContentType) {\n verifyContentType(ct, expectedContentType);\n }\n\n const contentType = ct ? parseContentType(ct) : null;\n let body: unknown = null;\n\n switch (contentType?.type) {\n case 'application/json':\n try {\n body = await c.req.json();\n } catch {\n throw new HTTPException(400, {\n message: 'Invalid JSON body',\n cause: {\n code: 'api/invalid-json',\n detail: 'Request body must be valid JSON.',\n },\n });\n }\n break;\n case 'application/x-www-form-urlencoded':\n case 'multipart/form-data':\n body = await c.req.parseBody({ all: true });\n break;\n default:\n body = {};\n }\n\n // Whole-body schemas may accept any JSON value. A field selector, however,\n // requires an object: guard the property read itself rather than catching\n // arbitrary errors thrown by the application's selector.\n const selectedBody =\n body !== null && typeof body === 'object' && !Array.isArray(body)\n ? body\n : new Proxy(\n {},\n {\n get() {\n throw new HTTPException(400, {\n message: 'Invalid request body',\n cause: {\n code: 'api/invalid-body',\n detail:\n 'Request body must be an object when selecting fields.',\n },\n });\n },\n },\n );\n const payload = {\n body: selectedBody,\n query: c.req.query(),\n queries: c.req.queries(),\n params: c.req.param(),\n headers: c.req.header(),\n };\n\n const config = _selector(payload as never);\n const schema = z.object(\n Object.fromEntries(\n Object.entries(config).map(([key, value]) => [key, value.against]),\n ),\n );\n\n const input = Object.fromEntries(\n Object.entries(config).map(([key, value]) => [\n key,\n value.select === selectedBody ? body : value.select,\n ]),\n );\n\n const parsed = await parse(schema, input);\n c.set('input', parsed as ExtractInput<T>);\n await next();\n });\n}\n\n/** Parse any Zod schema asynchronously, throwing a structured HTTP 400 on rejection. */\nexport async function parse<T extends z.ZodType>(\n schema: T,\n input: unknown,\n): Promise<z.output<T>> {\n const result = await schema.safeParseAsync(input);\n if (!result.success) {\n const { fieldErrors, formErrors } = z.flattenError(\n result.error,\n (issue) => ({\n message: issue.message,\n code: issue.code,\n path: issue.path.join('.'),\n }),\n );\n const error = new HTTPException(400, {\n message: 'Validation failed',\n cause: {\n code: 'api/validation-failed',\n detail: 'The input data is invalid',\n errors: fieldErrors,\n formErrors,\n },\n });\n throw error;\n }\n return result.data;\n}\n\nexport const openapi = validate;\n\n/** Enforce a request content type without reading or validating its body. */\nexport const consume = (contentType: ContentType) => {\n return createMiddleware(async (context, next) => {\n verifyContentType(context.req.header('content-type'), contentType);\n await next();\n });\n};\n\nfunction parseContentType(header: string) {\n const contentType = safeParse(header);\n if (!contentType.type) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: 'Invalid content type header',\n },\n });\n }\n return contentType;\n}\n\nexport function verifyContentType(\n actual: string | undefined,\n expected: ContentType,\n): asserts actual is ContentType {\n if (!actual) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: 'Missing content type header',\n },\n });\n }\n const { type: incomingContentType } = parseContentType(actual);\n if (incomingContentType !== expected) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: `Expected content type: ${expected}, but got: ${incomingContentType}`,\n },\n });\n }\n}\n"],
|
|
5
|
+
"mappings": ";AACA,SAAS,kBAAkB;AAO3B,SAAS,KACP,SACA,OACA,QACA,SACA;AACA,MAAI,UAAU,UAAa,UAAU,MAAM;AACzC,WAAO,QAAQ,KAAK,MAAM,QAAQ,OAAO;AAAA,EAC3C;AACA,QAAM,kBAAkB,EAAE,GAAG,QAAQ;AACrC,kBAAgB,cAAc,MAAM;AACpC,MAAI,gBAAgB,cAAc,EAAE,SAAS,kBAAkB,GAAG;AAChE,WAAO,QAAQ,KAAK,KAAK,UAAU,KAA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K;AAAA,MAC3B,SAAS;AAAA,MACT,OAAO;AAAA,QACL,MAAM;AAAA,QACN,QAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,EACH;AACA,QAAM,EAAE,MAAM,oBAAoB,IAAI,iBAAiB,MAAM;AAC7D,MAAI,wBAAwB,UAAU;AACpC,UAAM,IAAI,cAAc,KAAK;AAAA,MAC3B,SAAS;AAAA,MACT,OAAO;AAAA,QACL,MAAM;AAAA,QACN,QAAQ,0BAA0B,QAAQ,cAAc,mBAAmB;AAAA,MAC7E;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -5,9 +5,9 @@ type ValidatorConfig = Record<string, {
|
|
|
5
5
|
select: unknown;
|
|
6
6
|
against: z.ZodType<any>;
|
|
7
7
|
}>;
|
|
8
|
-
type ExtractInput<T extends ValidatorConfig> = {
|
|
9
|
-
[K in keyof T]:
|
|
10
|
-
}
|
|
8
|
+
type ExtractInput<T extends ValidatorConfig> = z.output<z.ZodObject<{
|
|
9
|
+
[K in keyof T]: T[K]['against'];
|
|
10
|
+
}>>;
|
|
11
11
|
type HasUndefined<T> = undefined extends T ? true : false;
|
|
12
12
|
type InferTarget<T extends ValidatorConfig, S, Target extends keyof ValidationTargets> = {
|
|
13
13
|
[K in keyof T as T[K]['select'] extends S ? K : never]: HasUndefined<z.infer<T[K]['against']>> extends true ? z.infer<T[K]['against']> | undefined : z.infer<T[K]['against']> extends ValidationTargets[Target] ? z.infer<T[K]['against']> : z.infer<T[K]['against']>;
|
|
@@ -23,24 +23,15 @@ type InferIn<T extends ValidatorConfig> = (keyof InferTarget<T, QuerySelect | Qu
|
|
|
23
23
|
}) & (keyof InferTarget<T, CookieSelect, 'cookie'> extends never ? never : {
|
|
24
24
|
cookie: InferTarget<T, CookieSelect, 'cookie'>;
|
|
25
25
|
});
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
declare class ParamsSelect {
|
|
36
|
-
#private;
|
|
37
|
-
}
|
|
38
|
-
declare class HeadersSelect {
|
|
39
|
-
#private;
|
|
40
|
-
}
|
|
41
|
-
declare class CookieSelect {
|
|
42
|
-
#private;
|
|
43
|
-
}
|
|
26
|
+
type Select<Target extends string> = {
|
|
27
|
+
readonly validationTarget: Target;
|
|
28
|
+
};
|
|
29
|
+
type BodySelect = Select<'body'>;
|
|
30
|
+
type QuerySelect = Select<'query'>;
|
|
31
|
+
type QueriesSelect = Select<'queries'>;
|
|
32
|
+
type ParamsSelect = Select<'params'>;
|
|
33
|
+
type HeadersSelect = Select<'headers'>;
|
|
34
|
+
type CookieSelect = Select<'cookie'>;
|
|
44
35
|
type SelectorFn<T> = (payload: {
|
|
45
36
|
body: Record<string, BodySelect>;
|
|
46
37
|
query: Record<string, QuerySelect>;
|
|
@@ -55,10 +46,14 @@ type ValidateMiddleware<T extends ValidatorConfig> = MiddlewareHandler<{
|
|
|
55
46
|
}, string, {
|
|
56
47
|
in: InferIn<T>;
|
|
57
48
|
}>;
|
|
49
|
+
/** Validate selected request values and expose Zod's parsed output as `c.var.input`. */
|
|
58
50
|
export declare function validate<T extends ValidatorConfig>(selector: SelectorFn<T>): ValidateMiddleware<T>;
|
|
51
|
+
/** Enforce a content type before validating the selected request values. */
|
|
59
52
|
export declare function validate<T extends ValidatorConfig>(expectedContentTypeOrSelector: ContentType, selector: SelectorFn<T>): ValidateMiddleware<T>;
|
|
60
|
-
|
|
53
|
+
/** Parse any Zod schema asynchronously, throwing a structured HTTP 400 on rejection. */
|
|
54
|
+
export declare function parse<T extends z.ZodType>(schema: T, input: unknown): Promise<z.output<T>>;
|
|
61
55
|
export declare const openapi: typeof validate;
|
|
56
|
+
/** Enforce a request content type without reading or validating its body. */
|
|
62
57
|
export declare const consume: (contentType: ContentType) => MiddlewareHandler<any, string, {}, Response>;
|
|
63
58
|
export declare function verifyContentType(actual: string | undefined, expected: ContentType): asserts actual is ContentType;
|
|
64
59
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.d.ts","sourceRoot":"","sources":["../../../src/lib/runtime/validator.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAGjE,OAAO,CAAC,MAAM,KAAK,CAAC;AAEpB,KAAK,WAAW,GACZ,kBAAkB,GAClB,mCAAmC,GACnC,qBAAqB,GACrB,YAAY,CAAC;AAMjB,KAAK,eAAe,GAAG,MAAM,CAC3B,MAAM,EACN;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;CAAE,CAC7C,CAAC;AAEF,KAAK,YAAY,CAAC,CAAC,SAAS,eAAe,IAAI
|
|
1
|
+
{"version":3,"file":"validator.d.ts","sourceRoot":"","sources":["../../../src/lib/runtime/validator.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAGjE,OAAO,CAAC,MAAM,KAAK,CAAC;AAEpB,KAAK,WAAW,GACZ,kBAAkB,GAClB,mCAAmC,GACnC,qBAAqB,GACrB,YAAY,CAAC;AAMjB,KAAK,eAAe,GAAG,MAAM,CAC3B,MAAM,EACN;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;CAAE,CAC7C,CAAC;AAEF,KAAK,YAAY,CAAC,CAAC,SAAS,eAAe,IAAI,CAAC,CAAC,MAAM,CACrD,CAAC,CAAC,SAAS,CAAC;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;CAAE,CAAC,CACjD,CAAC;AAEF,KAAK,YAAY,CAAC,CAAC,IAAI,SAAS,SA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@@ -16,18 +16,22 @@
|
|
|
16
16
|
"default": "./dist/index.js"
|
|
17
17
|
},
|
|
18
18
|
"./runtime": {
|
|
19
|
-
"types":
|
|
19
|
+
"types": {
|
|
20
|
+
"@sdk-it/source": "./src/lib/runtime/index.ts",
|
|
21
|
+
"default": "./dist/lib/runtime/index.d.ts"
|
|
22
|
+
},
|
|
20
23
|
"import": "./dist/lib/runtime/index.js",
|
|
21
24
|
"default": "./dist/lib/runtime/index.js"
|
|
22
25
|
}
|
|
23
26
|
},
|
|
24
27
|
"files": [
|
|
25
28
|
"dist",
|
|
29
|
+
"src/lib/runtime",
|
|
26
30
|
"!**/*.tsbuildinfo",
|
|
27
31
|
"!**/*.test.*"
|
|
28
32
|
],
|
|
29
33
|
"dependencies": {
|
|
30
|
-
"@sdk-it/core": "0.46.
|
|
34
|
+
"@sdk-it/core": "0.46.8",
|
|
31
35
|
"hono": "^4.7.4",
|
|
32
36
|
"zod": "^4.3.0",
|
|
33
37
|
"fast-content-type-parse": "^3.0.0"
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import { getContext } from 'hono/context-storage';
|
|
3
|
+
import type {
|
|
4
|
+
ContentfulStatusCode,
|
|
5
|
+
RedirectStatusCode,
|
|
6
|
+
} from 'hono/utils/http-status';
|
|
7
|
+
|
|
8
|
+
type Data = any;
|
|
9
|
+
function send(
|
|
10
|
+
context: Context,
|
|
11
|
+
value: Data | undefined | null,
|
|
12
|
+
status: ContentfulStatusCode,
|
|
13
|
+
headers?: Readonly<Record<string, string>>,
|
|
14
|
+
) {
|
|
15
|
+
if (value === undefined || value === null) {
|
|
16
|
+
return context.body(null, status, headers);
|
|
17
|
+
}
|
|
18
|
+
const responseHeaders = { ...headers };
|
|
19
|
+
responseHeaders['Content-Type'] ??= 'application/json';
|
|
20
|
+
if (responseHeaders['Content-Type'].includes('application/json')) {
|
|
21
|
+
return context.body(JSON.stringify(value), status, responseHeaders);
|
|
22
|
+
}
|
|
23
|
+
return context.body(value, status, responseHeaders);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function createOutput(contextFn: () => Context) {
|
|
27
|
+
return {
|
|
28
|
+
nocontent() {
|
|
29
|
+
const context = contextFn();
|
|
30
|
+
return context.body(null, 204, {});
|
|
31
|
+
},
|
|
32
|
+
ok(value: Data | undefined | null, headers?: Record<string, string>) {
|
|
33
|
+
return send(contextFn(), value, 200, headers);
|
|
34
|
+
},
|
|
35
|
+
created(
|
|
36
|
+
valueOrUri: string | Data,
|
|
37
|
+
value: Data | undefined | null,
|
|
38
|
+
headers?: Record<string, string>,
|
|
39
|
+
) {
|
|
40
|
+
if (typeof valueOrUri === 'string') {
|
|
41
|
+
// If no content is provided, we send null
|
|
42
|
+
return send(contextFn(), value, 201, {
|
|
43
|
+
Location: valueOrUri,
|
|
44
|
+
...(headers || {}),
|
|
45
|
+
});
|
|
46
|
+
} else {
|
|
47
|
+
// valueOrUri is the data
|
|
48
|
+
return send(contextFn(), valueOrUri, 201, headers);
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
redirect(uri: string | URL, statusCode?: unknown) {
|
|
52
|
+
const context = contextFn();
|
|
53
|
+
return context.redirect(
|
|
54
|
+
uri.toString(),
|
|
55
|
+
(statusCode as RedirectStatusCode) ?? undefined,
|
|
56
|
+
);
|
|
57
|
+
},
|
|
58
|
+
attachment(buffer: Buffer, filename: string, mimeType: string) {
|
|
59
|
+
const context = contextFn();
|
|
60
|
+
// https://github.com/honojs/hono/issues/3720
|
|
61
|
+
return context.body(buffer as never, 200, {
|
|
62
|
+
'Content-Type': mimeType,
|
|
63
|
+
'Content-Disposition': `attachment; filename="${filename}"`,
|
|
64
|
+
'Content-Length': buffer.length.toString(),
|
|
65
|
+
});
|
|
66
|
+
},
|
|
67
|
+
badRequest(
|
|
68
|
+
value: Data | undefined | null,
|
|
69
|
+
headers?: Record<string, string>,
|
|
70
|
+
) {
|
|
71
|
+
return send(contextFn(), value, 400, headers);
|
|
72
|
+
},
|
|
73
|
+
unauthorized(
|
|
74
|
+
value: Data | undefined | null,
|
|
75
|
+
headers?: Record<string, string>,
|
|
76
|
+
) {
|
|
77
|
+
return send(contextFn(), value, 401, headers);
|
|
78
|
+
},
|
|
79
|
+
forbidden(
|
|
80
|
+
value: Data | undefined | null,
|
|
81
|
+
headers?: Record<string, string>,
|
|
82
|
+
) {
|
|
83
|
+
return send(contextFn(), value, 403, headers);
|
|
84
|
+
},
|
|
85
|
+
notFound(value: Data | undefined | null, headers?: Record<string, string>) {
|
|
86
|
+
return send(contextFn(), value, 404, headers);
|
|
87
|
+
},
|
|
88
|
+
notImplemented(
|
|
89
|
+
value: Data | undefined | null,
|
|
90
|
+
headers?: Record<string, string>,
|
|
91
|
+
) {
|
|
92
|
+
return send(contextFn(), value, 501, headers);
|
|
93
|
+
},
|
|
94
|
+
accepted(value: Data | undefined | null, headers?: Record<string, string>) {
|
|
95
|
+
return send(contextFn(), value, 202, headers);
|
|
96
|
+
},
|
|
97
|
+
conflict(value: Data | undefined | null, headers?: Record<string, string>) {
|
|
98
|
+
return send(contextFn(), value, 409, headers);
|
|
99
|
+
},
|
|
100
|
+
unprocessableEntity(
|
|
101
|
+
value: Data | undefined | null,
|
|
102
|
+
headers?: Record<string, string>,
|
|
103
|
+
) {
|
|
104
|
+
return send(contextFn(), value, 422, headers);
|
|
105
|
+
},
|
|
106
|
+
internalServerError(
|
|
107
|
+
value: Data | undefined | null,
|
|
108
|
+
headers?: Record<string, string>,
|
|
109
|
+
) {
|
|
110
|
+
return send(contextFn(), value, 500, headers);
|
|
111
|
+
},
|
|
112
|
+
serviceUnavailable(
|
|
113
|
+
value: Data | undefined | null,
|
|
114
|
+
headers?: Record<string, string>,
|
|
115
|
+
) {
|
|
116
|
+
return send(contextFn(), value, 503, headers);
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export const output = createOutput(() => getContext());
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { safeParse } from 'fast-content-type-parse';
|
|
2
|
+
import type { MiddlewareHandler, ValidationTargets } from 'hono';
|
|
3
|
+
import { createMiddleware } from 'hono/factory';
|
|
4
|
+
import { HTTPException } from 'hono/http-exception';
|
|
5
|
+
import z from 'zod';
|
|
6
|
+
|
|
7
|
+
type ContentType =
|
|
8
|
+
| 'application/json'
|
|
9
|
+
| 'application/x-www-form-urlencoded'
|
|
10
|
+
| 'multipart/form-data'
|
|
11
|
+
| 'text/plain';
|
|
12
|
+
|
|
13
|
+
// z.ZodType<any> mirrors zod v3's ZodTypeAny: with the default `unknown`
|
|
14
|
+
// output, concrete middlewares stop being assignable to
|
|
15
|
+
// ValidateMiddleware<ValidatorConfig>.
|
|
16
|
+
|
|
17
|
+
type ValidatorConfig = Record<
|
|
18
|
+
string,
|
|
19
|
+
{ select: unknown; against: z.ZodType<any> }
|
|
20
|
+
>;
|
|
21
|
+
|
|
22
|
+
type ExtractInput<T extends ValidatorConfig> = z.output<
|
|
23
|
+
z.ZodObject<{ [K in keyof T]: T[K]['against'] }>
|
|
24
|
+
>;
|
|
25
|
+
|
|
26
|
+
type HasUndefined<T> = undefined extends T ? true : false;
|
|
27
|
+
|
|
28
|
+
type InferTarget<
|
|
29
|
+
T extends ValidatorConfig,
|
|
30
|
+
S,
|
|
31
|
+
Target extends keyof ValidationTargets,
|
|
32
|
+
> = {
|
|
33
|
+
[K in keyof T as T[K]['select'] extends S ? K : never]: HasUndefined<
|
|
34
|
+
z.infer<T[K]['against']>
|
|
35
|
+
> extends true
|
|
36
|
+
? z.infer<T[K]['against']> | undefined
|
|
37
|
+
: z.infer<T[K]['against']> extends ValidationTargets[Target]
|
|
38
|
+
? z.infer<T[K]['against']>
|
|
39
|
+
: z.infer<T[K]['against']>;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
type InferIn<T extends ValidatorConfig> = (keyof InferTarget<
|
|
43
|
+
T,
|
|
44
|
+
QuerySelect | QueriesSelect,
|
|
45
|
+
'query'
|
|
46
|
+
> extends never
|
|
47
|
+
? never
|
|
48
|
+
: { query: InferTarget<T, QuerySelect | QueriesSelect, 'query'> }) &
|
|
49
|
+
(keyof InferTarget<T, BodySelect, 'json'> extends never
|
|
50
|
+
? never
|
|
51
|
+
: { json: InferTarget<T, BodySelect, 'json'> }) &
|
|
52
|
+
(keyof InferTarget<T, ParamsSelect, 'param'> extends never
|
|
53
|
+
? never
|
|
54
|
+
: { param: InferTarget<T, ParamsSelect, 'param'> }) &
|
|
55
|
+
(keyof InferTarget<T, HeadersSelect, 'header'> extends never
|
|
56
|
+
? never
|
|
57
|
+
: { header: InferTarget<T, HeadersSelect, 'header'> }) &
|
|
58
|
+
(keyof InferTarget<T, CookieSelect, 'cookie'> extends never
|
|
59
|
+
? never
|
|
60
|
+
: { cookie: InferTarget<T, CookieSelect, 'cookie'> });
|
|
61
|
+
|
|
62
|
+
// Type-only markers distinguish request sources; no marker objects exist at runtime.
|
|
63
|
+
type Select<Target extends string> = {
|
|
64
|
+
readonly validationTarget: Target;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
type BodySelect = Select<'body'>;
|
|
68
|
+
type QuerySelect = Select<'query'>;
|
|
69
|
+
type QueriesSelect = Select<'queries'>;
|
|
70
|
+
type ParamsSelect = Select<'params'>;
|
|
71
|
+
type HeadersSelect = Select<'headers'>;
|
|
72
|
+
type CookieSelect = Select<'cookie'>;
|
|
73
|
+
|
|
74
|
+
type SelectorFn<T> = (payload: {
|
|
75
|
+
body: Record<string, BodySelect>;
|
|
76
|
+
query: Record<string, QuerySelect>;
|
|
77
|
+
queries: Record<string, QueriesSelect>;
|
|
78
|
+
params: Record<string, ParamsSelect>;
|
|
79
|
+
headers: Record<string, HeadersSelect>;
|
|
80
|
+
}) => T;
|
|
81
|
+
type ValidateMiddleware<T extends ValidatorConfig> = MiddlewareHandler<
|
|
82
|
+
{
|
|
83
|
+
Variables: {
|
|
84
|
+
input: ExtractInput<T>;
|
|
85
|
+
};
|
|
86
|
+
},
|
|
87
|
+
string,
|
|
88
|
+
{ in: InferIn<T> }
|
|
89
|
+
>;
|
|
90
|
+
|
|
91
|
+
/** Validate selected request values and expose Zod's parsed output as `c.var.input`. */
|
|
92
|
+
export function validate<T extends ValidatorConfig>(
|
|
93
|
+
selector: SelectorFn<T>,
|
|
94
|
+
): ValidateMiddleware<T>;
|
|
95
|
+
/** Enforce a content type before validating the selected request values. */
|
|
96
|
+
export function validate<T extends ValidatorConfig>(
|
|
97
|
+
expectedContentTypeOrSelector: ContentType,
|
|
98
|
+
selector: SelectorFn<T>,
|
|
99
|
+
): ValidateMiddleware<T>;
|
|
100
|
+
export function validate<T extends ValidatorConfig>(
|
|
101
|
+
expectedContentTypeOrSelector: ContentType | SelectorFn<T>,
|
|
102
|
+
selector?: SelectorFn<T>,
|
|
103
|
+
): ValidateMiddleware<T> {
|
|
104
|
+
const expectedContentType =
|
|
105
|
+
typeof expectedContentTypeOrSelector === 'string'
|
|
106
|
+
? expectedContentTypeOrSelector
|
|
107
|
+
: undefined;
|
|
108
|
+
const _selector =
|
|
109
|
+
typeof expectedContentTypeOrSelector === 'function'
|
|
110
|
+
? expectedContentTypeOrSelector
|
|
111
|
+
: selector;
|
|
112
|
+
if (!_selector) {
|
|
113
|
+
throw new Error('Selector function is required');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return createMiddleware(async (c, next) => {
|
|
117
|
+
const ct = c.req.header('content-type');
|
|
118
|
+
if (c.req.method === 'GET' && ct) {
|
|
119
|
+
throw new HTTPException(415, {
|
|
120
|
+
message: 'Unsupported Media Type',
|
|
121
|
+
cause: {
|
|
122
|
+
code: 'api/unsupported-media-type',
|
|
123
|
+
detail: `GET requests cannot have a content type header`,
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
if (expectedContentType) {
|
|
128
|
+
verifyContentType(ct, expectedContentType);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const contentType = ct ? parseContentType(ct) : null;
|
|
132
|
+
let body: unknown = null;
|
|
133
|
+
|
|
134
|
+
switch (contentType?.type) {
|
|
135
|
+
case 'application/json':
|
|
136
|
+
try {
|
|
137
|
+
body = await c.req.json();
|
|
138
|
+
} catch {
|
|
139
|
+
throw new HTTPException(400, {
|
|
140
|
+
message: 'Invalid JSON body',
|
|
141
|
+
cause: {
|
|
142
|
+
code: 'api/invalid-json',
|
|
143
|
+
detail: 'Request body must be valid JSON.',
|
|
144
|
+
},
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
break;
|
|
148
|
+
case 'application/x-www-form-urlencoded':
|
|
149
|
+
case 'multipart/form-data':
|
|
150
|
+
body = await c.req.parseBody({ all: true });
|
|
151
|
+
break;
|
|
152
|
+
default:
|
|
153
|
+
body = {};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Whole-body schemas may accept any JSON value. A field selector, however,
|
|
157
|
+
// requires an object: guard the property read itself rather than catching
|
|
158
|
+
// arbitrary errors thrown by the application's selector.
|
|
159
|
+
const selectedBody =
|
|
160
|
+
body !== null && typeof body === 'object' && !Array.isArray(body)
|
|
161
|
+
? body
|
|
162
|
+
: new Proxy(
|
|
163
|
+
{},
|
|
164
|
+
{
|
|
165
|
+
get() {
|
|
166
|
+
throw new HTTPException(400, {
|
|
167
|
+
message: 'Invalid request body',
|
|
168
|
+
cause: {
|
|
169
|
+
code: 'api/invalid-body',
|
|
170
|
+
detail:
|
|
171
|
+
'Request body must be an object when selecting fields.',
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
);
|
|
177
|
+
const payload = {
|
|
178
|
+
body: selectedBody,
|
|
179
|
+
query: c.req.query(),
|
|
180
|
+
queries: c.req.queries(),
|
|
181
|
+
params: c.req.param(),
|
|
182
|
+
headers: c.req.header(),
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
const config = _selector(payload as never);
|
|
186
|
+
const schema = z.object(
|
|
187
|
+
Object.fromEntries(
|
|
188
|
+
Object.entries(config).map(([key, value]) => [key, value.against]),
|
|
189
|
+
),
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
const input = Object.fromEntries(
|
|
193
|
+
Object.entries(config).map(([key, value]) => [
|
|
194
|
+
key,
|
|
195
|
+
value.select === selectedBody ? body : value.select,
|
|
196
|
+
]),
|
|
197
|
+
);
|
|
198
|
+
|
|
199
|
+
const parsed = await parse(schema, input);
|
|
200
|
+
c.set('input', parsed as ExtractInput<T>);
|
|
201
|
+
await next();
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Parse any Zod schema asynchronously, throwing a structured HTTP 400 on rejection. */
|
|
206
|
+
export async function parse<T extends z.ZodType>(
|
|
207
|
+
schema: T,
|
|
208
|
+
input: unknown,
|
|
209
|
+
): Promise<z.output<T>> {
|
|
210
|
+
const result = await schema.safeParseAsync(input);
|
|
211
|
+
if (!result.success) {
|
|
212
|
+
const { fieldErrors, formErrors } = z.flattenError(
|
|
213
|
+
result.error,
|
|
214
|
+
(issue) => ({
|
|
215
|
+
message: issue.message,
|
|
216
|
+
code: issue.code,
|
|
217
|
+
path: issue.path.join('.'),
|
|
218
|
+
}),
|
|
219
|
+
);
|
|
220
|
+
const error = new HTTPException(400, {
|
|
221
|
+
message: 'Validation failed',
|
|
222
|
+
cause: {
|
|
223
|
+
code: 'api/validation-failed',
|
|
224
|
+
detail: 'The input data is invalid',
|
|
225
|
+
errors: fieldErrors,
|
|
226
|
+
formErrors,
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
231
|
+
return result.data;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export const openapi = validate;
|
|
235
|
+
|
|
236
|
+
/** Enforce a request content type without reading or validating its body. */
|
|
237
|
+
export const consume = (contentType: ContentType) => {
|
|
238
|
+
return createMiddleware(async (context, next) => {
|
|
239
|
+
verifyContentType(context.req.header('content-type'), contentType);
|
|
240
|
+
await next();
|
|
241
|
+
});
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
function parseContentType(header: string) {
|
|
245
|
+
const contentType = safeParse(header);
|
|
246
|
+
if (!contentType.type) {
|
|
247
|
+
throw new HTTPException(415, {
|
|
248
|
+
message: 'Unsupported Media Type',
|
|
249
|
+
cause: {
|
|
250
|
+
code: 'api/unsupported-media-type',
|
|
251
|
+
detail: 'Invalid content type header',
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
return contentType;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function verifyContentType(
|
|
259
|
+
actual: string | undefined,
|
|
260
|
+
expected: ContentType,
|
|
261
|
+
): asserts actual is ContentType {
|
|
262
|
+
if (!actual) {
|
|
263
|
+
throw new HTTPException(415, {
|
|
264
|
+
message: 'Unsupported Media Type',
|
|
265
|
+
cause: {
|
|
266
|
+
code: 'api/unsupported-media-type',
|
|
267
|
+
detail: 'Missing content type header',
|
|
268
|
+
},
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
const { type: incomingContentType } = parseContentType(actual);
|
|
272
|
+
if (incomingContentType !== expected) {
|
|
273
|
+
throw new HTTPException(415, {
|
|
274
|
+
message: 'Unsupported Media Type',
|
|
275
|
+
cause: {
|
|
276
|
+
code: 'api/unsupported-media-type',
|
|
277
|
+
detail: `Expected content type: ${expected}, but got: ${incomingContentType}`,
|
|
278
|
+
},
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
}
|