@bram-dc/fastify-type-provider-zod 3.1.1 → 4.0.2

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 CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 turkerdev
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2022-2024 turkerdev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,145 +1,280 @@
1
- # Fastify Type Provider Zod
2
-
3
- [![NPM Version](https://img.shields.io/npm/v/@bram-dc/fastify-type-provider-zod.svg)](https://www.npmjs.com/package/@bram-dc/fastify-type-provider-zod)
4
- [![NPM Downloads](https://img.shields.io/npm/dm/@bram-dc/fastify-type-provider-zod.svg)](https://www.npmjs.com/package/@bram-dc/fastify-type-provider-zod)
5
- [![Build Status](https://github.com//bram-dc/fastify-type-provider-zod/workflows/CI/badge.svg)](https://github.com/bram-dc/fastify-type-provider-zod/actions)
6
-
7
- ## How to use?
8
-
9
- ```js
10
- import Fastify from "fastify";
11
- import { ZodSerializerCompiler, ZodValidatorCompiler, ZodTypeProvider } from "@bram-dc/fastify-type-provider-zod";
12
- import z from "zod";
13
-
14
- const app = Fastify()
15
-
16
- // Add schema validator and serializer
17
- app.setValidatorCompiler(ZodValidatorCompiler);
18
- app.setSerializerCompiler(ZodSerializerCompiler);
19
-
20
- app.withTypeProvider<ZodTypeProvider>().route({
21
- method: "GET",
22
- url: "/",
23
- // Define your schema
24
- schema: {
25
- querystring: z.object({
26
- name: z.string().min(4),
27
- }),
28
- response: {
29
- 200: z.string(),
30
- },
31
- },
32
- handler: (req, res) => {
33
- res.send(req.query.name);
34
- },
35
- });
36
-
37
- app.listen({ port: 4949 });
38
- ```
39
-
40
- ## How to use together with @fastify/swagger
41
-
42
- ```ts
43
- import fastify from "fastify";
44
- import fastifySwagger from "@fastify/swagger";
45
- import fastifySwaggerUI from "@fastify/swagger-ui";
46
- import { z } from "zod";
47
-
48
- import {
49
- jsonSchemaTransform,
50
- createJsonSchemaTransform,
51
- ZodSerializerCompiler,
52
- ZodValidatorCompiler,
53
- ZodTypeProvider,
54
- } from "@bram-dc/fastify-type-provider-zod";
55
-
56
- const app = fastify();
57
- app.setValidatorCompiler(ZodValidatorCompiler);
58
- app.setSerializerCompiler(ZodSerializerCompiler);
59
-
60
- app.register(fastifySwagger, {
61
- openapi: {
62
- info: {
63
- title: "SampleApi",
64
- description: "Sample backend service",
65
- version: "1.0.0",
66
- },
67
- servers: [],
68
- },
69
- transform: jsonSchemaTransform,
70
- // You can also create transform with custom skiplist of endpoints that should not be included in the specification:
71
- //
72
- // transform: createJsonSchemaTransform({
73
- // skipList: [ "/documentation/static/*" ]
74
- // })
75
-
76
- // In order to create refs to the schemas, you need to provide the schemas to the transformObject using createJsonSchemaTransformObject
77
- //
78
- // transformObject: createJsonSchemaTransformObject({
79
- // schemas: {
80
- // User: z.object({
81
- // id: z.string(),
82
- // name: z.string(),
83
- // }),
84
- // }
85
- // }),
86
- });
87
-
88
- app.register(fastifySwaggerUI, {
89
- routePrefix: "/documentation",
90
- });
91
-
92
- const LOGIN_SCHEMA = z.object({
93
- username: z.string().max(32).describe("Some description for username"),
94
- password: z.string().max(32),
95
- });
96
-
97
- app.after(() => {
98
- app.withTypeProvider<ZodTypeProvider>().route({
99
- method: "POST",
100
- url: "/login",
101
- schema: { body: LOGIN_SCHEMA },
102
- handler: (req, res) => {
103
- res.send("ok");
104
- },
105
- });
106
- });
107
-
108
- async function run() {
109
- await app.ready();
110
-
111
- await app.listen({
112
- port: 4949,
113
- });
114
-
115
- console.log(`Documentation running at http://localhost:4949/documentation`);
116
- }
117
-
118
- run();
119
- ```
120
-
121
- ## How to create a plugin?
122
-
123
- ```ts
124
- import { z } from "zod";
125
- import { FastifyPluginAsyncZod } from "@bram-dc/fastify-type-provider-zod";
126
-
127
- const plugin: FastifyPluginAsyncZod = async function (fastify, _opts) {
128
- fastify.route({
129
- method: "GET",
130
- url: "/",
131
- // Define your schema
132
- schema: {
133
- querystring: z.object({
134
- name: z.string().min(4),
135
- }),
136
- response: {
137
- 200: z.string(),
138
- },
139
- },
140
- handler: (req, res) => {
141
- res.send(req.query.name);
142
- },
143
- });
144
- };
145
- ```
1
+ # Fastify Type Provider Zod
2
+
3
+ [![NPM Version](https://img.shields.io/npm/v/fastify-type-provider-zod.svg)](https://npmjs.org/package/fastify-type-provider-zod)
4
+ [![NPM Downloads](https://img.shields.io/npm/dm/fastify-type-provider-zod.svg)](https://npmjs.org/package/fastify-type-provider-zod)
5
+ [![Build Status](https://github.com//turkerdev/fastify-type-provider-zod/workflows/CI/badge.svg)](https://github.com//turkerdev/fastify-type-provider-zod/actions)
6
+
7
+ ## How to use?
8
+
9
+ ```js
10
+ import Fastify from "fastify";
11
+ import { serializerCompiler, validatorCompiler, ZodTypeProvider } from "fastify-type-provider-zod";
12
+ import z from "zod";
13
+
14
+ const app = Fastify()
15
+
16
+ // Add schema validator and serializer
17
+ app.setValidatorCompiler(validatorCompiler);
18
+ app.setSerializerCompiler(serializerCompiler);
19
+
20
+ app.withTypeProvider<ZodTypeProvider>().route({
21
+ method: "GET",
22
+ url: "/",
23
+ // Define your schema
24
+ schema: {
25
+ querystring: z.object({
26
+ name: z.string().min(4),
27
+ }),
28
+ response: {
29
+ 200: z.string(),
30
+ },
31
+ },
32
+ handler: (req, res) => {
33
+ res.send(req.query.name);
34
+ },
35
+ });
36
+
37
+ app.listen({ port: 4949 });
38
+ ```
39
+
40
+ You can also pass options to the `serializerCompiler` function:
41
+
42
+ ```ts
43
+ type ZodSerializerCompilerOptions = {
44
+ replacer?: ReplacerFunction;
45
+ };
46
+ ```
47
+
48
+ ```js
49
+ import Fastify from 'fastify';
50
+ import { createSerializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
51
+ import z from 'zod';
52
+
53
+ const app = Fastify();
54
+
55
+ const replacer = function (key, value) {
56
+ if (this[key] instanceof Date) {
57
+ return { _date: value.toISOString() };
58
+ }
59
+ return value;
60
+ };
61
+
62
+ // Create a custom serializer compiler
63
+ const customSerializerCompiler = createSerializerCompiler({ replacer });
64
+
65
+ // Add schema validator and serializer
66
+ app.setValidatorCompiler(validatorCompiler);
67
+ app.setSerializerCompiler(customSerializerCompiler);
68
+
69
+ // ...
70
+
71
+ app.listen({ port: 4949 });
72
+ ```
73
+
74
+ ## How to use together with @fastify/swagger
75
+
76
+ ```ts
77
+ import fastify from 'fastify';
78
+ import fastifySwagger from '@fastify/swagger';
79
+ import fastifySwaggerUI from '@fastify/swagger-ui';
80
+ import { z } from 'zod';
81
+
82
+ import {
83
+ jsonSchemaTransform,
84
+ createJsonSchemaTransform,
85
+ serializerCompiler,
86
+ validatorCompiler,
87
+ ZodTypeProvider,
88
+ } from 'fastify-type-provider-zod';
89
+
90
+ const app = fastify();
91
+ app.setValidatorCompiler(validatorCompiler);
92
+ app.setSerializerCompiler(serializerCompiler);
93
+
94
+ app.register(fastifySwagger, {
95
+ openapi: {
96
+ info: {
97
+ title: 'SampleApi',
98
+ description: 'Sample backend service',
99
+ version: '1.0.0',
100
+ },
101
+ servers: [],
102
+ },
103
+ transform: jsonSchemaTransform,
104
+
105
+ // You can also create transform with custom skiplist of endpoints that should not be included in the specification:
106
+ //
107
+ // transform: createJsonSchemaTransform({
108
+ // skipList: [ '/documentation/static/*' ]
109
+ // })
110
+ });
111
+
112
+ app.register(fastifySwaggerUI, {
113
+ routePrefix: '/documentation',
114
+ });
115
+
116
+ const LOGIN_SCHEMA = z.object({
117
+ username: z.string().max(32).describe('Some description for username'),
118
+ password: z.string().max(32),
119
+ });
120
+
121
+ app.after(() => {
122
+ app.withTypeProvider<ZodTypeProvider>().route({
123
+ method: 'POST',
124
+ url: '/login',
125
+ schema: { body: LOGIN_SCHEMA },
126
+ handler: (req, res) => {
127
+ res.send('ok');
128
+ },
129
+ });
130
+ });
131
+
132
+ async function run() {
133
+ await app.ready();
134
+
135
+ await app.listen({
136
+ port: 4949,
137
+ });
138
+
139
+ console.log(`Documentation running at http://localhost:4949/documentation`);
140
+ }
141
+
142
+ run();
143
+ ```
144
+
145
+ ## Customizing error responses
146
+
147
+ You can add custom handling of request and response validation errors to your fastify error handler like this:
148
+
149
+ ```ts
150
+ import { hasZodFastifySchemaValidationErrors } from 'fastify-type-provider-zod'
151
+
152
+ fastifyApp.setErrorHandler((err, req, reply) => {
153
+ if (hasZodFastifySchemaValidationErrors(err)) {
154
+ return reply.code(400).send({
155
+ error: 'Response Validation Error',
156
+ message: "Request doesn't match the schema",
157
+ statusCode: 400,
158
+ details: {
159
+ issues: err.validation,
160
+ method: req.method,
161
+ url: req.url,
162
+ },
163
+ })
164
+ }
165
+
166
+ if (isResponseSerializationError(err)) {
167
+ return reply.code(500).send({
168
+ error: 'Internal Server Error',
169
+ message: "Response doesn't match the schema",
170
+ statusCode: 500,
171
+ details: {
172
+ issues: err.cause.issues,
173
+ method: err.method,
174
+ url: err.url,
175
+ },
176
+ })
177
+ }
178
+
179
+ // the rest of the error handler
180
+ })
181
+ ```
182
+
183
+ ## How to create refs to the schemas?
184
+
185
+ When provided, this package will automatically create refs using the `jsonSchemaTransformObject` function. You register the schemas to the global zod registry and give it an `id` and fastifySwagger will create a OpenAPI document in which the schemas are referenced. The following example creates a ref to the `User` schema and will include the `User` schema in the OpenAPI document.
186
+
187
+ ```ts
188
+ import fastifySwagger from '@fastify/swagger';
189
+ import fastifySwaggerUI from '@fastify/swagger-ui';
190
+ import fastify from 'fastify';
191
+ import { z } from 'zod';
192
+ import type { ZodTypeProvider } from 'fastify-type-provider-zod';
193
+ import {
194
+ jsonSchemaTransformObject,
195
+ jsonSchemaTransform,
196
+ serializerCompiler,
197
+ validatorCompiler,
198
+ } from 'fastify-type-provider-zod';
199
+
200
+ const USER_SCHEMA = z.object({
201
+ id: z.number().int().positive(),
202
+ name: z.string().describe('The name of the user'),
203
+ });
204
+
205
+ z.globalRegistry.add(USER_SCHEMA, { id: 'User' })
206
+
207
+ const app = fastify();
208
+ app.setValidatorCompiler(validatorCompiler);
209
+ app.setSerializerCompiler(serializerCompiler);
210
+
211
+ app.register(fastifySwagger, {
212
+ openapi: {
213
+ info: {
214
+ title: 'SampleApi',
215
+ description: 'Sample backend service',
216
+ version: '1.0.0',
217
+ },
218
+ servers: [],
219
+ },
220
+ transform: jsonSchemaTransform,
221
+ transformObject: jsonSchemaTransformObject,
222
+ });
223
+
224
+ app.register(fastifySwaggerUI, {
225
+ routePrefix: '/documentation',
226
+ });
227
+
228
+ app.after(() => {
229
+ app.withTypeProvider<ZodTypeProvider>().route({
230
+ method: 'GET',
231
+ url: '/users',
232
+ schema: {
233
+ response: {
234
+ 200: USER_SCHEMA.array(),
235
+ },
236
+ },
237
+ handler: (req, res) => {
238
+ res.send([]);
239
+ },
240
+ });
241
+ });
242
+
243
+ async function run() {
244
+ await app.ready();
245
+
246
+ await app.listen({
247
+ port: 4949,
248
+ });
249
+
250
+ console.log(`Documentation running at http://localhost:4949/documentation`);
251
+ }
252
+
253
+ run();
254
+ ```
255
+
256
+ ## How to create a plugin?
257
+
258
+ ```ts
259
+ import { z } from 'zod';
260
+ import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod';
261
+
262
+ const plugin: FastifyPluginAsyncZod = async function (fastify, _opts) {
263
+ fastify.route({
264
+ method: 'GET',
265
+ url: '/',
266
+ // Define your schema
267
+ schema: {
268
+ querystring: z.object({
269
+ name: z.string().min(4),
270
+ }),
271
+ response: {
272
+ 200: z.string(),
273
+ },
274
+ },
275
+ handler: (req, res) => {
276
+ res.send(req.query.name);
277
+ },
278
+ });
279
+ };
280
+ ```
package/dist/index.d.ts CHANGED
@@ -1,86 +1,2 @@
1
- import type { FastifyPluginAsync, FastifyPluginCallback, FastifyPluginOptions, FastifySchema, FastifySchemaCompiler, FastifyTypeProvider, RawServerBase, RawServerDefault } from "fastify";
2
- import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from "openapi-types";
3
- import type { FastifySerializerCompiler } from "fastify/types/schema";
4
- import type { z } from "zod";
5
- type FreeformRecord = Record<string, any>;
6
- export declare const ResponseValidationError: import("@fastify/error").FastifyErrorConstructor<{
7
- code: string;
8
- }, [{
9
- cause: Error;
10
- }]>;
11
- export declare const InvalidSchemaError: import("@fastify/error").FastifyErrorConstructor<{
12
- code: string;
13
- }, [string]>;
14
- export interface ZodTypeProvider extends FastifyTypeProvider {
15
- validator: this["schema"] extends z.ZodTypeAny ? z.output<this["schema"]> : unknown;
16
- serializer: this["schema"] extends z.ZodTypeAny ? z.input<this["schema"]> : unknown;
17
- }
18
- interface Schema extends FastifySchema {
19
- hide?: boolean;
20
- }
21
- export declare const createJsonSchemaTransform: ({ skipList }: {
22
- skipList: readonly string[];
23
- }) => ({ schema, url }: {
24
- schema: Schema;
25
- url: string;
26
- }) => {
27
- schema: Schema;
28
- url: string;
29
- } | {
30
- schema: FreeformRecord;
31
- url: string;
32
- };
33
- export declare const jsonSchemaTransform: ({ schema, url }: {
34
- schema: Schema;
35
- url: string;
36
- }) => {
37
- schema: Schema;
38
- url: string;
39
- } | {
40
- schema: FreeformRecord;
41
- url: string;
42
- };
43
- export declare const ZodValidatorCompiler: FastifySchemaCompiler<z.ZodAny>;
44
- type ReplacerFunction = (this: any, key: string, value: any) => any;
45
- type ZodSerializerCompilerOptions = {
46
- replacer?: ReplacerFunction;
47
- };
48
- export declare const createZodSerializerCompiler: (options: ZodSerializerCompilerOptions) => FastifySerializerCompiler<z.ZodAny | {
49
- properties: z.ZodAny;
50
- }>;
51
- export declare const ZodSerializerCompiler: FastifySerializerCompiler<z.ZodAny | {
52
- properties: z.ZodAny;
53
- }>;
54
- export declare const createJsonSchemaTransformObject: ({ schemas: zodSchemas }: {
55
- schemas: Record<string, z.ZodTypeAny>;
56
- }) => (input: {
57
- swaggerObject: Partial<OpenAPIV2.Document>;
58
- } | {
59
- openapiObject: Partial<OpenAPIV3.Document | OpenAPIV3_1.Document>;
60
- }) => any;
61
- /**
62
- * FastifyPluginCallbackZod with Zod automatic type inference
63
- *
64
- * @example
65
- * ```typescript
66
- * import { FastifyPluginCallbackZod } from "fastify-type-provider-zod"
67
- *
68
- * const plugin: FastifyPluginCallbackZod = (fastify, options, done) => {
69
- * done()
70
- * }
71
- * ```
72
- */
73
- export type FastifyPluginCallbackZod<Options extends FastifyPluginOptions = Record<never, never>, Server extends RawServerBase = RawServerDefault> = FastifyPluginCallback<Options, Server, ZodTypeProvider>;
74
- /**
75
- * FastifyPluginAsyncZod with Zod automatic type inference
76
- *
77
- * @example
78
- * ```typescript
79
- * import { FastifyPluginAsyncZod } from "fastify-type-provider-zod"
80
- *
81
- * const plugin: FastifyPluginAsyncZod = async (fastify, options) => {
82
- * }
83
- * ```
84
- */
85
- export type FastifyPluginAsyncZod<Options extends FastifyPluginOptions = Record<never, never>, Server extends RawServerBase = RawServerDefault> = FastifyPluginAsync<Options, Server, ZodTypeProvider>;
86
- export {};
1
+ export { type ZodTypeProvider, type FastifyPluginAsyncZod, type FastifyPluginCallbackZod, type ZodSerializerCompilerOptions, jsonSchemaTransform, createJsonSchemaTransform, jsonSchemaTransformObject, serializerCompiler, validatorCompiler, createSerializerCompiler, } from './src/core';
2
+ export { type ZodFastifySchemaValidationError, ResponseSerializationError, InvalidSchemaError, hasZodFastifySchemaValidationErrors, isResponseSerializationError, } from './src/errors';
package/dist/index.js CHANGED
@@ -1,161 +1,15 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.createJsonSchemaTransformObject = exports.ZodSerializerCompiler = exports.createZodSerializerCompiler = exports.ZodValidatorCompiler = exports.jsonSchemaTransform = exports.createJsonSchemaTransform = exports.InvalidSchemaError = exports.ResponseValidationError = void 0;
7
- const error_1 = __importDefault(require("@fastify/error"));
8
- const zod_to_json_schema_1 = require("zod-to-json-schema");
9
- const defaultSkipList = [
10
- "/documentation/",
11
- "/documentation/initOAuth",
12
- "/documentation/json",
13
- "/documentation/uiConfig",
14
- "/documentation/yaml",
15
- "/documentation/*",
16
- "/documentation/static/*",
17
- ];
18
- exports.ResponseValidationError = (0, error_1.default)("FST_ERR_RESPONSE_VALIDATION", "Response doesn't match the schema", 500);
19
- exports.InvalidSchemaError = (0, error_1.default)("FST_ERR_INVALID_SCHEMA", "Invalid schema passed: %s", 500);
20
- const zodToJsonSchemaOptions = {
21
- target: "openApi3",
22
- $refStrategy: "none",
23
- };
24
- const createJsonSchemaTransform = ({ skipList }) => {
25
- return ({ schema, url }) => {
26
- if (!schema) {
27
- return {
28
- schema,
29
- url,
30
- };
31
- }
32
- const { response, headers, querystring, body, params, hide, ...rest } = schema;
33
- const transformed = {};
34
- if (skipList.includes(url) || hide) {
35
- transformed.hide = true;
36
- return { schema: transformed, url };
37
- }
38
- const zodSchemas = { headers, querystring, body, params };
39
- for (const prop in zodSchemas) {
40
- const zodSchema = zodSchemas[prop];
41
- if (zodSchema) {
42
- transformed[prop] = (0, zod_to_json_schema_1.zodToJsonSchema)(zodSchema, zodToJsonSchemaOptions);
43
- }
44
- }
45
- if (response) {
46
- transformed.response = {};
47
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
48
- for (const prop in response) {
49
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
50
- const schema = resolveSchema(response[prop]);
51
- const transformedResponse = (0, zod_to_json_schema_1.zodToJsonSchema)(
52
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
53
- schema, zodToJsonSchemaOptions);
54
- transformed.response[prop] = transformedResponse;
55
- }
56
- }
57
- for (const prop in rest) {
58
- const meta = rest[prop];
59
- if (meta) {
60
- transformed[prop] = meta;
61
- }
62
- }
63
- return { schema: transformed, url };
64
- };
65
- };
66
- exports.createJsonSchemaTransform = createJsonSchemaTransform;
67
- exports.jsonSchemaTransform = (0, exports.createJsonSchemaTransform)({
68
- skipList: defaultSkipList,
69
- });
70
- const ZodValidatorCompiler = ({ schema }) => (data) => {
71
- const result = schema.safeParse(data);
72
- if (result.success) {
73
- return { value: result.data };
74
- }
75
- else {
76
- return {
77
- error: result.error.errors.map(error => ({
78
- keyword: error.code,
79
- instancePath: `/${error.path.join("/")}`,
80
- schemaPath: `#/${error.path.join("/")}/${error.code}`,
81
- params: {
82
- code: error.code,
83
- zodError: result.error,
84
- },
85
- message: error.message,
86
- })),
87
- };
88
- }
89
- };
90
- exports.ZodValidatorCompiler = ZodValidatorCompiler;
91
- const resolveSchema = (maybeSchema) => {
92
- if ("safeParse" in maybeSchema) {
93
- return maybeSchema;
94
- }
95
- if ("properties" in maybeSchema) {
96
- return maybeSchema.properties;
97
- }
98
- throw new exports.InvalidSchemaError(JSON.stringify(maybeSchema));
99
- };
100
- const createZodSerializerCompiler = (options) => ({ schema: maybeSchema }) => (data) => {
101
- const schema = resolveSchema(maybeSchema);
102
- const result = schema.safeParse(data);
103
- if (result.success) {
104
- return JSON.stringify(result.data, options.replacer);
105
- }
106
- throw new exports.ResponseValidationError({ cause: result.error });
107
- };
108
- exports.createZodSerializerCompiler = createZodSerializerCompiler;
109
- exports.ZodSerializerCompiler = (0, exports.createZodSerializerCompiler)({});
110
- const createJsonSchemaTransformObject = ({ schemas: zodSchemas }) => (input) => {
111
- if ("swaggerObject" in input) {
112
- console.warn("This package currently does not support component references for Swagger 2.0");
113
- return input.swaggerObject;
114
- }
115
- const schemas = {};
116
- for (const key in zodSchemas) {
117
- schemas[key] = (0, zod_to_json_schema_1.zodToJsonSchema)(zodSchemas[key], zodToJsonSchemaOptions);
118
- }
119
- const document = {
120
- ...input.openapiObject,
121
- components: {
122
- ...input.openapiObject.components,
123
- schemas: {
124
- ...input.openapiObject.components?.schemas,
125
- ...schemas,
126
- },
127
- },
128
- };
129
- const componentMapVK = new Map();
130
- Object.entries(schemas).forEach(([key, value]) => componentMapVK.set(JSON.stringify(value), key));
131
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
132
- function componentReplacer(key, value) {
133
- if (typeof value !== "object") {
134
- return value;
135
- }
136
- // Check if the parent is the schemas object, if so, return the value as is
137
- if (this === document.components.schemas) {
138
- return value;
139
- }
140
- const stringifiedValue = JSON.stringify(value);
141
- if (componentMapVK.has(stringifiedValue)) {
142
- return { $ref: `#/components/schemas/${componentMapVK.get(stringifiedValue)}` };
143
- }
144
- if (value.nullable === true) {
145
- const nonNullableValue = { ...value };
146
- delete nonNullableValue.nullable;
147
- const stringifiedNonNullableValue = JSON.stringify(nonNullableValue);
148
- if (componentMapVK.has(stringifiedNonNullableValue)) {
149
- return {
150
- anyOf: [
151
- { $ref: `#/components/schemas/${componentMapVK.get(stringifiedNonNullableValue)}` },
152
- ],
153
- nullable: true,
154
- };
155
- }
156
- }
157
- return value;
158
- }
159
- return JSON.parse(JSON.stringify(document, componentReplacer));
160
- };
161
- exports.createJsonSchemaTransformObject = createJsonSchemaTransformObject;
3
+ exports.isResponseSerializationError = exports.hasZodFastifySchemaValidationErrors = exports.InvalidSchemaError = exports.ResponseSerializationError = exports.createSerializerCompiler = exports.validatorCompiler = exports.serializerCompiler = exports.jsonSchemaTransformObject = exports.createJsonSchemaTransform = exports.jsonSchemaTransform = void 0;
4
+ var core_1 = require("./src/core");
5
+ Object.defineProperty(exports, "jsonSchemaTransform", { enumerable: true, get: function () { return core_1.jsonSchemaTransform; } });
6
+ Object.defineProperty(exports, "createJsonSchemaTransform", { enumerable: true, get: function () { return core_1.createJsonSchemaTransform; } });
7
+ Object.defineProperty(exports, "jsonSchemaTransformObject", { enumerable: true, get: function () { return core_1.jsonSchemaTransformObject; } });
8
+ Object.defineProperty(exports, "serializerCompiler", { enumerable: true, get: function () { return core_1.serializerCompiler; } });
9
+ Object.defineProperty(exports, "validatorCompiler", { enumerable: true, get: function () { return core_1.validatorCompiler; } });
10
+ Object.defineProperty(exports, "createSerializerCompiler", { enumerable: true, get: function () { return core_1.createSerializerCompiler; } });
11
+ var errors_1 = require("./src/errors");
12
+ Object.defineProperty(exports, "ResponseSerializationError", { enumerable: true, get: function () { return errors_1.ResponseSerializationError; } });
13
+ Object.defineProperty(exports, "InvalidSchemaError", { enumerable: true, get: function () { return errors_1.InvalidSchemaError; } });
14
+ Object.defineProperty(exports, "hasZodFastifySchemaValidationErrors", { enumerable: true, get: function () { return errors_1.hasZodFastifySchemaValidationErrors; } });
15
+ Object.defineProperty(exports, "isResponseSerializationError", { enumerable: true, get: function () { return errors_1.isResponseSerializationError; } });
@@ -0,0 +1,58 @@
1
+ import type { SwaggerTransform, SwaggerTransformObject } from '@fastify/swagger';
2
+ import type { FastifyPluginAsync, FastifyPluginCallback, FastifyPluginOptions, FastifySchema, FastifySchemaCompiler, FastifyTypeProvider, RawServerBase, RawServerDefault } from 'fastify';
3
+ import type { FastifySerializerCompiler } from 'fastify/types/schema';
4
+ import { z } from 'zod';
5
+ export interface ZodTypeProvider extends FastifyTypeProvider {
6
+ validator: this['schema'] extends z.ZodTypeAny ? z.output<this['schema']> : unknown;
7
+ serializer: this['schema'] extends z.ZodTypeAny ? z.input<this['schema']> : unknown;
8
+ }
9
+ interface Schema extends FastifySchema {
10
+ hide?: boolean;
11
+ }
12
+ type CreateJsonSchemaTransformOptions = {
13
+ skipList: readonly string[];
14
+ };
15
+ export declare const createJsonSchemaTransform: ({ skipList, }: CreateJsonSchemaTransformOptions) => SwaggerTransform<Schema>;
16
+ export declare const jsonSchemaTransform: SwaggerTransform<Schema>;
17
+ type CreateJsonSchemaTransformObjectOptions = {
18
+ schemaRegistry: z.core.$ZodJSONSchemaRegistry;
19
+ };
20
+ export declare const createJsonSchemaTransformObject: ({ schemaRegistry }: CreateJsonSchemaTransformObjectOptions) => SwaggerTransformObject;
21
+ export declare const jsonSchemaTransformObject: SwaggerTransformObject;
22
+ export declare const validatorCompiler: FastifySchemaCompiler<z.ZodTypeAny>;
23
+ type ReplacerFunction = (this: any, key: string, value: any) => any;
24
+ export type ZodSerializerCompilerOptions = {
25
+ replacer?: ReplacerFunction;
26
+ };
27
+ export declare const createSerializerCompiler: (options?: ZodSerializerCompilerOptions) => FastifySerializerCompiler<z.ZodTypeAny | {
28
+ properties: z.ZodTypeAny;
29
+ }>;
30
+ export declare const serializerCompiler: FastifySerializerCompiler<z.ZodType<unknown, unknown> | {
31
+ properties: z.ZodTypeAny;
32
+ }>;
33
+ /**
34
+ * FastifyPluginCallbackZod with Zod automatic type inference
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * import { FastifyPluginCallbackZod } from "fastify-type-provider-zod"
39
+ *
40
+ * const plugin: FastifyPluginCallbackZod = (fastify, options, done) => {
41
+ * done()
42
+ * }
43
+ * ```
44
+ */
45
+ export type FastifyPluginCallbackZod<Options extends FastifyPluginOptions = Record<never, never>, Server extends RawServerBase = RawServerDefault> = FastifyPluginCallback<Options, Server, ZodTypeProvider>;
46
+ /**
47
+ * FastifyPluginAsyncZod with Zod automatic type inference
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * import { FastifyPluginAsyncZod } from "fastify-type-provider-zod"
52
+ *
53
+ * const plugin: FastifyPluginAsyncZod = async (fastify, options) => {
54
+ * }
55
+ * ```
56
+ */
57
+ export type FastifyPluginAsyncZod<Options extends FastifyPluginOptions = Record<never, never>, Server extends RawServerBase = RawServerDefault> = FastifyPluginAsync<Options, Server, ZodTypeProvider>;
58
+ export {};
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.serializerCompiler = exports.createSerializerCompiler = exports.validatorCompiler = exports.jsonSchemaTransformObject = exports.createJsonSchemaTransformObject = exports.jsonSchemaTransform = exports.createJsonSchemaTransform = void 0;
4
+ const zod_1 = require("zod");
5
+ const errors_1 = require("./errors");
6
+ const defaultSkipList = [
7
+ '/documentation/',
8
+ '/documentation/initOAuth',
9
+ '/documentation/json',
10
+ '/documentation/uiConfig',
11
+ '/documentation/yaml',
12
+ '/documentation/*',
13
+ '/documentation/static/*',
14
+ ];
15
+ const zodtoJSONSchemaOptions = {
16
+ uri: (id) => `#/components/schemas/${id}`,
17
+ external: {
18
+ registry: zod_1.z.globalRegistry,
19
+ uri: (id) => `#/components/schemas/${id}`,
20
+ defs: {},
21
+ },
22
+ };
23
+ const createJsonSchemaTransform = ({ skipList, }) => {
24
+ return ({ schema, url }) => {
25
+ if (!schema) {
26
+ return {
27
+ schema,
28
+ url,
29
+ };
30
+ }
31
+ const { response, headers, querystring, body, params, hide, ...rest } = schema;
32
+ const transformed = {};
33
+ if (skipList.includes(url) || hide) {
34
+ transformed.hide = true;
35
+ return { schema: transformed, url };
36
+ }
37
+ const zodSchemas = { headers, querystring, body, params };
38
+ for (const prop in zodSchemas) {
39
+ const zodSchema = zodSchemas[prop];
40
+ if (zodSchema) {
41
+ transformed[prop] = zod_1.z.toJSONSchema(zodSchema, zodtoJSONSchemaOptions);
42
+ }
43
+ }
44
+ if (response) {
45
+ transformed.response = {};
46
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
47
+ for (const prop in response) {
48
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
49
+ const zodSchema = resolveSchema(response[prop]);
50
+ const transformedResponse = zod_1.z.toJSONSchema(zodSchema, zodtoJSONSchemaOptions);
51
+ transformed.response[prop] = transformedResponse;
52
+ }
53
+ }
54
+ for (const prop in rest) {
55
+ const meta = rest[prop];
56
+ if (meta) {
57
+ transformed[prop] = meta;
58
+ }
59
+ }
60
+ return { schema: transformed, url };
61
+ };
62
+ };
63
+ exports.createJsonSchemaTransform = createJsonSchemaTransform;
64
+ exports.jsonSchemaTransform = (0, exports.createJsonSchemaTransform)({
65
+ skipList: defaultSkipList,
66
+ });
67
+ const createJsonSchemaTransformObject = ({ schemaRegistry }) => (input) => {
68
+ if ('swaggerObject' in input) {
69
+ console.warn('This package currently does not support component references for Swagger 2.0');
70
+ return input.swaggerObject;
71
+ }
72
+ const { schemas } = zod_1.z.toJSONSchema(schemaRegistry, zodtoJSONSchemaOptions);
73
+ return {
74
+ ...input.openapiObject,
75
+ components: {
76
+ ...input.openapiObject.components,
77
+ schemas: {
78
+ ...input.openapiObject.components?.schemas,
79
+ ...schemas,
80
+ },
81
+ },
82
+ };
83
+ };
84
+ exports.createJsonSchemaTransformObject = createJsonSchemaTransformObject;
85
+ exports.jsonSchemaTransformObject = (0, exports.createJsonSchemaTransformObject)({
86
+ schemaRegistry: zod_1.z.globalRegistry,
87
+ });
88
+ const validatorCompiler = ({ schema }) => (data) => {
89
+ const result = schema.safeParse(data);
90
+ if (result.error) {
91
+ return { error: (0, errors_1.createValidationError)(result.error) };
92
+ }
93
+ return { value: result.data };
94
+ };
95
+ exports.validatorCompiler = validatorCompiler;
96
+ function resolveSchema(maybeSchema) {
97
+ if ('safeParse' in maybeSchema) {
98
+ return maybeSchema;
99
+ }
100
+ if ('properties' in maybeSchema) {
101
+ return maybeSchema.properties;
102
+ }
103
+ throw new errors_1.InvalidSchemaError(JSON.stringify(maybeSchema));
104
+ }
105
+ const createSerializerCompiler = (options) => ({ schema: maybeSchema, method, url }) => (data) => {
106
+ const schema = resolveSchema(maybeSchema);
107
+ const result = schema.safeParse(data);
108
+ if (result.error) {
109
+ throw new errors_1.ResponseSerializationError(method, url, { cause: result.error });
110
+ }
111
+ return JSON.stringify(result.data, options?.replacer);
112
+ };
113
+ exports.createSerializerCompiler = createSerializerCompiler;
114
+ exports.serializerCompiler = (0, exports.createSerializerCompiler)({});
@@ -0,0 +1,35 @@
1
+ import type { FastifyError } from 'fastify';
2
+ import type { z } from 'zod';
3
+ declare const ResponseSerializationError_base: import("@fastify/error").FastifyErrorConstructor<{
4
+ code: string;
5
+ }, [{
6
+ cause: z.core.$ZodError;
7
+ }]>;
8
+ export declare class ResponseSerializationError extends ResponseSerializationError_base {
9
+ method: string;
10
+ url: string;
11
+ cause: z.core.$ZodError;
12
+ constructor(method: string, url: string, options: {
13
+ cause: z.core.$ZodError;
14
+ });
15
+ }
16
+ export declare function isResponseSerializationError(value: unknown): value is ResponseSerializationError;
17
+ export declare const InvalidSchemaError: import("@fastify/error").FastifyErrorConstructor<{
18
+ code: string;
19
+ }, [string]>;
20
+ declare const ZodFastifySchemaValidationErrorSymbol: unique symbol;
21
+ export type ZodFastifySchemaValidationError = {
22
+ [ZodFastifySchemaValidationErrorSymbol]: true;
23
+ keyword: string;
24
+ instancePath: string;
25
+ schemaPath: string;
26
+ params: {
27
+ issue: z.core.$ZodIssue;
28
+ };
29
+ message: string;
30
+ };
31
+ export declare const hasZodFastifySchemaValidationErrors: (error: unknown) => error is Omit<FastifyError, "validation"> & {
32
+ validation: ZodFastifySchemaValidationError[];
33
+ };
34
+ export declare const createValidationError: (error: z.core.$ZodError) => ZodFastifySchemaValidationError[];
35
+ export {};
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createValidationError = exports.hasZodFastifySchemaValidationErrors = exports.InvalidSchemaError = exports.ResponseSerializationError = void 0;
7
+ exports.isResponseSerializationError = isResponseSerializationError;
8
+ const error_1 = __importDefault(require("@fastify/error"));
9
+ class ResponseSerializationError extends (0, error_1.default)('FST_ERR_RESPONSE_SERIALIZATION', "Response doesn't match the schema", 500) {
10
+ constructor(method, url, options) {
11
+ super({ cause: options.cause });
12
+ this.method = method;
13
+ this.url = url;
14
+ }
15
+ }
16
+ exports.ResponseSerializationError = ResponseSerializationError;
17
+ function isResponseSerializationError(value) {
18
+ return 'method' in value;
19
+ }
20
+ exports.InvalidSchemaError = (0, error_1.default)('FST_ERR_INVALID_SCHEMA', 'Invalid schema passed: %s', 500);
21
+ const ZodFastifySchemaValidationErrorSymbol = Symbol.for('ZodFastifySchemaValidationError');
22
+ const isZodFastifySchemaValidationError = (error) => typeof error === 'object' &&
23
+ error !== null &&
24
+ ZodFastifySchemaValidationErrorSymbol in error &&
25
+ error[ZodFastifySchemaValidationErrorSymbol] === true;
26
+ const hasZodFastifySchemaValidationErrors = (error) => typeof error === 'object' &&
27
+ error !== null &&
28
+ 'validation' in error &&
29
+ Array.isArray(error.validation) &&
30
+ error.validation.length > 0 &&
31
+ isZodFastifySchemaValidationError(error.validation[0]);
32
+ exports.hasZodFastifySchemaValidationErrors = hasZodFastifySchemaValidationErrors;
33
+ const createValidationError = (error) => error.issues.map((issue) => ({
34
+ [ZodFastifySchemaValidationErrorSymbol]: true,
35
+ keyword: issue.code ?? 'custom',
36
+ instancePath: `/${issue.path.join('/')}`,
37
+ schemaPath: `#/${issue.path.join('/')}/${issue.code}`,
38
+ params: {
39
+ issue,
40
+ },
41
+ message: issue.message,
42
+ }));
43
+ exports.createValidationError = createValidationError;
package/package.json CHANGED
@@ -1,62 +1,61 @@
1
- {
2
- "name": "@bram-dc/fastify-type-provider-zod",
3
- "version": "3.1.1",
4
- "description": "Zod Type Provider for Fastify@5",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "files": [
8
- "README.md",
9
- "LICENSE",
10
- "dist"
11
- ],
12
- "scripts": {
13
- "build": "tsc",
14
- "test": "npm run build && npm run typescript && vitest",
15
- "lint": "eslint .",
16
- "lint:fix": "eslint --fix .",
17
- "typescript": "tsd",
18
- "prepublishOnly": "npm run build"
19
- },
20
- "peerDependencies": {
21
- "fastify": "^5.0.0",
22
- "zod": "^3.23.8"
23
- },
24
- "repository": {
25
- "url": "https://github.com/bram-dc/fastify-type-provider-zod"
26
- },
27
- "keywords": [
28
- "fastify",
29
- "zod",
30
- "type",
31
- "provider"
32
- ],
33
- "author": "turkerd",
34
- "license": "MIT",
35
- "bugs": {
36
- "url": "https://github.com/bram-dc/fastify-type-provider-zod/issues"
37
- },
38
- "homepage": "https://github.com/bram-dc/fastify-type-provider-zod",
39
- "dependencies": {
40
- "@fastify/error": "^4.0.0",
41
- "zod-to-json-schema": "^3.23.3"
42
- },
43
- "devDependencies": {
44
- "@fastify/swagger": "^9.0.0",
45
- "@fastify/swagger-ui": "^5.0.1",
46
- "@stylistic/eslint-plugin": "^2.8.0",
47
- "@types/node": "^22.5.5",
48
- "eslint": "^9.10.0",
49
- "fastify": "^5.0.0",
50
- "fastify-plugin": "^5.0.0",
51
- "oas-validator": "^5.0.8",
52
- "openapi-types": "^12.1.3",
53
- "tsd": "^0.31.2",
54
- "typescript": "^5.6.2",
55
- "typescript-eslint": "^8.6.0",
56
- "vitest": "^2.1.1",
57
- "zod": "^3.23.8"
58
- },
59
- "tsd": {
60
- "directory": "types"
61
- }
62
- }
1
+ {
2
+ "name": "@bram-dc/fastify-type-provider-zod",
3
+ "version": "4.0.2",
4
+ "description": "Zod Type Provider for Fastify@5",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "README.md",
9
+ "LICENSE",
10
+ "dist"
11
+ ],
12
+ "scripts": {
13
+ "build": "tsc",
14
+ "test": "npm run build && npm run typescript && vitest",
15
+ "test:coverage": "vitest --coverage",
16
+ "lint": "biome check . && tsc --project tsconfig.lint.json --noEmit",
17
+ "lint:fix": "biome check --write .",
18
+ "typescript": "tsd",
19
+ "prepublishOnly": "npm run build"
20
+ },
21
+ "peerDependencies": {
22
+ "fastify": "^5.0.0",
23
+ "zod": "^4.0.0-beta.20250412T085909"
24
+ },
25
+ "repository": {
26
+ "url": "https://github.com/turkerdev/fastify-type-provider-zod"
27
+ },
28
+ "keywords": [
29
+ "fastify",
30
+ "zod",
31
+ "type",
32
+ "provider"
33
+ ],
34
+ "author": "turkerd",
35
+ "license": "MIT",
36
+ "bugs": {
37
+ "url": "https://github.com/turkerdev/fastify-type-provider-zod/issues"
38
+ },
39
+ "homepage": "https://github.com/turkerdev/fastify-type-provider-zod",
40
+ "dependencies": {
41
+ "@fastify/error": "^4.0.0"
42
+ },
43
+ "devDependencies": {
44
+ "@biomejs/biome": "^1.9.3",
45
+ "@fastify/swagger": "^9.1.0",
46
+ "@fastify/swagger-ui": "^5.0.1",
47
+ "@kibertoad/biome-config": "^1.2.1",
48
+ "@types/node": "^20.16.10",
49
+ "@vitest/coverage-v8": "^2.1.2",
50
+ "fastify": "^5.0.0",
51
+ "fastify-plugin": "^5.0.1",
52
+ "oas-validator": "^5.0.8",
53
+ "tsd": "^0.31.2",
54
+ "typescript": "^5.6.2",
55
+ "vitest": "^2.1.2",
56
+ "zod": "^4.0.0-beta.20250412T085909"
57
+ },
58
+ "tsd": {
59
+ "directory": "types"
60
+ }
61
+ }