@bram-dc/fastify-type-provider-zod 5.0.2 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +83 -46
  2. package/dist/cjs/core.cjs +125 -0
  3. package/dist/cjs/core.cjs.map +1 -0
  4. package/dist/cjs/core.d.cts +68 -0
  5. package/dist/cjs/errors.cjs +57 -0
  6. package/dist/cjs/errors.cjs.map +1 -0
  7. package/dist/cjs/errors.d.cts +30 -0
  8. package/dist/cjs/index.cjs +16 -0
  9. package/dist/cjs/index.cjs.map +1 -0
  10. package/dist/cjs/index.d.cts +2 -0
  11. package/dist/cjs/registry.cjs +43 -0
  12. package/dist/cjs/registry.cjs.map +1 -0
  13. package/dist/cjs/registry.d.cts +9 -0
  14. package/dist/cjs/utils.cjs +21 -0
  15. package/dist/cjs/utils.cjs.map +1 -0
  16. package/dist/cjs/utils.d.cts +12 -0
  17. package/dist/cjs/zod-to-json.cjs +93 -0
  18. package/dist/cjs/zod-to-json.cjs.map +1 -0
  19. package/dist/cjs/zod-to-json.d.cts +8 -0
  20. package/dist/esm/core.d.ts +68 -0
  21. package/dist/esm/core.js +125 -0
  22. package/dist/esm/core.js.map +1 -0
  23. package/dist/esm/errors.d.ts +30 -0
  24. package/dist/esm/errors.js +57 -0
  25. package/dist/esm/errors.js.map +1 -0
  26. package/dist/esm/index.d.ts +2 -0
  27. package/dist/esm/index.js +16 -0
  28. package/dist/esm/index.js.map +1 -0
  29. package/dist/esm/registry.d.ts +9 -0
  30. package/dist/esm/registry.js +43 -0
  31. package/dist/esm/registry.js.map +1 -0
  32. package/dist/esm/utils.d.ts +12 -0
  33. package/dist/esm/utils.js +21 -0
  34. package/dist/esm/utils.js.map +1 -0
  35. package/dist/esm/zod-to-json.d.ts +8 -0
  36. package/dist/esm/zod-to-json.js +93 -0
  37. package/dist/esm/zod-to-json.js.map +1 -0
  38. package/package.json +75 -58
  39. package/src/core.ts +228 -0
  40. package/src/errors.ts +99 -0
  41. package/src/index.ts +21 -0
  42. package/src/registry.ts +64 -0
  43. package/src/utils.ts +33 -0
  44. package/src/zod-to-json.ts +160 -0
  45. package/dist/index.d.ts +0 -2
  46. package/dist/index.js +0 -16
  47. package/dist/src/core.d.ts +0 -59
  48. package/dist/src/core.js +0 -121
  49. package/dist/src/errors.d.ts +0 -35
  50. package/dist/src/errors.js +0 -43
