@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
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const core = require("zod/v4/core");
4
+ const utils = require("./utils.cjs");
5
+ const SCHEMA_REGISTRY_ID_PLACEHOLDER = "__SCHEMA__ID__PLACEHOLDER__";
6
+ const SCHEMA_URI_PLACEHOLDER = "__SCHEMA__PLACEHOLDER__";
7
+ function isZodDate(entity) {
8
+ return entity instanceof core.$ZodType && entity._zod.def.type === "date";
9
+ }
10
+ function isZodUnion(entity) {
11
+ return entity instanceof core.$ZodType && entity._zod.def.type === "union";
12
+ }
13
+ function isZodUndefined(entity) {
14
+ return entity instanceof core.$ZodType && entity._zod.def.type === "undefined";
15
+ }
16
+ const getOverride = (ctx, io) => {
17
+ if (isZodUnion(ctx.zodSchema)) {
18
+ ctx.jsonSchema.anyOf = ctx.jsonSchema.anyOf?.filter((schema) => Object.keys(schema).length > 0);
19
+ }
20
+ if (isZodDate(ctx.zodSchema)) {
21
+ if (io === "output") {
22
+ ctx.jsonSchema.type = "string";
23
+ ctx.jsonSchema.format = "date-time";
24
+ }
25
+ }
26
+ if (isZodUndefined(ctx.zodSchema)) {
27
+ if (io === "output") {
28
+ ctx.jsonSchema.type = "null";
29
+ }
30
+ }
31
+ };
32
+ const deleteInvalidProperties = (schema) => {
33
+ const object = { ...schema };
34
+ delete object.id;
35
+ delete object.$schema;
36
+ delete object.$id;
37
+ return object;
38
+ };
39
+ const zodSchemaToJson = (zodSchema, registry, io, config) => {
40
+ const schemaRegistryEntry = registry.get(zodSchema);
41
+ if (schemaRegistryEntry?.id) {
42
+ return { $ref: utils.getReferenceUri(schemaRegistryEntry.id) };
43
+ }
44
+ const tempRegistry = new core.$ZodRegistry();
45
+ tempRegistry.add(zodSchema, { id: SCHEMA_REGISTRY_ID_PLACEHOLDER });
46
+ const {
47
+ schemas: { [SCHEMA_REGISTRY_ID_PLACEHOLDER]: result }
48
+ } = core.toJSONSchema(tempRegistry, {
49
+ ...config,
50
+ io,
51
+ target: config.target,
52
+ metadata: registry,
53
+ unrepresentable: config.unrepresentable ?? "any",
54
+ cycles: "ref",
55
+ reused: "inline",
56
+ /**
57
+ * The uri option only allows customizing the base path of the `$ref`, and it automatically appends a path to it.
58
+ * As a workaround, we set a placeholder that looks something like this.
59
+ * @see jsonSchemaReplaceRef
60
+ * @see https://github.com/colinhacks/zod/issues/4750
61
+ */
62
+ uri: () => SCHEMA_URI_PLACEHOLDER,
63
+ override: config.override ?? ((ctx) => getOverride(ctx, io))
64
+ });
65
+ const jsonSchema = deleteInvalidProperties(result);
66
+ return JSON.parse(JSON.stringify(jsonSchema), (__key, value) => {
67
+ if (typeof value === "string" && value.startsWith(SCHEMA_URI_PLACEHOLDER)) {
68
+ return utils.getReferenceUri(value.slice(SCHEMA_URI_PLACEHOLDER.length));
69
+ }
70
+ return value;
71
+ });
72
+ };
73
+ const zodRegistryToJson = (registry, io, config) => {
74
+ const result = core.toJSONSchema(registry, {
75
+ ...config,
76
+ io,
77
+ target: config.target,
78
+ metadata: registry,
79
+ unrepresentable: config.unrepresentable ?? "any",
80
+ cycles: "ref",
81
+ reused: "inline",
82
+ uri: (id) => utils.getReferenceUri(id),
83
+ override: config.override ?? ((ctx) => getOverride(ctx, io))
84
+ }).schemas;
85
+ const jsonSchemas = {};
86
+ for (const id in result) {
87
+ jsonSchemas[id] = deleteInvalidProperties(result[id]);
88
+ }
89
+ return jsonSchemas;
90
+ };
91
+ exports.zodRegistryToJson = zodRegistryToJson;
92
+ exports.zodSchemaToJson = zodSchemaToJson;
93
+ //# sourceMappingURL=zod-to-json.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zod-to-json.cjs","sources":["../../src/zod-to-json.ts"],"sourcesContent":["import type {\n $ZodDate,\n $ZodUndefined,\n $ZodUnion,\n JSONSchema,\n RegistryToJSONSchemaParams,\n} from 'zod/v4/core'\nimport { $ZodRegistry, $ZodType, toJSONSchema } from 'zod/v4/core'\nimport type { SchemaRegistryMeta } from './registry'\nimport { getReferenceUri } from './utils'\n\nconst SCHEMA_REGISTRY_ID_PLACEHOLDER = '__SCHEMA__ID__PLACEHOLDER__'\nconst SCHEMA_URI_PLACEHOLDER = '__SCHEMA__PLACEHOLDER__'\n\nfunction isZodDate(entity: unknown): entity is $ZodDate {\n return entity instanceof $ZodType && entity._zod.def.type === 'date'\n}\n\nfunction isZodUnion(entity: unknown): entity is $ZodUnion {\n return entity instanceof $ZodType && entity._zod.def.type === 'union'\n}\n\nfunction isZodUndefined(entity: unknown): entity is $ZodUndefined {\n return entity instanceof $ZodType && entity._zod.def.type === 'undefined'\n}\n\nconst getOverride = (\n ctx: {\n zodSchema: $ZodType\n jsonSchema: JSONSchema.BaseSchema\n },\n io: 'input' | 'output',\n) => {\n if (isZodUnion(ctx.zodSchema)) {\n // Filter unrepresentable types in unions\n // TODO: Should be fixed upstream and not merged in this plugin.\n // Remove when passed: https://github.com/colinhacks/zod/pull/5013\n ctx.jsonSchema.anyOf = ctx.jsonSchema.anyOf?.filter((schema) => Object.keys(schema).length > 0)\n }\n\n if (isZodDate(ctx.zodSchema)) {\n // Allow dates to be represented as strings in output schemas\n if (io === 'output') {\n ctx.jsonSchema.type = 'string'\n ctx.jsonSchema.format = 'date-time'\n }\n }\n\n if (isZodUndefined(ctx.zodSchema)) {\n // Allow undefined to be represented as null in output schemas\n if (io === 'output') {\n ctx.jsonSchema.type = 'null'\n }\n }\n}\n\nexport type ZodToJsonConfig = {} & Omit<\n RegistryToJSONSchemaParams,\n 'io' | 'metadata' | 'cycles' | 'reused' | 'uri'\n>\n\nconst deleteInvalidProperties: (\n schema: JSONSchema.BaseSchema,\n) => Omit<JSONSchema.BaseSchema, 'id' | '$schema'> = (schema) => {\n const object = { ...schema }\n\n delete object.id\n delete object.$schema\n\n // ToDo added in newer zod\n delete object.$id\n\n return object\n}\n\nexport const zodSchemaToJson: (\n zodSchema: $ZodType,\n registry: $ZodRegistry<SchemaRegistryMeta>,\n io: 'input' | 'output',\n config: ZodToJsonConfig,\n) => ReturnType<typeof deleteInvalidProperties> = (zodSchema, registry, io, config) => {\n /**\n * Checks whether the provided schema is registered in the given registry.\n * If it is present and has an `id`, it can be referenced as component.\n *\n * @see https://github.com/turkerdev/fastify-type-provider-zod/issues/173\n */\n const schemaRegistryEntry = registry.get(zodSchema)\n if (schemaRegistryEntry?.id) {\n return { $ref: getReferenceUri(schemaRegistryEntry.id) }\n }\n\n /**\n * Unfortunately, at the time of writing, there is no way to generate a schema with `$ref`\n * using `toJSONSchema` and a zod schema.\n *\n * As a workaround, we create a zod registry containing only the specific schema we want to convert.\n *\n * @see https://github.com/colinhacks/zod/issues/4281\n */\n const tempRegistry = new $ZodRegistry<SchemaRegistryMeta>()\n tempRegistry.add(zodSchema, { id: SCHEMA_REGISTRY_ID_PLACEHOLDER })\n\n const {\n schemas: { [SCHEMA_REGISTRY_ID_PLACEHOLDER]: result },\n } = toJSONSchema(tempRegistry, {\n ...config,\n io,\n target: config.target,\n metadata: registry,\n unrepresentable: config.unrepresentable ?? 'any',\n cycles: 'ref',\n reused: 'inline',\n /**\n * The uri option only allows customizing the base path of the `$ref`, and it automatically appends a path to it.\n * As a workaround, we set a placeholder that looks something like this.\n * @see jsonSchemaReplaceRef\n * @see https://github.com/colinhacks/zod/issues/4750\n */\n uri: () => SCHEMA_URI_PLACEHOLDER,\n override: config.override ?? ((ctx) => getOverride(ctx, io)),\n })\n\n const jsonSchema = deleteInvalidProperties(result)\n\n /**\n * Replace the previous generated placeholders with the final `$ref` value\n */\n return JSON.parse(JSON.stringify(jsonSchema), (__key, value) => {\n if (typeof value === 'string' && value.startsWith(SCHEMA_URI_PLACEHOLDER)) {\n return getReferenceUri(value.slice(SCHEMA_URI_PLACEHOLDER.length))\n }\n return value\n }) as typeof result\n}\n\nexport const zodRegistryToJson: (\n registry: $ZodRegistry<SchemaRegistryMeta>,\n io: 'input' | 'output',\n config: ZodToJsonConfig,\n) => Record<string, JSONSchema.BaseSchema> = (registry, io, config) => {\n const result = toJSONSchema(registry, {\n ...config,\n io,\n target: config.target,\n metadata: registry,\n unrepresentable: config.unrepresentable ?? 'any',\n cycles: 'ref',\n reused: 'inline',\n uri: (id) => getReferenceUri(id),\n override: config.override ?? ((ctx) => getOverride(ctx, io)),\n }).schemas\n\n const jsonSchemas: Record<string, JSONSchema.BaseSchema> = {}\n for (const id in result) {\n jsonSchemas[id] = deleteInvalidProperties(result[id])\n }\n\n return jsonSchemas\n}\n"],"names":["$ZodType","getReferenceUri","$ZodRegistry","toJSONSchema"],"mappings":";;;;AAWA,MAAM,iCAAiC;AACvC,MAAM,yBAAyB;AAE/B,SAAS,UAAU,QAAqC;AACtD,SAAO,kBAAkBA,KAAAA,YAAY,OAAO,KAAK,IAAI,SAAS;AAChE;AAEA,SAAS,WAAW,QAAsC;AACxD,SAAO,kBAAkBA,KAAAA,YAAY,OAAO,KAAK,IAAI,SAAS;AAChE;AAEA,SAAS,eAAe,QAA0C;AAChE,SAAO,kBAAkBA,KAAAA,YAAY,OAAO,KAAK,IAAI,SAAS;AAChE;AAEA,MAAM,cAAc,CAClB,KAIA,OACG;AACH,MAAI,WAAW,IAAI,SAAS,GAAG;AAI7B,QAAI,WAAW,QAAQ,IAAI,WAAW,OAAO,OAAO,CAAC,WAAW,OAAO,KAAK,MAAM,EAAE,SAAS,CAAC;AAAA,EAChG;AAEA,MAAI,UAAU,IAAI,SAAS,GAAG;AAE5B,QAAI,OAAO,UAAU;AACnB,UAAI,WAAW,OAAO;AACtB,UAAI,WAAW,SAAS;AAAA,IAC1B;AAAA,EACF;AAEA,MAAI,eAAe,IAAI,SAAS,GAAG;AAEjC,QAAI,OAAO,UAAU;AACnB,UAAI,WAAW,OAAO;AAAA,IACxB;AAAA,EACF;AACF;AAOA,MAAM,0BAE+C,CAAC,WAAW;AAC/D,QAAM,SAAS,EAAE,GAAG,OAAA;AAEpB,SAAO,OAAO;AACd,SAAO,OAAO;AAGd,SAAO,OAAO;AAEd,SAAO;AACT;AAEO,MAAM,kBAKqC,CAAC,WAAW,UAAU,IAAI,WAAW;AAOrF,QAAM,sBAAsB,SAAS,IAAI,SAAS;AAClD,MAAI,qBAAqB,IAAI;AAC3B,WAAO,EAAE,MAAMC,MAAAA,gBAAgB,oBAAoB,EAAE,EAAA;AAAA,EACvD;AAUA,QAAM,eAAe,IAAIC,kBAAA;AACzB,eAAa,IAAI,WAAW,EAAE,IAAI,gCAAgC;AAElE,QAAM;AAAA,IACJ,SAAS,EAAE,CAAC,8BAA8B,GAAG,OAAA;AAAA,EAAO,IAClDC,KAAAA,aAAa,cAAc;AAAA,IAC7B,GAAG;AAAA,IACH;AAAA,IACA,QAAQ,OAAO;AAAA,IACf,UAAU;AAAA,IACV,iBAAiB,OAAO,mBAAmB;AAAA,IAC3C,QAAQ;AAAA,IACR,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOR,KAAK,MAAM;AAAA,IACX,UAAU,OAAO,aAAa,CAAC,QAAQ,YAAY,KAAK,EAAE;AAAA,EAAA,CAC3D;AAED,QAAM,aAAa,wBAAwB,MAAM;AAKjD,SAAO,KAAK,MAAM,KAAK,UAAU,UAAU,GAAG,CAAC,OAAO,UAAU;AAC9D,QAAI,OAAO,UAAU,YAAY,MAAM,WAAW,sBAAsB,GAAG;AACzE,aAAOF,MAAAA,gBAAgB,MAAM,MAAM,uBAAuB,MAAM,CAAC;AAAA,IACnE;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAEO,MAAM,oBAIgC,CAAC,UAAU,IAAI,WAAW;AACrE,QAAM,SAASE,KAAAA,aAAa,UAAU;AAAA,IACpC,GAAG;AAAA,IACH;AAAA,IACA,QAAQ,OAAO;AAAA,IACf,UAAU;AAAA,IACV,iBAAiB,OAAO,mBAAmB;AAAA,IAC3C,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,KAAK,CAAC,OAAOF,MAAAA,gBAAgB,EAAE;AAAA,IAC/B,UAAU,OAAO,aAAa,CAAC,QAAQ,YAAY,KAAK,EAAE;AAAA,EAAA,CAC3D,EAAE;AAEH,QAAM,cAAqD,CAAA;AAC3D,aAAW,MAAM,QAAQ;AACvB,gBAAY,EAAE,IAAI,wBAAwB,OAAO,EAAE,CAAC;AAAA,EACtD;AAEA,SAAO;AACT;;;"}
@@ -0,0 +1,8 @@
1
+ import type { JSONSchema, RegistryToJSONSchemaParams } from "zod/v4/core";
2
+ import { $ZodRegistry, $ZodType } from "zod/v4/core";
3
+ import type { SchemaRegistryMeta } from "../cjs/registry.cjs";
4
+ export type ZodToJsonConfig = {} & Omit<RegistryToJSONSchemaParams, "io" | "metadata" | "cycles" | "reused" | "uri">;
5
+ declare const deleteInvalidProperties: (schema: JSONSchema.BaseSchema) => Omit<JSONSchema.BaseSchema, "id" | "$schema">;
6
+ export declare const zodSchemaToJson: (zodSchema: $ZodType, registry: $ZodRegistry<SchemaRegistryMeta>, io: "input" | "output", config: ZodToJsonConfig) => ReturnType<typeof deleteInvalidProperties>;
7
+ export declare const zodRegistryToJson: (registry: $ZodRegistry<SchemaRegistryMeta>, io: "input" | "output", config: ZodToJsonConfig) => Record<string, JSONSchema.BaseSchema>;
8
+ export {};
@@ -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 "../esm/registry.js";
7
+ import { type ZodToJsonConfig } from "../esm/zod-to-json.js";
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,125 @@
1
+ import { globalRegistry, safeEncode, safeDecode, $ZodType } from "zod/v4/core";
2
+ import { ResponseSerializationError, createValidationError, InvalidSchemaError } from "./errors.js";
3
+ import { generateIORegistries } from "./registry.js";
4
+ import { assertIsOpenAPIObject, getJSONSchemaTarget } from "./utils.js";
5
+ import { zodSchemaToJson, zodRegistryToJson } from "./zod-to-json.js";
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 createJsonSchemaTransform = ({
16
+ skipList = defaultSkipList,
17
+ schemaRegistry = globalRegistry,
18
+ zodToJsonConfig = {}
19
+ }) => {
20
+ return (document) => {
21
+ assertIsOpenAPIObject(document);
22
+ const { schema, url } = document;
23
+ if (!schema) {
24
+ return {
25
+ schema,
26
+ url
27
+ };
28
+ }
29
+ const target = getJSONSchemaTarget(document.openapiObject.openapi);
30
+ const config = {
31
+ target,
32
+ ...zodToJsonConfig
33
+ };
34
+ const { inputRegistry, outputRegistry } = generateIORegistries(schemaRegistry);
35
+ const { response, headers, querystring, body, params, hide, ...rest } = schema;
36
+ const transformed = {};
37
+ if (skipList.includes(url) || hide) {
38
+ transformed.hide = true;
39
+ return { schema: transformed, url };
40
+ }
41
+ const zodSchemas = { headers, querystring, body, params };
42
+ for (const prop in zodSchemas) {
43
+ const zodSchema = zodSchemas[prop];
44
+ if (zodSchema) {
45
+ transformed[prop] = zodSchemaToJson(zodSchema, inputRegistry, "input", config);
46
+ }
47
+ }
48
+ if (response) {
49
+ transformed.response = {};
50
+ for (const prop in response) {
51
+ const zodSchema = resolveSchema(response[prop]);
52
+ transformed.response[prop] = zodSchemaToJson(zodSchema, outputRegistry, "output", config);
53
+ }
54
+ }
55
+ for (const prop in rest) {
56
+ const meta = rest[prop];
57
+ if (meta) {
58
+ transformed[prop] = meta;
59
+ }
60
+ }
61
+ return { schema: transformed, url };
62
+ };
63
+ };
64
+ const jsonSchemaTransform = createJsonSchemaTransform({});
65
+ const createJsonSchemaTransformObject = ({
66
+ schemaRegistry = globalRegistry,
67
+ zodToJsonConfig = {}
68
+ }) => (document) => {
69
+ assertIsOpenAPIObject(document);
70
+ const target = getJSONSchemaTarget(document.openapiObject.openapi);
71
+ const config = {
72
+ target,
73
+ ...zodToJsonConfig
74
+ };
75
+ const { inputRegistry, outputRegistry } = generateIORegistries(schemaRegistry);
76
+ const inputSchemas = zodRegistryToJson(inputRegistry, "input", config);
77
+ const outputSchemas = zodRegistryToJson(outputRegistry, "output", config);
78
+ return {
79
+ ...document.openapiObject,
80
+ components: {
81
+ ...document.openapiObject.components,
82
+ schemas: {
83
+ ...document.openapiObject.components?.schemas,
84
+ ...inputSchemas,
85
+ ...outputSchemas
86
+ }
87
+ }
88
+ };
89
+ };
90
+ const jsonSchemaTransformObject = createJsonSchemaTransformObject({});
91
+ const validatorCompiler = ({ schema }) => (data) => {
92
+ const result = safeDecode(schema, data);
93
+ if (result.error) {
94
+ return { error: createValidationError(result.error) };
95
+ }
96
+ return { value: result.data };
97
+ };
98
+ function resolveSchema(maybeSchema) {
99
+ if (maybeSchema instanceof $ZodType) {
100
+ return maybeSchema;
101
+ }
102
+ if ("properties" in maybeSchema && maybeSchema.properties instanceof $ZodType) {
103
+ return maybeSchema.properties;
104
+ }
105
+ throw new InvalidSchemaError(JSON.stringify(maybeSchema));
106
+ }
107
+ const createSerializerCompiler = (options) => ({ schema: maybeSchema, method, url }) => (data) => {
108
+ const schema = resolveSchema(maybeSchema);
109
+ const result = safeEncode(schema, data);
110
+ if (result.error) {
111
+ throw new ResponseSerializationError(method, url, { cause: result.error });
112
+ }
113
+ return JSON.stringify(result.data, options?.replacer);
114
+ };
115
+ const serializerCompiler = createSerializerCompiler({});
116
+ export {
117
+ createJsonSchemaTransform,
118
+ createJsonSchemaTransformObject,
119
+ createSerializerCompiler,
120
+ jsonSchemaTransform,
121
+ jsonSchemaTransformObject,
122
+ serializerCompiler,
123
+ validatorCompiler
124
+ };
125
+ //# sourceMappingURL=core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.js","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":[],"mappings":"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"}
@@ -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,57 @@
1
+ import createError from "@fastify/error";
2
+ const InvalidSchemaError = createError("FST_ERR_INVALID_SCHEMA", "Invalid schema passed: %s", 500);
3
+ const ZodFastifySchemaValidationErrorSymbol = /* @__PURE__ */ Symbol.for("ZodFastifySchemaValidationError");
4
+ const ResponseSerializationBase = createError(
5
+ "FST_ERR_RESPONSE_SERIALIZATION",
6
+ "Response doesn't match the schema",
7
+ 500
8
+ );
9
+ class ResponseSerializationError extends ResponseSerializationBase {
10
+ constructor(method, url, options) {
11
+ super({ cause: options.cause });
12
+ this.method = method;
13
+ this.url = url;
14
+ this.cause = options.cause;
15
+ }
16
+ cause;
17
+ }
18
+ function isResponseSerializationError(value) {
19
+ return "method" in value;
20
+ }
21
+ function isZodFastifySchemaValidationError(error) {
22
+ return typeof error === "object" && error !== null && error[ZodFastifySchemaValidationErrorSymbol] === true;
23
+ }
24
+ function hasZodFastifySchemaValidationErrors(error) {
25
+ return typeof error === "object" && error !== null && "validation" in error && Array.isArray(error.validation) && error.validation.length > 0 && isZodFastifySchemaValidationError(error.validation[0]);
26
+ }
27
+ function omit(obj, keys) {
28
+ const result = {};
29
+ for (const key of Object.keys(obj)) {
30
+ if (!keys.includes(key)) {
31
+ result[key] = obj[key];
32
+ }
33
+ }
34
+ return result;
35
+ }
36
+ function createValidationError(error) {
37
+ return error.issues.map((issue) => {
38
+ return {
39
+ [ZodFastifySchemaValidationErrorSymbol]: true,
40
+ keyword: issue.code,
41
+ instancePath: `/${issue.path.join("/")}`,
42
+ schemaPath: `#/${issue.path.join("/")}/${issue.code}`,
43
+ message: issue.message,
44
+ params: {
45
+ ...omit(issue, ["path", "code", "message"])
46
+ }
47
+ };
48
+ });
49
+ }
50
+ export {
51
+ InvalidSchemaError,
52
+ ResponseSerializationError,
53
+ createValidationError,
54
+ hasZodFastifySchemaValidationErrors,
55
+ isResponseSerializationError
56
+ };
57
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","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,2 @@
1
+ export { createJsonSchemaTransform, createJsonSchemaTransformObject, createSerializerCompiler, type FastifyPluginAsyncZod, type FastifyPluginCallbackZod, jsonSchemaTransform, jsonSchemaTransformObject, serializerCompiler, validatorCompiler, type ZodSerializerCompilerOptions, type ZodTypeProvider } from "../esm/core.js";
2
+ export { hasZodFastifySchemaValidationErrors, InvalidSchemaError, isResponseSerializationError, ResponseSerializationError, type ZodFastifySchemaValidationError } from "../esm/errors.js";
@@ -0,0 +1,16 @@
1
+ import { createJsonSchemaTransform, createJsonSchemaTransformObject, createSerializerCompiler, jsonSchemaTransform, jsonSchemaTransformObject, serializerCompiler, validatorCompiler } from "./core.js";
2
+ import { InvalidSchemaError, ResponseSerializationError, hasZodFastifySchemaValidationErrors, isResponseSerializationError } from "./errors.js";
3
+ export {
4
+ InvalidSchemaError,
5
+ ResponseSerializationError,
6
+ createJsonSchemaTransform,
7
+ createJsonSchemaTransformObject,
8
+ createSerializerCompiler,
9
+ hasZodFastifySchemaValidationErrors,
10
+ isResponseSerializationError,
11
+ jsonSchemaTransform,
12
+ jsonSchemaTransformObject,
13
+ serializerCompiler,
14
+ validatorCompiler
15
+ };
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
@@ -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,43 @@
1
+ import { $ZodRegistry } from "zod/v4/core";
2
+ const getSchemaId = (id, io) => {
3
+ return io === "input" ? `${id}Input` : id;
4
+ };
5
+ class WeakMapWithFallback extends WeakMap {
6
+ constructor(fallback) {
7
+ super();
8
+ this.fallback = fallback;
9
+ }
10
+ get(key) {
11
+ return super.get(key) ?? this.fallback.get(key);
12
+ }
13
+ has(key) {
14
+ return super.has(key) || this.fallback.has(key);
15
+ }
16
+ }
17
+ const copyRegistry = (inputRegistry, idReplaceFn) => {
18
+ const outputRegistry = new $ZodRegistry();
19
+ outputRegistry._map = new WeakMapWithFallback(inputRegistry._map);
20
+ inputRegistry._idmap.forEach((schema, id) => {
21
+ outputRegistry.add(schema, {
22
+ ...inputRegistry._map.get(schema),
23
+ id: idReplaceFn(id)
24
+ });
25
+ });
26
+ return outputRegistry;
27
+ };
28
+ const generateIORegistries = (baseRegistry) => {
29
+ const inputRegistry = copyRegistry(baseRegistry, (id) => getSchemaId(id, "input"));
30
+ const outputRegistry = copyRegistry(baseRegistry, (id) => getSchemaId(id, "output"));
31
+ inputRegistry._idmap.forEach((_, id) => {
32
+ if (outputRegistry._idmap.has(id)) {
33
+ throw new Error(
34
+ `Collision detected for schema "${id}". There is already an input schema with the same name.`
35
+ );
36
+ }
37
+ });
38
+ return { inputRegistry, outputRegistry };
39
+ };
40
+ export {
41
+ generateIORegistries
42
+ };
43
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.js","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":[],"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,IAAI,aAAA;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,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 {};
@@ -0,0 +1,21 @@
1
+ const assertIsOpenAPIObject = (obj) => {
2
+ if ("swaggerObject" in obj) {
3
+ throw new Error("This package currently does not support component references for Swagger 2.0");
4
+ }
5
+ };
6
+ const getReferenceUri = (input) => {
7
+ const id = input.replace(/^#\/(?:\$defs|definitions|components\/schemas)\//, "");
8
+ return `#/components/schemas/${id}`;
9
+ };
10
+ const getJSONSchemaTarget = (version = "3.0.0") => {
11
+ if (version.startsWith("3.0")) {
12
+ return "openapi-3.0";
13
+ }
14
+ return "draft-2020-12";
15
+ };
16
+ export {
17
+ assertIsOpenAPIObject,
18
+ getJSONSchemaTarget,
19
+ getReferenceUri
20
+ };
21
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","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,8 @@
1
+ import type { JSONSchema, RegistryToJSONSchemaParams } from "zod/v4/core";
2
+ import { $ZodRegistry, $ZodType } from "zod/v4/core";
3
+ import type { SchemaRegistryMeta } from "../esm/registry.js";
4
+ export type ZodToJsonConfig = {} & Omit<RegistryToJSONSchemaParams, "io" | "metadata" | "cycles" | "reused" | "uri">;
5
+ declare const deleteInvalidProperties: (schema: JSONSchema.BaseSchema) => Omit<JSONSchema.BaseSchema, "id" | "$schema">;
6
+ export declare const zodSchemaToJson: (zodSchema: $ZodType, registry: $ZodRegistry<SchemaRegistryMeta>, io: "input" | "output", config: ZodToJsonConfig) => ReturnType<typeof deleteInvalidProperties>;
7
+ export declare const zodRegistryToJson: (registry: $ZodRegistry<SchemaRegistryMeta>, io: "input" | "output", config: ZodToJsonConfig) => Record<string, JSONSchema.BaseSchema>;
8
+ export {};