package/README.md CHANGED
@@ -4,22 +4,37 @@
4
4
  [![NPM Downloads](https://img.shields.io/npm/dm/fastify-type-provider-zod.svg)](https://npmjs.org/package/fastify-type-provider-zod)
5
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
6
 
7
+ ## Zod compatibility
8
+
9
+ | fastify-type-provider-zod | zod |
10
+ |---------------------------|-------|
11
+ | <=4.x | v3 |
12
+ | >=5.x <7.x | v4 |
13
+ | >=7.x | v4.3+ |
14
+
15
+ > **Important (v7+)**
16
+ >
17
+ > Starting from **v7**, this library uses Zod’s `.encode()` / `.decode()` APIs introduced in **Zod 4.3**.
18
+ > Because of this change, **response serialization is now based on `z.output<T>` instead of `z.input<T>`**.
19
+ >
20
+ > This means Fastify serializers always expect the **post-transformation output type** of your Zod schemas.
21
+
7
22
  ## How to use?
8
23
 
9
- ```js
10
- import Fastify from "fastify";
11
- import { serializerCompiler, validatorCompiler, ZodTypeProvider } from "fastify-type-provider-zod";
12
- import z from "zod";
24
+ ```ts
25
+ import type { ZodTypeProvider } from 'fastify-type-provider-zod';
26
+ import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
27
+ import { z } from 'zod/v4';
13
28
 
14
- const app = Fastify()
29
+ const app = Fastify();
15
30
 
16
31
  // Add schema validator and serializer
17
32
  app.setValidatorCompiler(validatorCompiler);
18
33
  app.setSerializerCompiler(serializerCompiler);
19
34
 
20
35
  app.withTypeProvider<ZodTypeProvider>().route({
21
- method: "GET",
22
- url: "/",
36
+ method: 'GET',
37
+ url: '/',
23
38
  // Define your schema
24
39
  schema: {
25
40
  querystring: z.object({
@@ -45,10 +60,9 @@ type ZodSerializerCompilerOptions = {
45
60
  };
46
61
  ```
47
62
 
48
- ```js
63
+ ```ts
49
64
  import Fastify from 'fastify';
50
65
  import { createSerializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
51
- import z from 'zod';
52
66
 
53
67
  const app = Fastify();
54
68
 
@@ -77,14 +91,13 @@ app.listen({ port: 4949 });
77
91
  import fastify from 'fastify';
78
92
  import fastifySwagger from '@fastify/swagger';
79
93
  import fastifySwaggerUI from '@fastify/swagger-ui';
80
- import { z } from 'zod';
81
-
94
+ import { z } from 'zod/v4';
95
+ import type { ZodTypeProvider } from 'fastify-type-provider-zod';
82
96
  import {
83
97
  jsonSchemaTransform,
84
98
  createJsonSchemaTransform,
85
99
  serializerCompiler,
86
100
  validatorCompiler,
87
- ZodTypeProvider,
88
101
  } from 'fastify-type-provider-zod';
89
102
 
90
103
  const app = fastify();
@@ -147,48 +160,50 @@ run();
147
160
  You can add custom handling of request and response validation errors to your fastify error handler like this:
148
161
 
149
162
  ```ts
150
- import { hasZodFastifySchemaValidationErrors } from 'fastify-type-provider-zod'
163
+ import { hasZodFastifySchemaValidationErrors } from 'fastify-type-provider-zod';
151
164
 
152
165
  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
- })
166
+ if (hasZodFastifySchemaValidationErrors(err)) {
167
+ return reply.code(400).send({
168
+ error: 'Response Validation Error',
169
+ message: "Request doesn't match the schema",
170
+ statusCode: 400,
171
+ details: {
172
+ issues: err.validation,
173
+ method: req.method,
174
+ url: req.url,
175
+ },
176
+ });
177
+ }
178
+
179
+ if (isResponseSerializationError(err)) {
180
+ return reply.code(500).send({
181
+ error: 'Internal Server Error',
182
+ message: "Response doesn't match the schema",
183
+ statusCode: 500,
184
+ details: {
185
+ issues: err.cause.issues,
186
+ method: err.method,
187
+ url: err.url,
188
+ },
189
+ });
190
+ }
191
+
192
+ // the rest of the error handler
193
+ });
181
194
  ```
182
195
 
183
196
  ## How to create refs to the schemas?
184
197
 
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.
198
+ When provided, this package will automatically create refs using the `jsonSchemaTransformObject` function. You register the schemas with the global Zod registry and assign them an `id`. `fastifySwagger` will then create an OpenAPI document that references the schemas.
199
+
200
+ The following example creates a ref to the `User` schema and will include the `User` schema in the OpenAPI document.
186
201
 
187
202
  ```ts
188
203
  import fastifySwagger from '@fastify/swagger';
189
204
  import fastifySwaggerUI from '@fastify/swagger-ui';
190
205
  import fastify from 'fastify';
191
- import { z } from 'zod';
206
+ import { z } from 'zod/v4';
192
207
  import type { ZodTypeProvider } from 'fastify-type-provider-zod';
193
208
  import {
194
209
  jsonSchemaTransformObject,
@@ -202,7 +217,7 @@ const USER_SCHEMA = z.object({
202
217
  name: z.string().describe('The name of the user'),
203
218
  });
204
219
 
205
- z.globalRegistry.add(USER_SCHEMA, { id: 'User' })
220
+ z.globalRegistry.add(USER_SCHEMA, { id: 'User' });
206
221
 
207
222
  const app = fastify();
208
223
  app.setValidatorCompiler(validatorCompiler);
@@ -256,8 +271,8 @@ run();
256
271
  ## How to create a plugin?
257
272
 
258
273
  ```ts
259
- import { z } from 'zod';
260
- import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod';
274
+ import { z } from 'zod/v4';
275
+ import type { FastifyPluginAsyncZod } from 'fastify-type-provider-zod';
261
276
 
262
277
  const plugin: FastifyPluginAsyncZod = async function (fastify, _opts) {
263
278
  fastify.route({
@@ -278,3 +293,25 @@ const plugin: FastifyPluginAsyncZod = async function (fastify, _opts) {
278
293
  });
279
294
  };
280
295
  ```
296
+
297
+ ## How to specify different OpenAPI targets
298
+
299
+ You can specify different JSON Schema targets for OpenAPI compatibility using the `createJsonSchemaTransform` function with the `zodToJsonConfig.target` option.
300
+
301
+ By default target "openapi-3.0" is used for documents with "openapi" field set to "3.0.x", and target "draft-2020-12" is used for documents with "openapi" field set to "3.1.x".
302
+
303
+ ### Usage
304
+
305
+ ```typescript
306
+ import { createJsonSchemaTransform } from "fastify-type-provider-zod";
307
+
308
+ // For OpenAPI 3.0.x compatibility
309
+ const transform = createJsonSchemaTransform({
310
+ zodToJsonConfig: { target: "openapi-3.0" },
311
+ });
312
+
313
+ // For OpenAPI 3.1+
314
+ const transform = createJsonSchemaTransform({
315
+ zodToJsonConfig: { target: "draft-2020-12" },
316
+ });
317
+ ```
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const core = require("zod/v4/core");
4
+ const errors = require("./errors.cjs");
5
+ const registry = require("./registry.cjs");
6
+ const utils = require("./utils.cjs");
7
+ const zodToJson = require("./zod-to-json.cjs");
8
+ const defaultSkipList = [
9
+ "/documentation/",
10
+ "/documentation/initOAuth",
11
+ "/documentation/json",
12
+ "/documentation/uiConfig",
13
+ "/documentation/yaml",
14
+ "/documentation/*",
15
+ "/documentation/static/*"
16
+ ];
17
+ const createJsonSchemaTransform = ({
18
+ skipList = defaultSkipList,
19
+ schemaRegistry = core.globalRegistry,
20
+ zodToJsonConfig = {}
21
+ }) => {
22
+ return (document) => {
23
+ utils.assertIsOpenAPIObject(document);
24
+ const { schema, url } = document;
25
+ if (!schema) {
26
+ return {
27
+ schema,
28
+ url
29
+ };
30
+ }
31
+ const target = utils.getJSONSchemaTarget(document.openapiObject.openapi);
32
+ const config = {
33
+ target,
34
+ ...zodToJsonConfig
35
+ };
36
+ const { inputRegistry, outputRegistry } = registry.generateIORegistries(schemaRegistry);
37
+ const { response, headers, querystring, body, params, hide, ...rest } = schema;
38
+ const transformed = {};
39
+ if (skipList.includes(url) || hide) {
40
+ transformed.hide = true;
41
+ return { schema: transformed, url };
42
+ }
43
+ const zodSchemas = { headers, querystring, body, params };
44
+ for (const prop in zodSchemas) {
45
+ const zodSchema = zodSchemas[prop];
46
+ if (zodSchema) {
47
+ transformed[prop] = zodToJson.zodSchemaToJson(zodSchema, inputRegistry, "input", config);
48
+ }
49
+ }
50
+ if (response) {
51
+ transformed.response = {};
52
+ for (const prop in response) {
53
+ const zodSchema = resolveSchema(response[prop]);
54
+ transformed.response[prop] = zodToJson.zodSchemaToJson(zodSchema, outputRegistry, "output", config);
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
+ const jsonSchemaTransform = createJsonSchemaTransform({});
67
+ const createJsonSchemaTransformObject = ({
68
+ schemaRegistry = core.globalRegistry,
69
+ zodToJsonConfig = {}
70
+ }) => (document) => {
71
+ utils.assertIsOpenAPIObject(document);
72
+ const target = utils.getJSONSchemaTarget(document.openapiObject.openapi);
73
+ const config = {
74
+ target,
75
+ ...zodToJsonConfig
76
+ };
77
+ const { inputRegistry, outputRegistry } = registry.generateIORegistries(schemaRegistry);
78
+ const inputSchemas = zodToJson.zodRegistryToJson(inputRegistry, "input", config);
79
+ const outputSchemas = zodToJson.zodRegistryToJson(outputRegistry, "output", config);
80
+ return {
81
+ ...document.openapiObject,
82
+ components: {
83
+ ...document.openapiObject.components,
84
+ schemas: {
85
+ ...document.openapiObject.components?.schemas,
86
+ ...inputSchemas,
87
+ ...outputSchemas
88
+ }
89
+ }
90
+ };
91
+ };
92
+ const jsonSchemaTransformObject = createJsonSchemaTransformObject({});
93
+ const validatorCompiler = ({ schema }) => (data) => {
94
+ const result = core.safeDecode(schema, data);
95
+ if (result.error) {
96
+ return { error: errors.createValidationError(result.error) };
97
+ }
98
+ return { value: result.data };
99
+ };
100
+ function resolveSchema(maybeSchema) {
101
+ if (maybeSchema instanceof core.$ZodType) {
102
+ return maybeSchema;
103
+ }
104
+ if ("properties" in maybeSchema && maybeSchema.properties instanceof core.$ZodType) {
105
+ return maybeSchema.properties;
106
+ }
107
+ throw new errors.InvalidSchemaError(JSON.stringify(maybeSchema));
108
+ }
109
+ const createSerializerCompiler = (options) => ({ schema: maybeSchema, method, url }) => (data) => {
110
+ const schema = resolveSchema(maybeSchema);
111
+ const result = core.safeEncode(schema, data);
112
+ if (result.error) {
113
+ throw new errors.ResponseSerializationError(method, url, { cause: result.error });
114
+ }
115
+ return JSON.stringify(result.data, options?.replacer);
116
+ };
117
+ const serializerCompiler = createSerializerCompiler({});
118
+ exports.createJsonSchemaTransform = createJsonSchemaTransform;
119
+ exports.createJsonSchemaTransformObject = createJsonSchemaTransformObject;
120
+ exports.createSerializerCompiler = createSerializerCompiler;
121
+ exports.jsonSchemaTransform = jsonSchemaTransform;
122
+ exports.jsonSchemaTransformObject = jsonSchemaTransformObject;
123
+ exports.serializerCompiler = serializerCompiler;
124
+ exports.validatorCompiler = validatorCompiler;
125
+ //# sourceMappingURL=core.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.cjs","sources":["../../src/core.ts"],"sourcesContent":["import type { SwaggerTransform, SwaggerTransformObject } from '@fastify/swagger'\nimport type {\n FastifyPluginAsync,\n FastifyPluginCallback,\n FastifyPluginOptions,\n FastifySchema,\n FastifySchemaCompiler,\n FastifyTypeProvider,\n RawServerBase,\n RawServerDefault,\n} from 'fastify'\nimport type { FastifySerializerCompiler } from 'fastify/types/schema'\nimport type { $ZodRegistry, output } from 'zod/v4/core'\nimport { $ZodType, globalRegistry, safeDecode, safeEncode } from 'zod/v4/core'\nimport { createValidationError, InvalidSchemaError, ResponseSerializationError } from './errors'\nimport { generateIORegistries, type SchemaRegistryMeta } from './registry'\nimport { assertIsOpenAPIObject, getJSONSchemaTarget } from './utils'\nimport { type ZodToJsonConfig, zodRegistryToJson, zodSchemaToJson } from './zod-to-json'\n\ntype FreeformRecord = Record<string, any>\n\nconst defaultSkipList = [\n '/documentation/',\n '/documentation/initOAuth',\n '/documentation/json',\n '/documentation/uiConfig',\n '/documentation/yaml',\n '/documentation/*',\n '/documentation/static/*',\n]\n\nexport interface ZodTypeProvider extends FastifyTypeProvider {\n validator: this['schema'] extends $ZodType ? output<this['schema']> : unknown\n serializer: this['schema'] extends $ZodType ? output<this['schema']> : unknown\n}\n\ninterface Schema extends FastifySchema {\n hide?: boolean\n}\n\ntype CreateJsonSchemaTransformOptions = {\n skipList?: readonly string[]\n schemaRegistry?: $ZodRegistry<SchemaRegistryMeta>\n zodToJsonConfig?: ZodToJsonConfig\n}\n\nexport const createJsonSchemaTransform = ({\n skipList = defaultSkipList,\n schemaRegistry = globalRegistry,\n zodToJsonConfig = {},\n}: CreateJsonSchemaTransformOptions): SwaggerTransform<Schema> => {\n return (document) => {\n assertIsOpenAPIObject(document)\n\n const { schema, url } = document\n\n if (!schema) {\n return {\n schema,\n url,\n }\n }\n\n const target = getJSONSchemaTarget(document.openapiObject.openapi)\n const config = {\n target,\n ...zodToJsonConfig,\n }\n\n const { inputRegistry, outputRegistry } = generateIORegistries(schemaRegistry)\n\n const { response, headers, querystring, body, params, hide, ...rest } = schema\n\n const transformed: FreeformRecord = {}\n\n if (skipList.includes(url) || hide) {\n transformed.hide = true\n return { schema: transformed, url }\n }\n\n const zodSchemas: FreeformRecord = { headers, querystring, body, params }\n\n for (const prop in zodSchemas) {\n const zodSchema = zodSchemas[prop]\n if (zodSchema) {\n transformed[prop] = zodSchemaToJson(zodSchema, inputRegistry, 'input', config)\n }\n }\n\n if (response) {\n transformed.response = {}\n\n for (const prop in response as any) {\n const zodSchema = resolveSchema((response as any)[prop])\n\n transformed.response[prop] = zodSchemaToJson(zodSchema, outputRegistry, 'output', config)\n }\n }\n\n for (const prop in rest) {\n const meta = rest[prop as keyof typeof rest]\n if (meta) {\n transformed[prop] = meta\n }\n }\n\n return { schema: transformed, url }\n }\n}\n\nexport const jsonSchemaTransform: SwaggerTransform<Schema> = createJsonSchemaTransform({})\n\ntype CreateJsonSchemaTransformObjectOptions = {\n schemaRegistry?: $ZodRegistry<SchemaRegistryMeta>\n zodToJsonConfig?: ZodToJsonConfig\n}\n\nexport const createJsonSchemaTransformObject =\n ({\n schemaRegistry = globalRegistry,\n zodToJsonConfig = {},\n }: CreateJsonSchemaTransformObjectOptions): SwaggerTransformObject =>\n (document) => {\n assertIsOpenAPIObject(document)\n\n const target = getJSONSchemaTarget(document.openapiObject.openapi)\n const config = {\n target,\n ...zodToJsonConfig,\n }\n\n const { inputRegistry, outputRegistry } = generateIORegistries(schemaRegistry)\n const inputSchemas = zodRegistryToJson(inputRegistry, 'input', config)\n const outputSchemas = zodRegistryToJson(outputRegistry, 'output', config)\n\n return {\n ...document.openapiObject,\n components: {\n ...document.openapiObject.components,\n schemas: {\n ...document.openapiObject.components?.schemas,\n ...inputSchemas,\n ...outputSchemas,\n },\n },\n } as ReturnType<SwaggerTransformObject>\n }\n\nexport const jsonSchemaTransformObject: SwaggerTransformObject = createJsonSchemaTransformObject({})\n\nexport const validatorCompiler: FastifySchemaCompiler<$ZodType> =\n ({ schema }) =>\n (data) => {\n const result = safeDecode(schema, data)\n if (result.error) {\n return { error: createValidationError(result.error) as unknown as Error }\n }\n\n return { value: result.data }\n }\n\nfunction resolveSchema(maybeSchema: $ZodType | { properties: $ZodType }): $ZodType {\n if (maybeSchema instanceof $ZodType) {\n return maybeSchema as $ZodType\n }\n if ('properties' in maybeSchema && maybeSchema.properties instanceof $ZodType) {\n return maybeSchema.properties as $ZodType\n }\n throw new InvalidSchemaError(JSON.stringify(maybeSchema))\n}\n\ntype ReplacerFunction = (this: any, key: string, value: any) => any\n\nexport type ZodSerializerCompilerOptions = {\n replacer?: ReplacerFunction\n}\n\nexport const createSerializerCompiler =\n (\n options?: ZodSerializerCompilerOptions,\n ): FastifySerializerCompiler<$ZodType | { properties: $ZodType }> =>\n ({ schema: maybeSchema, method, url }) =>\n (data) => {\n const schema = resolveSchema(maybeSchema)\n\n const result = safeEncode(schema, data)\n if (result.error) {\n throw new ResponseSerializationError(method, url, { cause: result.error })\n }\n\n return JSON.stringify(result.data, options?.replacer)\n }\n\nexport const serializerCompiler: ReturnType<typeof createSerializerCompiler> =\n createSerializerCompiler({})\n\n/**\n * FastifyPluginCallbackZod with Zod automatic type inference\n *\n * @example\n * ```typescript\n * import { FastifyPluginCallbackZod } from \"fastify-type-provider-zod\"\n *\n * const plugin: FastifyPluginCallbackZod = (fastify, options, done) => {\n * done()\n * }\n * ```\n */\nexport type FastifyPluginCallbackZod<\n Options extends FastifyPluginOptions = Record<never, never>,\n Server extends RawServerBase = RawServerDefault,\n> = FastifyPluginCallback<Options, Server, ZodTypeProvider>\n\n/**\n * FastifyPluginAsyncZod with Zod automatic type inference\n *\n * @example\n * ```typescript\n * import { FastifyPluginAsyncZod } from \"fastify-type-provider-zod\"\n *\n * const plugin: FastifyPluginAsyncZod = async (fastify, options) => {\n * }\n * ```\n */\nexport type FastifyPluginAsyncZod<\n Options extends FastifyPluginOptions = Record<never, never>,\n Server extends RawServerBase = RawServerDefault,\n> = FastifyPluginAsync<Options, Server, ZodTypeProvider>\n"],"names":["globalRegistry","assertIsOpenAPIObject","getJSONSchemaTarget","generateIORegistries","zodSchemaToJson","zodRegistryToJson","safeDecode","createValidationError","$ZodType","InvalidSchemaError","safeEncode","ResponseSerializationError"],"mappings":"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"}
@@ -0,0 +1,68 @@
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 type { $ZodRegistry, output } from "zod/v4/core";
5
+ import { $ZodType } from "zod/v4/core";
6
+ import { type SchemaRegistryMeta } from "../cjs/registry.cjs";
7
+ import { type ZodToJsonConfig } from "../cjs/zod-to-json.cjs";
8
+ export interface ZodTypeProvider extends FastifyTypeProvider {
9
+ validator: this["schema"] extends $ZodType ? output<this["schema"]> : unknown;
10
+ serializer: this["schema"] extends $ZodType ? output<this["schema"]> : unknown;
11
+ }
12
+ interface Schema extends FastifySchema {
13
+ hide?: boolean;
14
+ }
15
+ type CreateJsonSchemaTransformOptions = {
16
+ skipList?: readonly string[];
17
+ schemaRegistry?: $ZodRegistry<SchemaRegistryMeta>;
18
+ zodToJsonConfig?: ZodToJsonConfig;
19
+ };
20
+ export declare const createJsonSchemaTransform: ({ skipList, schemaRegistry, zodToJsonConfig }: CreateJsonSchemaTransformOptions) => SwaggerTransform<Schema>;
21
+ export declare const jsonSchemaTransform: SwaggerTransform<Schema>;
22
+ type CreateJsonSchemaTransformObjectOptions = {
23
+ schemaRegistry?: $ZodRegistry<SchemaRegistryMeta>;
24
+ zodToJsonConfig?: ZodToJsonConfig;
25
+ };
26
+ export declare const createJsonSchemaTransformObject: ({ schemaRegistry, zodToJsonConfig }: CreateJsonSchemaTransformObjectOptions) => SwaggerTransformObject;
27
+ export declare const jsonSchemaTransformObject: SwaggerTransformObject;
28
+ export declare const validatorCompiler: FastifySchemaCompiler<$ZodType>;
29
+ type ReplacerFunction = (this: any, key: string, value: any) => any;
30
+ export type ZodSerializerCompilerOptions = {
31
+ replacer?: ReplacerFunction;
32
+ };
33
+ export declare const createSerializerCompiler: (options?: ZodSerializerCompilerOptions) => FastifySerializerCompiler<$ZodType | {
34
+ properties: $ZodType;
35
+ }>;
36
+ export declare const serializerCompiler: ReturnType<typeof createSerializerCompiler>;
37
+ /**
38
+ * FastifyPluginCallbackZod with Zod automatic type inference
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * import { FastifyPluginCallbackZod } from "fastify-type-provider-zod"
43
+ *
44
+ * const plugin: FastifyPluginCallbackZod = (fastify, options, done) => {
45
+ * done()
46
+ * }
47
+ * ```
48
+ */
49
+ export type FastifyPluginCallbackZod<
50
+ Options extends FastifyPluginOptions = Record<never, never>,
51
+ Server extends RawServerBase = RawServerDefault
52
+ > = FastifyPluginCallback<Options, Server, ZodTypeProvider>;
53
+ /**
54
+ * FastifyPluginAsyncZod with Zod automatic type inference
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * import { FastifyPluginAsyncZod } from "fastify-type-provider-zod"
59
+ *
60
+ * const plugin: FastifyPluginAsyncZod = async (fastify, options) => {
61
+ * }
62
+ * ```
63
+ */
64
+ export type FastifyPluginAsyncZod<
65
+ Options extends FastifyPluginOptions = Record<never, never>,
66
+ Server extends RawServerBase = RawServerDefault
67
+ > = FastifyPluginAsync<Options, Server, ZodTypeProvider>;
68
+ export {};
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const createError = require("@fastify/error");
4
+ const InvalidSchemaError = createError("FST_ERR_INVALID_SCHEMA", "Invalid schema passed: %s", 500);
5
+ const ZodFastifySchemaValidationErrorSymbol = /* @__PURE__ */ Symbol.for("ZodFastifySchemaValidationError");
6
+ const ResponseSerializationBase = createError(
7
+ "FST_ERR_RESPONSE_SERIALIZATION",
8
+ "Response doesn't match the schema",
9
+ 500
10
+ );
11
+ class ResponseSerializationError extends ResponseSerializationBase {
12
+ constructor(method, url, options) {
13
+ super({ cause: options.cause });
14
+ this.method = method;
15
+ this.url = url;
16
+ this.cause = options.cause;
17
+ }
18
+ cause;
19
+ }
20
+ function isResponseSerializationError(value) {
21
+ return "method" in value;
22
+ }
23
+ function isZodFastifySchemaValidationError(error) {
24
+ return typeof error === "object" && error !== null && error[ZodFastifySchemaValidationErrorSymbol] === true;
25
+ }
26
+ function hasZodFastifySchemaValidationErrors(error) {
27
+ return typeof error === "object" && error !== null && "validation" in error && Array.isArray(error.validation) && error.validation.length > 0 && isZodFastifySchemaValidationError(error.validation[0]);
28
+ }
29
+ function omit(obj, keys) {
30
+ const result = {};
31
+ for (const key of Object.keys(obj)) {
32
+ if (!keys.includes(key)) {
33
+ result[key] = obj[key];
34
+ }
35
+ }
36
+ return result;
37
+ }
38
+ function createValidationError(error) {
39
+ return error.issues.map((issue) => {
40
+ return {
41
+ [ZodFastifySchemaValidationErrorSymbol]: true,
42
+ keyword: issue.code,
43
+ instancePath: `/${issue.path.join("/")}`,
44
+ schemaPath: `#/${issue.path.join("/")}/${issue.code}`,
45
+ message: issue.message,
46
+ params: {
47
+ ...omit(issue, ["path", "code", "message"])
48
+ }
49
+ };
50
+ });
51
+ }
52
+ exports.InvalidSchemaError = InvalidSchemaError;
53
+ exports.ResponseSerializationError = ResponseSerializationError;
54
+ exports.createValidationError = createValidationError;
55
+ exports.hasZodFastifySchemaValidationErrors = hasZodFastifySchemaValidationErrors;
56
+ exports.isResponseSerializationError = isResponseSerializationError;
57
+ //# sourceMappingURL=errors.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.cjs","sources":["../../src/errors.ts"],"sourcesContent":["import createError, { type FastifyErrorConstructor } from '@fastify/error'\nimport type { FastifyError } from 'fastify'\nimport type { FastifySchemaValidationError } from 'fastify/types/schema'\nimport type { $ZodError } from 'zod/v4/core'\n\nexport const InvalidSchemaError: FastifyErrorConstructor<\n {\n code: string\n },\n [string]\n> = createError<[string]>('FST_ERR_INVALID_SCHEMA', 'Invalid schema passed: %s', 500)\n\nconst ZodFastifySchemaValidationErrorSymbol: symbol = Symbol.for('ZodFastifySchemaValidationError')\n\nexport type ZodFastifySchemaValidationError = FastifySchemaValidationError & {\n [ZodFastifySchemaValidationErrorSymbol]: true\n}\n\nconst ResponseSerializationBase: FastifyErrorConstructor<\n {\n code: string\n },\n [\n {\n cause: $ZodError\n },\n ]\n> = createError<[{ cause: $ZodError }]>(\n 'FST_ERR_RESPONSE_SERIALIZATION',\n \"Response doesn't match the schema\",\n 500,\n)\n\nexport class ResponseSerializationError extends ResponseSerializationBase {\n cause!: $ZodError\n\n constructor(\n public method: string,\n public url: string,\n options: { cause: $ZodError },\n ) {\n super({ cause: options.cause })\n\n this.cause = options.cause\n }\n}\n\nexport function isResponseSerializationError(value: unknown): value is ResponseSerializationError {\n return 'method' in (value as ResponseSerializationError)\n}\n\nfunction isZodFastifySchemaValidationError(\n error: unknown,\n): error is ZodFastifySchemaValidationError {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as ZodFastifySchemaValidationError)[ZodFastifySchemaValidationErrorSymbol] === true\n )\n}\n\nexport function hasZodFastifySchemaValidationErrors(\n error: unknown,\n): error is Omit<FastifyError, 'validation'> & { validation: ZodFastifySchemaValidationError[] } {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'validation' in error &&\n Array.isArray(error.validation) &&\n error.validation.length > 0 &&\n isZodFastifySchemaValidationError(error.validation[0])\n )\n}\n\nfunction omit<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Omit<T, K> {\n const result = {} as Omit<T, K>\n for (const key of Object.keys(obj) as Array<keyof T>) {\n if (!keys.includes(key as K)) {\n // @ts-expect-error\n result[key] = obj[key]\n }\n }\n return result\n}\n\nexport function createValidationError(error: $ZodError): ZodFastifySchemaValidationError[] {\n return error.issues.map((issue) => {\n return {\n [ZodFastifySchemaValidationErrorSymbol]: true,\n keyword: issue.code,\n instancePath: `/${issue.path.join('/')}`,\n schemaPath: `#/${issue.path.join('/')}/${issue.code}`,\n message: issue.message,\n params: {\n ...omit(issue, ['path', 'code', 'message']),\n },\n }\n })\n}\n"],"names":[],"mappings":";;;AAKO,MAAM,qBAKT,YAAsB,0BAA0B,6BAA6B,GAAG;AAEpF,MAAM,wCAAgD,uBAAO,IAAI,iCAAiC;AAMlG,MAAM,4BASF;AAAA,EACF;AAAA,EACA;AAAA,EACA;AACF;AAEO,MAAM,mCAAmC,0BAA0B;AAAA,EAGxE,YACS,QACA,KACP,SACA;AACA,UAAM,EAAE,OAAO,QAAQ,MAAA,CAAO;AAJvB,SAAA,SAAA;AACA,SAAA,MAAA;AAKP,SAAK,QAAQ,QAAQ;AAAA,EACvB;AAAA,EAVA;AAWF;AAEO,SAAS,6BAA6B,OAAqD;AAChG,SAAO,YAAa;AACtB;AAEA,SAAS,kCACP,OAC0C;AAC1C,SACE,OAAO,UAAU,YACjB,UAAU,QACT,MAA0C,qCAAqC,MAAM;AAE1F;AAEO,SAAS,oCACd,OAC+F;AAC/F,SACE,OAAO,UAAU,YACjB,UAAU,QACV,gBAAgB,SAChB,MAAM,QAAQ,MAAM,UAAU,KAC9B,MAAM,WAAW,SAAS,KAC1B,kCAAkC,MAAM,WAAW,CAAC,CAAC;AAEzD;AAEA,SAAS,KAA0C,KAAQ,MAAgC;AACzF,QAAM,SAAS,CAAA;AACf,aAAW,OAAO,OAAO,KAAK,GAAG,GAAqB;AACpD,QAAI,CAAC,KAAK,SAAS,GAAQ,GAAG;AAE5B,aAAO,GAAG,IAAI,IAAI,GAAG;AAAA,IACvB;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,sBAAsB,OAAqD;AACzF,SAAO,MAAM,OAAO,IAAI,CAAC,UAAU;AACjC,WAAO;AAAA,MACL,CAAC,qCAAqC,GAAG;AAAA,MACzC,SAAS,MAAM;AAAA,MACf,cAAc,IAAI,MAAM,KAAK,KAAK,GAAG,CAAC;AAAA,MACtC,YAAY,KAAK,MAAM,KAAK,KAAK,GAAG,CAAC,IAAI,MAAM,IAAI;AAAA,MACnD,SAAS,MAAM;AAAA,MACf,QAAQ;AAAA,QACN,GAAG,KAAK,OAAO,CAAC,QAAQ,QAAQ,SAAS,CAAC;AAAA,MAAA;AAAA,IAC5C;AAAA,EAEJ,CAAC;AACH;;;;;;"}
@@ -0,0 +1,30 @@
1
+ import { type FastifyErrorConstructor } from "@fastify/error";
2
+ import type { FastifyError } from "fastify";
3
+ import type { FastifySchemaValidationError } from "fastify/types/schema";
4
+ import type { $ZodError } from "zod/v4/core";
5
+ export declare const InvalidSchemaError: FastifyErrorConstructor<{
6
+ code: string;
7
+ }, [string]>;
8
+ declare const ZodFastifySchemaValidationErrorSymbol: symbol;
9
+ export type ZodFastifySchemaValidationError = FastifySchemaValidationError & {
10
+ [ZodFastifySchemaValidationErrorSymbol]: true;
11
+ };
12
+ declare const ResponseSerializationBase: FastifyErrorConstructor<{
13
+ code: string;
14
+ }, [{
15
+ cause: $ZodError;
16
+ }]>;
17
+ export declare class ResponseSerializationError extends ResponseSerializationBase {
18
+ method: string;
19
+ url: string;
20
+ cause: $ZodError;
21
+ constructor(method: string, url: string, options: {
22
+ cause: $ZodError;
23
+ });
24
+ }
25
+ export declare function isResponseSerializationError(value: unknown): value is ResponseSerializationError;
26
+ export declare function hasZodFastifySchemaValidationErrors(error: unknown): error is Omit<FastifyError, "validation"> & {
27
+ validation: ZodFastifySchemaValidationError[];
28
+ };
29
+ export declare function createValidationError(error: $ZodError): ZodFastifySchemaValidationError[];
30
+ export {};
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const core = require("./core.cjs");
4
+ const errors = require("./errors.cjs");
5
+ exports.createJsonSchemaTransform = core.createJsonSchemaTransform;
6
+ exports.createJsonSchemaTransformObject = core.createJsonSchemaTransformObject;
7
+ exports.createSerializerCompiler = core.createSerializerCompiler;
8
+ exports.jsonSchemaTransform = core.jsonSchemaTransform;
9
+ exports.jsonSchemaTransformObject = core.jsonSchemaTransformObject;
10
+ exports.serializerCompiler = core.serializerCompiler;
11
+ exports.validatorCompiler = core.validatorCompiler;
12
+ exports.InvalidSchemaError = errors.InvalidSchemaError;
13
+ exports.ResponseSerializationError = errors.ResponseSerializationError;
14
+ exports.hasZodFastifySchemaValidationErrors = errors.hasZodFastifySchemaValidationErrors;
15
+ exports.isResponseSerializationError = errors.isResponseSerializationError;
16
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;"}
@@ -0,0 +1,2 @@
1
+ export { createJsonSchemaTransform, createJsonSchemaTransformObject, createSerializerCompiler, type FastifyPluginAsyncZod, type FastifyPluginCallbackZod, jsonSchemaTransform, jsonSchemaTransformObject, serializerCompiler, validatorCompiler, type ZodSerializerCompilerOptions, type ZodTypeProvider } from "../cjs/core.cjs";
2
+ export { hasZodFastifySchemaValidationErrors, InvalidSchemaError, isResponseSerializationError, ResponseSerializationError, type ZodFastifySchemaValidationError } from "../cjs/errors.cjs";
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const core = require("zod/v4/core");
4
+ const getSchemaId = (id, io) => {
5
+ return io === "input" ? `${id}Input` : id;
6
+ };
7
+ class WeakMapWithFallback extends WeakMap {
8
+ constructor(fallback) {
9
+ super();
10
+ this.fallback = fallback;
11
+ }
12
+ get(key) {
13
+ return super.get(key) ?? this.fallback.get(key);
14
+ }
15
+ has(key) {
16
+ return super.has(key) || this.fallback.has(key);
17
+ }
18
+ }
19
+ const copyRegistry = (inputRegistry, idReplaceFn) => {
20
+ const outputRegistry = new core.$ZodRegistry();
21
+ outputRegistry._map = new WeakMapWithFallback(inputRegistry._map);
22
+ inputRegistry._idmap.forEach((schema, id) => {
23
+ outputRegistry.add(schema, {
24
+ ...inputRegistry._map.get(schema),
25
+ id: idReplaceFn(id)
26
+ });
27
+ });
28
+ return outputRegistry;
29
+ };
30
+ const generateIORegistries = (baseRegistry) => {
31
+ const inputRegistry = copyRegistry(baseRegistry, (id) => getSchemaId(id, "input"));
32
+ const outputRegistry = copyRegistry(baseRegistry, (id) => getSchemaId(id, "output"));
33
+ inputRegistry._idmap.forEach((_, id) => {
34
+ if (outputRegistry._idmap.has(id)) {
35
+ throw new Error(
36
+ `Collision detected for schema "${id}". There is already an input schema with the same name.`
37
+ );
38
+ }
39
+ });
40
+ return { inputRegistry, outputRegistry };
41
+ };
42
+ exports.generateIORegistries = generateIORegistries;
43
+ //# sourceMappingURL=registry.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.cjs","sources":["../../src/registry.ts"],"sourcesContent":["import { $ZodRegistry, type $ZodType } from 'zod/v4/core'\n\nexport type SchemaRegistryMeta = {\n id?: string | undefined\n [key: string]: unknown\n}\n\nconst getSchemaId = (id: string, io: 'input' | 'output'): string => {\n return io === 'input' ? `${id}Input` : id\n}\n\n// A WeakMap that falls back to another WeakMap when a key is not found, this is to ensure nested metadata is properly resolved\nclass WeakMapWithFallback extends WeakMap<$ZodType, SchemaRegistryMeta> {\n constructor(private fallback: WeakMap<$ZodType, SchemaRegistryMeta>) {\n super()\n }\n\n get(key: $ZodType): SchemaRegistryMeta | undefined {\n return super.get(key) ?? this.fallback.get(key)\n }\n\n has(key: $ZodType): boolean {\n return super.has(key) || this.fallback.has(key)\n }\n}\n\nconst copyRegistry = (\n inputRegistry: $ZodRegistry<SchemaRegistryMeta>,\n idReplaceFn: (id: string) => string,\n): $ZodRegistry<SchemaRegistryMeta> => {\n const outputRegistry = new $ZodRegistry<SchemaRegistryMeta>()\n\n outputRegistry._map = new WeakMapWithFallback(inputRegistry._map)\n\n inputRegistry._idmap.forEach((schema, id) => {\n outputRegistry.add(schema, {\n ...inputRegistry._map.get(schema),\n id: idReplaceFn(id),\n })\n })\n\n return outputRegistry\n}\n\nexport const generateIORegistries = (\n baseRegistry: $ZodRegistry<SchemaRegistryMeta>,\n): {\n inputRegistry: $ZodRegistry<SchemaRegistryMeta>\n outputRegistry: $ZodRegistry<SchemaRegistryMeta>\n} => {\n const inputRegistry = copyRegistry(baseRegistry, (id) => getSchemaId(id, 'input'))\n const outputRegistry = copyRegistry(baseRegistry, (id) => getSchemaId(id, 'output'))\n\n // Detect colliding schemas\n inputRegistry._idmap.forEach((_, id) => {\n if (outputRegistry._idmap.has(id)) {\n throw new Error(\n `Collision detected for schema \"${id}\". There is already an input schema with the same name.`,\n )\n }\n })\n\n return { inputRegistry, outputRegistry }\n}\n"],"names":["$ZodRegistry"],"mappings":";;;AAOA,MAAM,cAAc,CAAC,IAAY,OAAmC;AAClE,SAAO,OAAO,UAAU,GAAG,EAAE,UAAU;AACzC;AAGA,MAAM,4BAA4B,QAAsC;AAAA,EACtE,YAAoB,UAAiD;AACnE,UAAA;AADkB,SAAA,WAAA;AAAA,EAEpB;AAAA,EAEA,IAAI,KAA+C;AACjD,WAAO,MAAM,IAAI,GAAG,KAAK,KAAK,SAAS,IAAI,GAAG;AAAA,EAChD;AAAA,EAEA,IAAI,KAAwB;AAC1B,WAAO,MAAM,IAAI,GAAG,KAAK,KAAK,SAAS,IAAI,GAAG;AAAA,EAChD;AACF;AAEA,MAAM,eAAe,CACnB,eACA,gBACqC;AACrC,QAAM,iBAAiB,IAAIA,kBAAA;AAE3B,iBAAe,OAAO,IAAI,oBAAoB,cAAc,IAAI;AAEhE,gBAAc,OAAO,QAAQ,CAAC,QAAQ,OAAO;AAC3C,mBAAe,IAAI,QAAQ;AAAA,MACzB,GAAG,cAAc,KAAK,IAAI,MAAM;AAAA,MAChC,IAAI,YAAY,EAAE;AAAA,IAAA,CACnB;AAAA,EACH,CAAC;AAED,SAAO;AACT;AAEO,MAAM,uBAAuB,CAClC,iBAIG;AACH,QAAM,gBAAgB,aAAa,cAAc,CAAC,OAAO,YAAY,IAAI,OAAO,CAAC;AACjF,QAAM,iBAAiB,aAAa,cAAc,CAAC,OAAO,YAAY,IAAI,QAAQ,CAAC;AAGnF,gBAAc,OAAO,QAAQ,CAAC,GAAG,OAAO;AACtC,QAAI,eAAe,OAAO,IAAI,EAAE,GAAG;AACjC,YAAM,IAAI;AAAA,QACR,kCAAkC,EAAE;AAAA,MAAA;AAAA,IAExC;AAAA,EACF,CAAC;AAED,SAAO,EAAE,eAAe,eAAA;AAC1B;;"}
@@ -0,0 +1,9 @@
1
+ import { $ZodRegistry } from "zod/v4/core";
2
+ export type SchemaRegistryMeta = {
3
+ id?: string | undefined;
4
+ [key: string]: unknown;
5
+ };
6
+ export declare const generateIORegistries: (baseRegistry: $ZodRegistry<SchemaRegistryMeta>) => {
7
+ inputRegistry: $ZodRegistry<SchemaRegistryMeta>;
8
+ outputRegistry: $ZodRegistry<SchemaRegistryMeta>;
9
+ };
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const assertIsOpenAPIObject = (obj) => {
4
+ if ("swaggerObject" in obj) {
5
+ throw new Error("This package currently does not support component references for Swagger 2.0");
6
+ }
7
+ };
8
+ const getReferenceUri = (input) => {
9
+ const id = input.replace(/^#\/(?:\$defs|definitions|components\/schemas)\//, "");
10
+ return `#/components/schemas/${id}`;
11
+ };
12
+ const getJSONSchemaTarget = (version = "3.0.0") => {
13
+ if (version.startsWith("3.0")) {
14
+ return "openapi-3.0";
15
+ }
16
+ return "draft-2020-12";
17
+ };
18
+ exports.assertIsOpenAPIObject = assertIsOpenAPIObject;
19
+ exports.getJSONSchemaTarget = getJSONSchemaTarget;
20
+ exports.getReferenceUri = getReferenceUri;
21
+ //# sourceMappingURL=utils.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\n\ntype SwaggerObject = {\n swaggerObject: Partial<OpenAPIV2.Document>\n}\n\ntype OpenAPIObject = {\n openapiObject: Partial<OpenAPIV3.Document | OpenAPIV3_1.Document>\n}\n\nexport const assertIsOpenAPIObject: (\n obj: SwaggerObject | OpenAPIObject,\n) => asserts obj is OpenAPIObject = (obj) => {\n if ('swaggerObject' in obj) {\n throw new Error('This package currently does not support component references for Swagger 2.0')\n }\n}\n\nexport type JSONSchemaTarget = 'draft-2020-12' | 'openapi-3.0'\n\nexport const getReferenceUri = (input: string): string => {\n const id = input.replace(/^#\\/(?:\\$defs|definitions|components\\/schemas)\\//, '')\n\n return `#/components/schemas/${id}`\n}\n\nexport const getJSONSchemaTarget = (version = '3.0.0'): JSONSchemaTarget => {\n if (version.startsWith('3.0')) {\n return 'openapi-3.0'\n }\n\n return 'draft-2020-12'\n}\n"],"names":[],"mappings":";;AAUO,MAAM,wBAEuB,CAAC,QAAQ;AAC3C,MAAI,mBAAmB,KAAK;AAC1B,UAAM,IAAI,MAAM,8EAA8E;AAAA,EAChG;AACF;AAIO,MAAM,kBAAkB,CAAC,UAA0B;AACxD,QAAM,KAAK,MAAM,QAAQ,oDAAoD,EAAE;AAE/E,SAAO,wBAAwB,EAAE;AACnC;AAEO,MAAM,sBAAsB,CAAC,UAAU,YAA8B;AAC1E,MAAI,QAAQ,WAAW,KAAK,GAAG;AAC7B,WAAO;AAAA,EACT;AAEA,SAAO;AACT;;;;"}
@@ -0,0 +1,12 @@
1
+ import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from "openapi-types";
2
+ type SwaggerObject = {
3
+ swaggerObject: Partial<OpenAPIV2.Document>;
4
+ };
5
+ type OpenAPIObject = {
6
+ openapiObject: Partial<OpenAPIV3.Document | OpenAPIV3_1.Document>;
7
+ };
8
+ export declare const assertIsOpenAPIObject: (obj: SwaggerObject | OpenAPIObject) => asserts obj is OpenAPIObject;
9
+ export type JSONSchemaTarget = "draft-2020-12" | "openapi-3.0";
10
+ export declare const getReferenceUri: (input: string) => string;
11
+ export declare const getJSONSchemaTarget: (version?: string) => JSONSchemaTarget;
12
+ export {};