@rexeus/typeweaver-zod-to-json-schema 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -0
- package/dist/LICENSE +202 -0
- package/dist/NOTICE +4 -0
- package/dist/index.cjs +357 -0
- package/dist/index.d.cts +24 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +24 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +358 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +62 -0
package/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# @rexeus/typeweaver-zod-to-json-schema
|
|
2
|
+
|
|
3
|
+
Converts Zod v4 schemas to JSON Schema Draft 2020-12-compatible objects. Typeweaver uses this
|
|
4
|
+
package as the reusable conversion layer for OpenAPI 3.1 generation, but it is intentionally
|
|
5
|
+
standalone.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm add @rexeus/typeweaver-zod-to-json-schema zod
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { fromZod } from "@rexeus/typeweaver-zod-to-json-schema";
|
|
17
|
+
import { z } from "zod";
|
|
18
|
+
|
|
19
|
+
const result = fromZod(
|
|
20
|
+
z.object({
|
|
21
|
+
id: z.uuid(),
|
|
22
|
+
name: z.string().optional(),
|
|
23
|
+
})
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
console.log(result.schema);
|
|
27
|
+
// {
|
|
28
|
+
// type: "object",
|
|
29
|
+
// properties: { id: { type: "string", format: "uuid" }, name: { type: "string" } },
|
|
30
|
+
// required: ["id"],
|
|
31
|
+
// additionalProperties: false
|
|
32
|
+
// }
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`fromZod()` returns both the JSON Schema and deterministic warnings for Zod features that JSON
|
|
36
|
+
Schema cannot represent precisely, such as transforms, custom refinements, dates, maps, and sets.
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
const { schema, warnings } = fromZod(z.string().transform(value => value.length));
|
|
40
|
+
|
|
41
|
+
// schema falls back to a broad JSON Schema object when Zod cannot represent the
|
|
42
|
+
// runtime behavior exactly.
|
|
43
|
+
console.log(schema); // {}
|
|
44
|
+
console.log(warnings[0]?.code); // "unsupported-schema"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
If Zod's conversion throws, `fromZod()` does not throw. It returns `{ schema: {}, warnings }` and
|
|
48
|
+
appends a `conversion-error` warning with the original error message.
|
|
49
|
+
|
|
50
|
+
Warning paths are JSON Pointer strings. When a warning corresponds to JSON Schema output, the path
|
|
51
|
+
points at that output location: the root path is `""`, object properties appear under
|
|
52
|
+
`/properties/name`, and record keys and values appear under `/propertyNames` and
|
|
53
|
+
`/additionalProperties`. Pointer segments escape `~` as `~0` and `/` as `~1`. Source-side Zod
|
|
54
|
+
concepts without a direct JSON Schema output location use stable Typeweaver extension paths under
|
|
55
|
+
the nearest output path, such as `/x-typeweaver/mapKey`, `/x-typeweaver/mapValue`,
|
|
56
|
+
`/x-typeweaver/pipeIn`, and `/x-typeweaver/pipeOut`. For example, a root pipe input is reported at
|
|
57
|
+
`/x-typeweaver/pipeIn`, while a `count` property pipe output is reported at
|
|
58
|
+
`/properties/count/x-typeweaver/pipeOut`.
|
|
59
|
+
|
|
60
|
+
Warnings include `schemaType` as best-effort diagnostic context from the source Zod schema. Treat it
|
|
61
|
+
as debugging detail, not a stable public API contract.
|
|
62
|
+
|
|
63
|
+
## Output
|
|
64
|
+
|
|
65
|
+
- Target dialect: JSON Schema Draft 2020-12.
|
|
66
|
+
- The root `$schema` marker from Zod's output is stripped for easier embedding in downstream OpenAPI
|
|
67
|
+
documents.
|
|
68
|
+
- Tuple schemas are normalized with `minItems`. Fixed-length tuples also receive `items: {}` and
|
|
69
|
+
`maxItems`; rest tuples preserve their `items` schema and do not receive a synthesized `maxItems`.
|
package/dist/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Dennis Wentzien
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/NOTICE
ADDED
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let zod = require("zod");
|
|
3
|
+
//#region src/internal/zodIntrospection.ts
|
|
4
|
+
const TRANSPARENT_WRAPPER_TYPES = new Set([
|
|
5
|
+
"optional",
|
|
6
|
+
"nullable",
|
|
7
|
+
"default",
|
|
8
|
+
"catch",
|
|
9
|
+
"prefault",
|
|
10
|
+
"readonly",
|
|
11
|
+
"nonoptional"
|
|
12
|
+
]);
|
|
13
|
+
function getSchemaDefinition(schema) {
|
|
14
|
+
if (schema === void 0) return;
|
|
15
|
+
const schemaWithDefinition = schema;
|
|
16
|
+
return schemaWithDefinition._zod?.def ?? schemaWithDefinition.def ?? schemaWithDefinition._def;
|
|
17
|
+
}
|
|
18
|
+
function getZodDef(schema) {
|
|
19
|
+
return getSchemaDefinition(schema);
|
|
20
|
+
}
|
|
21
|
+
function getSchemaType(schema) {
|
|
22
|
+
if (schema === void 0) return;
|
|
23
|
+
return getSchemaDefinition(schema)?.type ?? "unknown";
|
|
24
|
+
}
|
|
25
|
+
function isZodTransparentWrapperType(schemaType, transparentWrapperTypes = TRANSPARENT_WRAPPER_TYPES) {
|
|
26
|
+
return schemaType !== void 0 && transparentWrapperTypes.has(schemaType);
|
|
27
|
+
}
|
|
28
|
+
function isZodSchema(value) {
|
|
29
|
+
if (typeof value !== "object" || value === null || !("_zod" in value)) return false;
|
|
30
|
+
const zodMetadata = value._zod;
|
|
31
|
+
return typeof zodMetadata === "object" && zodMetadata !== null && "def" in zodMetadata && typeof zodMetadata.def === "object" && zodMetadata.def !== null;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/internal/collectZodWarnings.ts
|
|
35
|
+
const SUPPORTED_SCHEMA_TYPES = new Set([
|
|
36
|
+
"any",
|
|
37
|
+
"array",
|
|
38
|
+
"boolean",
|
|
39
|
+
"catch",
|
|
40
|
+
"default",
|
|
41
|
+
"enum",
|
|
42
|
+
"intersection",
|
|
43
|
+
"lazy",
|
|
44
|
+
"literal",
|
|
45
|
+
"null",
|
|
46
|
+
"nullable",
|
|
47
|
+
"number",
|
|
48
|
+
"object",
|
|
49
|
+
"optional",
|
|
50
|
+
"prefault",
|
|
51
|
+
"record",
|
|
52
|
+
"string",
|
|
53
|
+
"tuple",
|
|
54
|
+
"union",
|
|
55
|
+
"unknown"
|
|
56
|
+
]);
|
|
57
|
+
const SUPPORTED_CHECKS = new Set([
|
|
58
|
+
"greater_than",
|
|
59
|
+
"length_equals",
|
|
60
|
+
"less_than",
|
|
61
|
+
"max_length",
|
|
62
|
+
"max_size",
|
|
63
|
+
"mime_type",
|
|
64
|
+
"min_length",
|
|
65
|
+
"min_size",
|
|
66
|
+
"multiple_of",
|
|
67
|
+
"number_format",
|
|
68
|
+
"overwrite",
|
|
69
|
+
"property",
|
|
70
|
+
"regex",
|
|
71
|
+
"size_equals",
|
|
72
|
+
"string_format"
|
|
73
|
+
]);
|
|
74
|
+
const SUPPORTED_STRING_FORMATS = new Set([
|
|
75
|
+
"base64",
|
|
76
|
+
"base64url",
|
|
77
|
+
"cuid",
|
|
78
|
+
"cuid2",
|
|
79
|
+
"date",
|
|
80
|
+
"datetime",
|
|
81
|
+
"duration",
|
|
82
|
+
"e164",
|
|
83
|
+
"email",
|
|
84
|
+
"emoji",
|
|
85
|
+
"ends_with",
|
|
86
|
+
"guid",
|
|
87
|
+
"includes",
|
|
88
|
+
"ipv4",
|
|
89
|
+
"ipv6",
|
|
90
|
+
"jwt",
|
|
91
|
+
"lowercase",
|
|
92
|
+
"nanoid",
|
|
93
|
+
"regex",
|
|
94
|
+
"starts_with",
|
|
95
|
+
"time",
|
|
96
|
+
"ulid",
|
|
97
|
+
"uppercase",
|
|
98
|
+
"url",
|
|
99
|
+
"uuid"
|
|
100
|
+
]);
|
|
101
|
+
function collectZodWarnings(schema) {
|
|
102
|
+
const collector = {
|
|
103
|
+
warnings: [],
|
|
104
|
+
seen: /* @__PURE__ */ new WeakSet()
|
|
105
|
+
};
|
|
106
|
+
collectWarnings(schema, collector, []);
|
|
107
|
+
return collector.warnings;
|
|
108
|
+
}
|
|
109
|
+
function createWarning(input) {
|
|
110
|
+
return {
|
|
111
|
+
code: input.code,
|
|
112
|
+
schemaType: input.schemaType,
|
|
113
|
+
path: formatPath(input.path),
|
|
114
|
+
message: input.message
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function collectWarnings(schema, collector, path) {
|
|
118
|
+
if (!isZodSchema(schema) || collector.seen.has(schema)) return;
|
|
119
|
+
collector.seen.add(schema);
|
|
120
|
+
const def = getZodDef(schema);
|
|
121
|
+
const schemaType = getSchemaType(schema);
|
|
122
|
+
if (def === void 0) return;
|
|
123
|
+
collectCheckWarnings(def, collector, path, schemaType);
|
|
124
|
+
collectUnsupportedSchemaWarning(schemaType, collector, path);
|
|
125
|
+
collectNestedWarnings(def, schemaType, collector, path);
|
|
126
|
+
}
|
|
127
|
+
function collectCheckWarnings(def, collector, path, schemaType) {
|
|
128
|
+
if (schemaType === "custom" || schemaType === "transform") return;
|
|
129
|
+
for (const check of getChecks(def)) {
|
|
130
|
+
const checkDef = check._zod?.def;
|
|
131
|
+
const checkType = checkDef?.check ?? checkDef?.type ?? "unknown";
|
|
132
|
+
const format = checkDef?.format;
|
|
133
|
+
if (isSupportedCheck(checkType, format)) continue;
|
|
134
|
+
collector.warnings.push(createWarning({
|
|
135
|
+
code: "unsupported-check",
|
|
136
|
+
schemaType,
|
|
137
|
+
path,
|
|
138
|
+
message: `Zod ${schemaType} check ${checkType} cannot be represented exactly in JSON Schema.`
|
|
139
|
+
}));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function isSupportedCheck(checkType, format) {
|
|
143
|
+
if (!SUPPORTED_CHECKS.has(checkType)) return false;
|
|
144
|
+
return checkType !== "string_format" || format === void 0 || SUPPORTED_STRING_FORMATS.has(format);
|
|
145
|
+
}
|
|
146
|
+
function getChecks(def) {
|
|
147
|
+
return [...def.check === void 0 ? [] : [{ _zod: { def } }], ...def.checks ?? []];
|
|
148
|
+
}
|
|
149
|
+
function collectUnsupportedSchemaWarning(schemaType, collector, path) {
|
|
150
|
+
if (SUPPORTED_SCHEMA_TYPES.has(schemaType)) return;
|
|
151
|
+
collector.warnings.push(createWarning({
|
|
152
|
+
code: "unsupported-schema",
|
|
153
|
+
schemaType,
|
|
154
|
+
path,
|
|
155
|
+
message: `Zod ${schemaType} falls back to a broader JSON Schema representation.`
|
|
156
|
+
}));
|
|
157
|
+
}
|
|
158
|
+
function collectNestedWarnings(def, schemaType, collector, path) {
|
|
159
|
+
switch (schemaType) {
|
|
160
|
+
case "object":
|
|
161
|
+
collectObjectWarnings(def, collector, path);
|
|
162
|
+
return;
|
|
163
|
+
case "array":
|
|
164
|
+
collectChild(def.element, collector, [...path, "items"]);
|
|
165
|
+
return;
|
|
166
|
+
case "union":
|
|
167
|
+
collectOptionWarnings(def.options, collector, path, "anyOf");
|
|
168
|
+
return;
|
|
169
|
+
case "intersection":
|
|
170
|
+
collectChild(def.left, collector, [
|
|
171
|
+
...path,
|
|
172
|
+
"allOf",
|
|
173
|
+
"0"
|
|
174
|
+
]);
|
|
175
|
+
collectChild(def.right, collector, [
|
|
176
|
+
...path,
|
|
177
|
+
"allOf",
|
|
178
|
+
"1"
|
|
179
|
+
]);
|
|
180
|
+
return;
|
|
181
|
+
case "tuple":
|
|
182
|
+
collectTupleWarnings(def, collector, path);
|
|
183
|
+
return;
|
|
184
|
+
case "record":
|
|
185
|
+
collectChild(def.keyType, collector, [...path, "propertyNames"]);
|
|
186
|
+
collectChild(def.valueType, collector, [...path, "additionalProperties"]);
|
|
187
|
+
return;
|
|
188
|
+
case "lazy":
|
|
189
|
+
collectLazyWarnings(def, collector, path);
|
|
190
|
+
return;
|
|
191
|
+
case "pipe":
|
|
192
|
+
collectChild(def.in, collector, [
|
|
193
|
+
...path,
|
|
194
|
+
"x-typeweaver",
|
|
195
|
+
"pipeIn"
|
|
196
|
+
]);
|
|
197
|
+
collectChild(def.out, collector, [
|
|
198
|
+
...path,
|
|
199
|
+
"x-typeweaver",
|
|
200
|
+
"pipeOut"
|
|
201
|
+
]);
|
|
202
|
+
return;
|
|
203
|
+
case "map":
|
|
204
|
+
collectChild(def.keyType, collector, [
|
|
205
|
+
...path,
|
|
206
|
+
"x-typeweaver",
|
|
207
|
+
"mapKey"
|
|
208
|
+
]);
|
|
209
|
+
collectChild(def.valueType, collector, [
|
|
210
|
+
...path,
|
|
211
|
+
"x-typeweaver",
|
|
212
|
+
"mapValue"
|
|
213
|
+
]);
|
|
214
|
+
return;
|
|
215
|
+
case "set":
|
|
216
|
+
collectChild(def.valueType, collector, [...path, "items"]);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (isZodTransparentWrapperType(schemaType)) collectChild(def.innerType, collector, path);
|
|
220
|
+
}
|
|
221
|
+
function collectObjectWarnings(def, collector, path) {
|
|
222
|
+
for (const [key, value] of Object.entries(def.shape ?? {})) collectChild(value, collector, [
|
|
223
|
+
...path,
|
|
224
|
+
"properties",
|
|
225
|
+
key
|
|
226
|
+
]);
|
|
227
|
+
collectChild(def.catchall, collector, [...path, "additionalProperties"]);
|
|
228
|
+
}
|
|
229
|
+
function collectOptionWarnings(options, collector, path, keyword) {
|
|
230
|
+
for (const [index, option] of (options ?? []).entries()) collectChild(option, collector, [
|
|
231
|
+
...path,
|
|
232
|
+
keyword,
|
|
233
|
+
String(index)
|
|
234
|
+
]);
|
|
235
|
+
}
|
|
236
|
+
function collectTupleWarnings(def, collector, path) {
|
|
237
|
+
for (const [index, item] of (def.items ?? []).entries()) collectChild(item, collector, [
|
|
238
|
+
...path,
|
|
239
|
+
"prefixItems",
|
|
240
|
+
String(index)
|
|
241
|
+
]);
|
|
242
|
+
collectChild(def.rest, collector, [...path, "items"]);
|
|
243
|
+
}
|
|
244
|
+
function collectLazyWarnings(def, collector, path) {
|
|
245
|
+
try {
|
|
246
|
+
collectChild(def.getter?.(), collector, path);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
collector.warnings.push(createWarning({
|
|
249
|
+
code: "conversion-error",
|
|
250
|
+
schemaType: "lazy",
|
|
251
|
+
path,
|
|
252
|
+
message: error instanceof Error ? error.message : "Failed to convert schema to JSON Schema."
|
|
253
|
+
}));
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
function collectChild(value, collector, path) {
|
|
257
|
+
if (isZodSchema(value)) collectWarnings(value, collector, path);
|
|
258
|
+
}
|
|
259
|
+
function formatPath(path) {
|
|
260
|
+
if (path.length === 0) return "";
|
|
261
|
+
return `/${path.map(encodeJsonPointerSegment).join("/")}`;
|
|
262
|
+
}
|
|
263
|
+
function encodeJsonPointerSegment(segment) {
|
|
264
|
+
return segment.replaceAll("~", "~0").replaceAll("/", "~1");
|
|
265
|
+
}
|
|
266
|
+
//#endregion
|
|
267
|
+
//#region src/internal/normalizeJsonSchema.ts
|
|
268
|
+
const SCHEMA_CHILD_KEYS = new Set([
|
|
269
|
+
"items",
|
|
270
|
+
"contains",
|
|
271
|
+
"propertyNames",
|
|
272
|
+
"if",
|
|
273
|
+
"then",
|
|
274
|
+
"else",
|
|
275
|
+
"not"
|
|
276
|
+
]);
|
|
277
|
+
const OBJECT_SCHEMA_CHILD_KEYS = new Set(["additionalProperties"]);
|
|
278
|
+
const SCHEMA_CHILD_MAP_KEYS = new Set([
|
|
279
|
+
"properties",
|
|
280
|
+
"patternProperties",
|
|
281
|
+
"$defs",
|
|
282
|
+
"definitions"
|
|
283
|
+
]);
|
|
284
|
+
const SCHEMA_CHILD_ARRAY_KEYS = new Set([
|
|
285
|
+
"prefixItems",
|
|
286
|
+
"allOf",
|
|
287
|
+
"anyOf",
|
|
288
|
+
"oneOf"
|
|
289
|
+
]);
|
|
290
|
+
function normalizeJsonSchema(schema) {
|
|
291
|
+
const normalizedSchema = Object.fromEntries(Object.entries(schema).map(([key, value]) => [key, normalizeSchemaKeyword(schema, key, value)]));
|
|
292
|
+
if (!isTupleSchema(normalizedSchema)) return normalizedSchema;
|
|
293
|
+
return normalizeTupleSchema(normalizedSchema);
|
|
294
|
+
}
|
|
295
|
+
function normalizeTupleSchema(schema) {
|
|
296
|
+
const itemCount = schema.prefixItems.length;
|
|
297
|
+
const minItems = schema.minItems ?? itemCount;
|
|
298
|
+
if (hasOwnSchemaKeyword(schema, "items")) return {
|
|
299
|
+
...schema,
|
|
300
|
+
minItems
|
|
301
|
+
};
|
|
302
|
+
return {
|
|
303
|
+
...schema,
|
|
304
|
+
items: schema.items ?? {},
|
|
305
|
+
minItems,
|
|
306
|
+
maxItems: schema.maxItems ?? itemCount
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
function normalizeSchemaKeyword(parent, key, value) {
|
|
310
|
+
if (SCHEMA_CHILD_KEYS.has(key) && isJsonSchema(value)) return normalizeJsonSchema(value);
|
|
311
|
+
if (OBJECT_SCHEMA_CHILD_KEYS.has(key) && parent.type === "object" && isJsonSchema(value)) return normalizeJsonSchema(value);
|
|
312
|
+
if (SCHEMA_CHILD_MAP_KEYS.has(key) && isJsonSchema(value)) return Object.fromEntries(Object.entries(value).map(([childKey, childValue]) => [childKey, isJsonSchema(childValue) ? normalizeJsonSchema(childValue) : childValue]));
|
|
313
|
+
if (SCHEMA_CHILD_ARRAY_KEYS.has(key) && Array.isArray(value)) return value.map((entry) => isJsonSchema(entry) ? normalizeJsonSchema(entry) : entry);
|
|
314
|
+
return value;
|
|
315
|
+
}
|
|
316
|
+
function isTupleSchema(schema) {
|
|
317
|
+
return schema.type === "array" && Array.isArray(schema.prefixItems);
|
|
318
|
+
}
|
|
319
|
+
function isJsonSchema(value) {
|
|
320
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
321
|
+
}
|
|
322
|
+
function hasOwnSchemaKeyword(schema, keyword) {
|
|
323
|
+
return Object.prototype.hasOwnProperty.call(schema, keyword);
|
|
324
|
+
}
|
|
325
|
+
//#endregion
|
|
326
|
+
//#region src/zodToJsonSchema.ts
|
|
327
|
+
function fromZod(schema) {
|
|
328
|
+
const warnings = [...collectZodWarnings(schema)];
|
|
329
|
+
try {
|
|
330
|
+
return {
|
|
331
|
+
schema: normalizeJsonSchema(stripRootSchemaDialect(zod.z.toJSONSchema(schema, {
|
|
332
|
+
target: "draft-2020-12",
|
|
333
|
+
unrepresentable: "any"
|
|
334
|
+
}))),
|
|
335
|
+
warnings
|
|
336
|
+
};
|
|
337
|
+
} catch (error) {
|
|
338
|
+
if (!warnings.some(isRootConversionWarning)) warnings.push(createWarning({
|
|
339
|
+
code: "conversion-error",
|
|
340
|
+
schemaType: getSchemaType(schema),
|
|
341
|
+
path: [],
|
|
342
|
+
message: error instanceof Error ? error.message : "Failed to convert schema to JSON Schema."
|
|
343
|
+
}));
|
|
344
|
+
return {
|
|
345
|
+
schema: {},
|
|
346
|
+
warnings
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function isRootConversionWarning(warning) {
|
|
351
|
+
return warning.code === "conversion-error" && warning.path === "";
|
|
352
|
+
}
|
|
353
|
+
function stripRootSchemaDialect(schema) {
|
|
354
|
+
return Object.fromEntries(Object.entries(schema).filter(([key]) => key !== "$schema"));
|
|
355
|
+
}
|
|
356
|
+
//#endregion
|
|
357
|
+
exports.fromZod = fromZod;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
//#region src/types.d.ts
|
|
4
|
+
type JsonSchema = {
|
|
5
|
+
readonly [key: string]: JsonSchemaValue;
|
|
6
|
+
};
|
|
7
|
+
type JsonSchemaValue = JsonSchema | readonly JsonSchemaValue[] | string | number | boolean | null;
|
|
8
|
+
type ZodToJsonSchemaWarningCode = "unsupported-schema" | "unsupported-check" | "conversion-error";
|
|
9
|
+
type ZodToJsonSchemaWarning = {
|
|
10
|
+
readonly code: ZodToJsonSchemaWarningCode; /** Best-effort diagnostic source type from Zod internals. */
|
|
11
|
+
readonly schemaType: string; /** JSON Pointer to the affected JSON Schema or Typeweaver extension location; root is "". */
|
|
12
|
+
readonly path: string;
|
|
13
|
+
readonly message: string;
|
|
14
|
+
};
|
|
15
|
+
type ZodToJsonSchemaResult = {
|
|
16
|
+
readonly schema: JsonSchema;
|
|
17
|
+
readonly warnings: readonly ZodToJsonSchemaWarning[];
|
|
18
|
+
};
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/zodToJsonSchema.d.ts
|
|
21
|
+
declare function fromZod(schema: z.core.$ZodType): ZodToJsonSchemaResult;
|
|
22
|
+
//#endregion
|
|
23
|
+
export { type JsonSchema, type JsonSchemaValue, type ZodToJsonSchemaResult, type ZodToJsonSchemaWarning, type ZodToJsonSchemaWarningCode, fromZod };
|
|
24
|
+
//# sourceMappingURL=index.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/types.ts","../src/zodToJsonSchema.ts"],"mappings":";;;KAAY,UAAA;EAAA,UACA,GAAA,WAAc,eAAA;AAAA;AAAA,KAGd,eAAA,GACR,UAAA,YACS,eAAA;AAAA,KAMD,0BAAA;AAAA,KAKA,sBAAA;EAAA,SACD,IAAA,EAAM,0BAAA,EAjBwB;EAAA,SAmB9B,UAAA,UAhBgB;EAAA,SAkBhB,IAAA;EAAA,SACA,OAAA;AAAA;AAAA,KAGC,qBAAA;EAAA,SACD,MAAA,EAAQ,UAAA;EAAA,SACR,QAAA,WAAmB,sBAAA;AAAA;;;iBCfd,OAAA,CAAQ,MAAA,EAAQ,CAAA,CAAE,IAAA,CAAK,QAAA,GAAW,qBAAA"}
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
//#region src/types.d.ts
|
|
4
|
+
type JsonSchema = {
|
|
5
|
+
readonly [key: string]: JsonSchemaValue;
|
|
6
|
+
};
|
|
7
|
+
type JsonSchemaValue = JsonSchema | readonly JsonSchemaValue[] | string | number | boolean | null;
|
|
8
|
+
type ZodToJsonSchemaWarningCode = "unsupported-schema" | "unsupported-check" | "conversion-error";
|
|
9
|
+
type ZodToJsonSchemaWarning = {
|
|
10
|
+
readonly code: ZodToJsonSchemaWarningCode; /** Best-effort diagnostic source type from Zod internals. */
|
|
11
|
+
readonly schemaType: string; /** JSON Pointer to the affected JSON Schema or Typeweaver extension location; root is "". */
|
|
12
|
+
readonly path: string;
|
|
13
|
+
readonly message: string;
|
|
14
|
+
};
|
|
15
|
+
type ZodToJsonSchemaResult = {
|
|
16
|
+
readonly schema: JsonSchema;
|
|
17
|
+
readonly warnings: readonly ZodToJsonSchemaWarning[];
|
|
18
|
+
};
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/zodToJsonSchema.d.ts
|
|
21
|
+
declare function fromZod(schema: z.core.$ZodType): ZodToJsonSchemaResult;
|
|
22
|
+
//#endregion
|
|
23
|
+
export { type JsonSchema, type JsonSchemaValue, type ZodToJsonSchemaResult, type ZodToJsonSchemaWarning, type ZodToJsonSchemaWarningCode, fromZod };
|
|
24
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/zodToJsonSchema.ts"],"mappings":";;;KAAY,UAAA;EAAA,UACA,GAAA,WAAc,eAAA;AAAA;AAAA,KAGd,eAAA,GACR,UAAA,YACS,eAAA;AAAA,KAMD,0BAAA;AAAA,KAKA,sBAAA;EAAA,SACD,IAAA,EAAM,0BAAA,EAjBwB;EAAA,SAmB9B,UAAA,UAhBgB;EAAA,SAkBhB,IAAA;EAAA,SACA,OAAA;AAAA;AAAA,KAGC,qBAAA;EAAA,SACD,MAAA,EAAQ,UAAA;EAAA,SACR,QAAA,WAAmB,sBAAA;AAAA;;;iBCfd,OAAA,CAAQ,MAAA,EAAQ,CAAA,CAAE,IAAA,CAAK,QAAA,GAAW,qBAAA"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region src/internal/zodIntrospection.ts
|
|
3
|
+
const TRANSPARENT_WRAPPER_TYPES = new Set([
|
|
4
|
+
"optional",
|
|
5
|
+
"nullable",
|
|
6
|
+
"default",
|
|
7
|
+
"catch",
|
|
8
|
+
"prefault",
|
|
9
|
+
"readonly",
|
|
10
|
+
"nonoptional"
|
|
11
|
+
]);
|
|
12
|
+
function getSchemaDefinition(schema) {
|
|
13
|
+
if (schema === void 0) return;
|
|
14
|
+
const schemaWithDefinition = schema;
|
|
15
|
+
return schemaWithDefinition._zod?.def ?? schemaWithDefinition.def ?? schemaWithDefinition._def;
|
|
16
|
+
}
|
|
17
|
+
function getZodDef(schema) {
|
|
18
|
+
return getSchemaDefinition(schema);
|
|
19
|
+
}
|
|
20
|
+
function getSchemaType(schema) {
|
|
21
|
+
if (schema === void 0) return;
|
|
22
|
+
return getSchemaDefinition(schema)?.type ?? "unknown";
|
|
23
|
+
}
|
|
24
|
+
function isZodTransparentWrapperType(schemaType, transparentWrapperTypes = TRANSPARENT_WRAPPER_TYPES) {
|
|
25
|
+
return schemaType !== void 0 && transparentWrapperTypes.has(schemaType);
|
|
26
|
+
}
|
|
27
|
+
function isZodSchema(value) {
|
|
28
|
+
if (typeof value !== "object" || value === null || !("_zod" in value)) return false;
|
|
29
|
+
const zodMetadata = value._zod;
|
|
30
|
+
return typeof zodMetadata === "object" && zodMetadata !== null && "def" in zodMetadata && typeof zodMetadata.def === "object" && zodMetadata.def !== null;
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/internal/collectZodWarnings.ts
|
|
34
|
+
const SUPPORTED_SCHEMA_TYPES = new Set([
|
|
35
|
+
"any",
|
|
36
|
+
"array",
|
|
37
|
+
"boolean",
|
|
38
|
+
"catch",
|
|
39
|
+
"default",
|
|
40
|
+
"enum",
|
|
41
|
+
"intersection",
|
|
42
|
+
"lazy",
|
|
43
|
+
"literal",
|
|
44
|
+
"null",
|
|
45
|
+
"nullable",
|
|
46
|
+
"number",
|
|
47
|
+
"object",
|
|
48
|
+
"optional",
|
|
49
|
+
"prefault",
|
|
50
|
+
"record",
|
|
51
|
+
"string",
|
|
52
|
+
"tuple",
|
|
53
|
+
"union",
|
|
54
|
+
"unknown"
|
|
55
|
+
]);
|
|
56
|
+
const SUPPORTED_CHECKS = new Set([
|
|
57
|
+
"greater_than",
|
|
58
|
+
"length_equals",
|
|
59
|
+
"less_than",
|
|
60
|
+
"max_length",
|
|
61
|
+
"max_size",
|
|
62
|
+
"mime_type",
|
|
63
|
+
"min_length",
|
|
64
|
+
"min_size",
|
|
65
|
+
"multiple_of",
|
|
66
|
+
"number_format",
|
|
67
|
+
"overwrite",
|
|
68
|
+
"property",
|
|
69
|
+
"regex",
|
|
70
|
+
"size_equals",
|
|
71
|
+
"string_format"
|
|
72
|
+
]);
|
|
73
|
+
const SUPPORTED_STRING_FORMATS = new Set([
|
|
74
|
+
"base64",
|
|
75
|
+
"base64url",
|
|
76
|
+
"cuid",
|
|
77
|
+
"cuid2",
|
|
78
|
+
"date",
|
|
79
|
+
"datetime",
|
|
80
|
+
"duration",
|
|
81
|
+
"e164",
|
|
82
|
+
"email",
|
|
83
|
+
"emoji",
|
|
84
|
+
"ends_with",
|
|
85
|
+
"guid",
|
|
86
|
+
"includes",
|
|
87
|
+
"ipv4",
|
|
88
|
+
"ipv6",
|
|
89
|
+
"jwt",
|
|
90
|
+
"lowercase",
|
|
91
|
+
"nanoid",
|
|
92
|
+
"regex",
|
|
93
|
+
"starts_with",
|
|
94
|
+
"time",
|
|
95
|
+
"ulid",
|
|
96
|
+
"uppercase",
|
|
97
|
+
"url",
|
|
98
|
+
"uuid"
|
|
99
|
+
]);
|
|
100
|
+
function collectZodWarnings(schema) {
|
|
101
|
+
const collector = {
|
|
102
|
+
warnings: [],
|
|
103
|
+
seen: /* @__PURE__ */ new WeakSet()
|
|
104
|
+
};
|
|
105
|
+
collectWarnings(schema, collector, []);
|
|
106
|
+
return collector.warnings;
|
|
107
|
+
}
|
|
108
|
+
function createWarning(input) {
|
|
109
|
+
return {
|
|
110
|
+
code: input.code,
|
|
111
|
+
schemaType: input.schemaType,
|
|
112
|
+
path: formatPath(input.path),
|
|
113
|
+
message: input.message
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function collectWarnings(schema, collector, path) {
|
|
117
|
+
if (!isZodSchema(schema) || collector.seen.has(schema)) return;
|
|
118
|
+
collector.seen.add(schema);
|
|
119
|
+
const def = getZodDef(schema);
|
|
120
|
+
const schemaType = getSchemaType(schema);
|
|
121
|
+
if (def === void 0) return;
|
|
122
|
+
collectCheckWarnings(def, collector, path, schemaType);
|
|
123
|
+
collectUnsupportedSchemaWarning(schemaType, collector, path);
|
|
124
|
+
collectNestedWarnings(def, schemaType, collector, path);
|
|
125
|
+
}
|
|
126
|
+
function collectCheckWarnings(def, collector, path, schemaType) {
|
|
127
|
+
if (schemaType === "custom" || schemaType === "transform") return;
|
|
128
|
+
for (const check of getChecks(def)) {
|
|
129
|
+
const checkDef = check._zod?.def;
|
|
130
|
+
const checkType = checkDef?.check ?? checkDef?.type ?? "unknown";
|
|
131
|
+
const format = checkDef?.format;
|
|
132
|
+
if (isSupportedCheck(checkType, format)) continue;
|
|
133
|
+
collector.warnings.push(createWarning({
|
|
134
|
+
code: "unsupported-check",
|
|
135
|
+
schemaType,
|
|
136
|
+
path,
|
|
137
|
+
message: `Zod ${schemaType} check ${checkType} cannot be represented exactly in JSON Schema.`
|
|
138
|
+
}));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function isSupportedCheck(checkType, format) {
|
|
142
|
+
if (!SUPPORTED_CHECKS.has(checkType)) return false;
|
|
143
|
+
return checkType !== "string_format" || format === void 0 || SUPPORTED_STRING_FORMATS.has(format);
|
|
144
|
+
}
|
|
145
|
+
function getChecks(def) {
|
|
146
|
+
return [...def.check === void 0 ? [] : [{ _zod: { def } }], ...def.checks ?? []];
|
|
147
|
+
}
|
|
148
|
+
function collectUnsupportedSchemaWarning(schemaType, collector, path) {
|
|
149
|
+
if (SUPPORTED_SCHEMA_TYPES.has(schemaType)) return;
|
|
150
|
+
collector.warnings.push(createWarning({
|
|
151
|
+
code: "unsupported-schema",
|
|
152
|
+
schemaType,
|
|
153
|
+
path,
|
|
154
|
+
message: `Zod ${schemaType} falls back to a broader JSON Schema representation.`
|
|
155
|
+
}));
|
|
156
|
+
}
|
|
157
|
+
function collectNestedWarnings(def, schemaType, collector, path) {
|
|
158
|
+
switch (schemaType) {
|
|
159
|
+
case "object":
|
|
160
|
+
collectObjectWarnings(def, collector, path);
|
|
161
|
+
return;
|
|
162
|
+
case "array":
|
|
163
|
+
collectChild(def.element, collector, [...path, "items"]);
|
|
164
|
+
return;
|
|
165
|
+
case "union":
|
|
166
|
+
collectOptionWarnings(def.options, collector, path, "anyOf");
|
|
167
|
+
return;
|
|
168
|
+
case "intersection":
|
|
169
|
+
collectChild(def.left, collector, [
|
|
170
|
+
...path,
|
|
171
|
+
"allOf",
|
|
172
|
+
"0"
|
|
173
|
+
]);
|
|
174
|
+
collectChild(def.right, collector, [
|
|
175
|
+
...path,
|
|
176
|
+
"allOf",
|
|
177
|
+
"1"
|
|
178
|
+
]);
|
|
179
|
+
return;
|
|
180
|
+
case "tuple":
|
|
181
|
+
collectTupleWarnings(def, collector, path);
|
|
182
|
+
return;
|
|
183
|
+
case "record":
|
|
184
|
+
collectChild(def.keyType, collector, [...path, "propertyNames"]);
|
|
185
|
+
collectChild(def.valueType, collector, [...path, "additionalProperties"]);
|
|
186
|
+
return;
|
|
187
|
+
case "lazy":
|
|
188
|
+
collectLazyWarnings(def, collector, path);
|
|
189
|
+
return;
|
|
190
|
+
case "pipe":
|
|
191
|
+
collectChild(def.in, collector, [
|
|
192
|
+
...path,
|
|
193
|
+
"x-typeweaver",
|
|
194
|
+
"pipeIn"
|
|
195
|
+
]);
|
|
196
|
+
collectChild(def.out, collector, [
|
|
197
|
+
...path,
|
|
198
|
+
"x-typeweaver",
|
|
199
|
+
"pipeOut"
|
|
200
|
+
]);
|
|
201
|
+
return;
|
|
202
|
+
case "map":
|
|
203
|
+
collectChild(def.keyType, collector, [
|
|
204
|
+
...path,
|
|
205
|
+
"x-typeweaver",
|
|
206
|
+
"mapKey"
|
|
207
|
+
]);
|
|
208
|
+
collectChild(def.valueType, collector, [
|
|
209
|
+
...path,
|
|
210
|
+
"x-typeweaver",
|
|
211
|
+
"mapValue"
|
|
212
|
+
]);
|
|
213
|
+
return;
|
|
214
|
+
case "set":
|
|
215
|
+
collectChild(def.valueType, collector, [...path, "items"]);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (isZodTransparentWrapperType(schemaType)) collectChild(def.innerType, collector, path);
|
|
219
|
+
}
|
|
220
|
+
function collectObjectWarnings(def, collector, path) {
|
|
221
|
+
for (const [key, value] of Object.entries(def.shape ?? {})) collectChild(value, collector, [
|
|
222
|
+
...path,
|
|
223
|
+
"properties",
|
|
224
|
+
key
|
|
225
|
+
]);
|
|
226
|
+
collectChild(def.catchall, collector, [...path, "additionalProperties"]);
|
|
227
|
+
}
|
|
228
|
+
function collectOptionWarnings(options, collector, path, keyword) {
|
|
229
|
+
for (const [index, option] of (options ?? []).entries()) collectChild(option, collector, [
|
|
230
|
+
...path,
|
|
231
|
+
keyword,
|
|
232
|
+
String(index)
|
|
233
|
+
]);
|
|
234
|
+
}
|
|
235
|
+
function collectTupleWarnings(def, collector, path) {
|
|
236
|
+
for (const [index, item] of (def.items ?? []).entries()) collectChild(item, collector, [
|
|
237
|
+
...path,
|
|
238
|
+
"prefixItems",
|
|
239
|
+
String(index)
|
|
240
|
+
]);
|
|
241
|
+
collectChild(def.rest, collector, [...path, "items"]);
|
|
242
|
+
}
|
|
243
|
+
function collectLazyWarnings(def, collector, path) {
|
|
244
|
+
try {
|
|
245
|
+
collectChild(def.getter?.(), collector, path);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
collector.warnings.push(createWarning({
|
|
248
|
+
code: "conversion-error",
|
|
249
|
+
schemaType: "lazy",
|
|
250
|
+
path,
|
|
251
|
+
message: error instanceof Error ? error.message : "Failed to convert schema to JSON Schema."
|
|
252
|
+
}));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
function collectChild(value, collector, path) {
|
|
256
|
+
if (isZodSchema(value)) collectWarnings(value, collector, path);
|
|
257
|
+
}
|
|
258
|
+
function formatPath(path) {
|
|
259
|
+
if (path.length === 0) return "";
|
|
260
|
+
return `/${path.map(encodeJsonPointerSegment).join("/")}`;
|
|
261
|
+
}
|
|
262
|
+
function encodeJsonPointerSegment(segment) {
|
|
263
|
+
return segment.replaceAll("~", "~0").replaceAll("/", "~1");
|
|
264
|
+
}
|
|
265
|
+
//#endregion
|
|
266
|
+
//#region src/internal/normalizeJsonSchema.ts
|
|
267
|
+
const SCHEMA_CHILD_KEYS = new Set([
|
|
268
|
+
"items",
|
|
269
|
+
"contains",
|
|
270
|
+
"propertyNames",
|
|
271
|
+
"if",
|
|
272
|
+
"then",
|
|
273
|
+
"else",
|
|
274
|
+
"not"
|
|
275
|
+
]);
|
|
276
|
+
const OBJECT_SCHEMA_CHILD_KEYS = new Set(["additionalProperties"]);
|
|
277
|
+
const SCHEMA_CHILD_MAP_KEYS = new Set([
|
|
278
|
+
"properties",
|
|
279
|
+
"patternProperties",
|
|
280
|
+
"$defs",
|
|
281
|
+
"definitions"
|
|
282
|
+
]);
|
|
283
|
+
const SCHEMA_CHILD_ARRAY_KEYS = new Set([
|
|
284
|
+
"prefixItems",
|
|
285
|
+
"allOf",
|
|
286
|
+
"anyOf",
|
|
287
|
+
"oneOf"
|
|
288
|
+
]);
|
|
289
|
+
function normalizeJsonSchema(schema) {
|
|
290
|
+
const normalizedSchema = Object.fromEntries(Object.entries(schema).map(([key, value]) => [key, normalizeSchemaKeyword(schema, key, value)]));
|
|
291
|
+
if (!isTupleSchema(normalizedSchema)) return normalizedSchema;
|
|
292
|
+
return normalizeTupleSchema(normalizedSchema);
|
|
293
|
+
}
|
|
294
|
+
function normalizeTupleSchema(schema) {
|
|
295
|
+
const itemCount = schema.prefixItems.length;
|
|
296
|
+
const minItems = schema.minItems ?? itemCount;
|
|
297
|
+
if (hasOwnSchemaKeyword(schema, "items")) return {
|
|
298
|
+
...schema,
|
|
299
|
+
minItems
|
|
300
|
+
};
|
|
301
|
+
return {
|
|
302
|
+
...schema,
|
|
303
|
+
items: schema.items ?? {},
|
|
304
|
+
minItems,
|
|
305
|
+
maxItems: schema.maxItems ?? itemCount
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
function normalizeSchemaKeyword(parent, key, value) {
|
|
309
|
+
if (SCHEMA_CHILD_KEYS.has(key) && isJsonSchema(value)) return normalizeJsonSchema(value);
|
|
310
|
+
if (OBJECT_SCHEMA_CHILD_KEYS.has(key) && parent.type === "object" && isJsonSchema(value)) return normalizeJsonSchema(value);
|
|
311
|
+
if (SCHEMA_CHILD_MAP_KEYS.has(key) && isJsonSchema(value)) return Object.fromEntries(Object.entries(value).map(([childKey, childValue]) => [childKey, isJsonSchema(childValue) ? normalizeJsonSchema(childValue) : childValue]));
|
|
312
|
+
if (SCHEMA_CHILD_ARRAY_KEYS.has(key) && Array.isArray(value)) return value.map((entry) => isJsonSchema(entry) ? normalizeJsonSchema(entry) : entry);
|
|
313
|
+
return value;
|
|
314
|
+
}
|
|
315
|
+
function isTupleSchema(schema) {
|
|
316
|
+
return schema.type === "array" && Array.isArray(schema.prefixItems);
|
|
317
|
+
}
|
|
318
|
+
function isJsonSchema(value) {
|
|
319
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
320
|
+
}
|
|
321
|
+
function hasOwnSchemaKeyword(schema, keyword) {
|
|
322
|
+
return Object.prototype.hasOwnProperty.call(schema, keyword);
|
|
323
|
+
}
|
|
324
|
+
//#endregion
|
|
325
|
+
//#region src/zodToJsonSchema.ts
|
|
326
|
+
function fromZod(schema) {
|
|
327
|
+
const warnings = [...collectZodWarnings(schema)];
|
|
328
|
+
try {
|
|
329
|
+
return {
|
|
330
|
+
schema: normalizeJsonSchema(stripRootSchemaDialect(z.toJSONSchema(schema, {
|
|
331
|
+
target: "draft-2020-12",
|
|
332
|
+
unrepresentable: "any"
|
|
333
|
+
}))),
|
|
334
|
+
warnings
|
|
335
|
+
};
|
|
336
|
+
} catch (error) {
|
|
337
|
+
if (!warnings.some(isRootConversionWarning)) warnings.push(createWarning({
|
|
338
|
+
code: "conversion-error",
|
|
339
|
+
schemaType: getSchemaType(schema),
|
|
340
|
+
path: [],
|
|
341
|
+
message: error instanceof Error ? error.message : "Failed to convert schema to JSON Schema."
|
|
342
|
+
}));
|
|
343
|
+
return {
|
|
344
|
+
schema: {},
|
|
345
|
+
warnings
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
function isRootConversionWarning(warning) {
|
|
350
|
+
return warning.code === "conversion-error" && warning.path === "";
|
|
351
|
+
}
|
|
352
|
+
function stripRootSchemaDialect(schema) {
|
|
353
|
+
return Object.fromEntries(Object.entries(schema).filter(([key]) => key !== "$schema"));
|
|
354
|
+
}
|
|
355
|
+
//#endregion
|
|
356
|
+
export { fromZod };
|
|
357
|
+
|
|
358
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/internal/zodIntrospection.ts","../src/internal/collectZodWarnings.ts","../src/internal/normalizeJsonSchema.ts","../src/zodToJsonSchema.ts"],"sourcesContent":["import type { z } from \"zod\";\n\nexport type ZodSchema = z.core.$ZodType;\n\nexport type ZodDef = {\n readonly type?: string;\n readonly check?: string;\n readonly format?: string;\n readonly checks?: readonly ZodCheck[];\n readonly shape?: Readonly<Record<string, ZodSchema>>;\n readonly catchall?: ZodSchema;\n readonly innerType?: ZodSchema;\n readonly element?: ZodSchema;\n readonly options?: readonly ZodSchema[];\n readonly left?: ZodSchema;\n readonly right?: ZodSchema;\n readonly items?: readonly ZodSchema[];\n readonly rest?: ZodSchema | null;\n readonly keyType?: ZodSchema;\n readonly valueType?: ZodSchema;\n readonly schema?: ZodSchema;\n readonly in?: ZodSchema;\n readonly out?: ZodSchema;\n readonly getter?: () => ZodSchema;\n};\n\nexport type ZodTransparentWrapperType =\n | \"optional\"\n | \"nullable\"\n | \"default\"\n | \"catch\"\n | \"prefault\"\n | \"readonly\"\n | \"nonoptional\";\n\nexport type ZodCheck = {\n readonly _zod?: {\n readonly def?: {\n readonly type?: string;\n readonly check?: string;\n readonly format?: string;\n };\n };\n};\n\nconst TRANSPARENT_WRAPPER_TYPES: ReadonlySet<string> = new Set([\n \"optional\",\n \"nullable\",\n \"default\",\n \"catch\",\n \"prefault\",\n \"readonly\",\n \"nonoptional\",\n]);\n\nexport function getSchemaDefinition(\n schema: ZodSchema | undefined\n): ZodDef | undefined {\n if (schema === undefined) {\n return undefined;\n }\n\n const schemaWithDefinition = schema as ZodSchema & {\n readonly def?: ZodDef;\n readonly _def?: ZodDef;\n };\n\n return (\n (schemaWithDefinition._zod?.def as ZodDef | undefined) ??\n schemaWithDefinition.def ??\n schemaWithDefinition._def\n );\n}\n\nexport function getZodDef(schema: ZodSchema): ZodDef | undefined {\n return getSchemaDefinition(schema);\n}\n\nexport function getSchemaType(schema: ZodSchema): string;\nexport function getSchemaType(\n schema: ZodSchema | undefined\n): string | undefined;\nexport function getSchemaType(\n schema: ZodSchema | undefined\n): string | undefined {\n if (schema === undefined) {\n return undefined;\n }\n\n return getSchemaDefinition(schema)?.type ?? \"unknown\";\n}\n\nexport function isZodTransparentWrapperType(\n schemaType: string | undefined,\n transparentWrapperTypes: ReadonlySet<string> = TRANSPARENT_WRAPPER_TYPES\n): schemaType is ZodTransparentWrapperType {\n return schemaType !== undefined && transparentWrapperTypes.has(schemaType);\n}\n\nexport function isZodSchema(value: unknown): value is ZodSchema {\n if (typeof value !== \"object\" || value === null || !(\"_zod\" in value)) {\n return false;\n }\n\n const zodMetadata = (value as { readonly _zod?: unknown })._zod;\n\n return (\n typeof zodMetadata === \"object\" &&\n zodMetadata !== null &&\n \"def\" in zodMetadata &&\n typeof (zodMetadata as { readonly def?: unknown }).def === \"object\" &&\n (zodMetadata as { readonly def?: unknown }).def !== null\n );\n}\n","import {\n getSchemaType,\n getZodDef,\n isZodSchema,\n isZodTransparentWrapperType,\n} from \"./zodIntrospection.js\";\nimport type {\n ZodToJsonSchemaWarning,\n ZodToJsonSchemaWarningCode,\n} from \"../types.js\";\nimport type { ZodDef, ZodSchema, ZodCheck } from \"./zodIntrospection.js\";\n\ntype WarningCollector = {\n readonly warnings: ZodToJsonSchemaWarning[];\n readonly seen: WeakSet<ZodSchema>;\n};\n\ntype WarningInput = {\n readonly code: ZodToJsonSchemaWarningCode;\n readonly schemaType: string;\n readonly path: readonly string[];\n readonly message: string;\n};\n\nconst SUPPORTED_SCHEMA_TYPES: ReadonlySet<string> = new Set([\n \"any\",\n \"array\",\n \"boolean\",\n \"catch\",\n \"default\",\n \"enum\",\n \"intersection\",\n \"lazy\",\n \"literal\",\n \"null\",\n \"nullable\",\n \"number\",\n \"object\",\n \"optional\",\n \"prefault\",\n \"record\",\n \"string\",\n \"tuple\",\n \"union\",\n \"unknown\",\n]);\n\nconst SUPPORTED_CHECKS: ReadonlySet<string> = new Set([\n \"greater_than\",\n \"length_equals\",\n \"less_than\",\n \"max_length\",\n \"max_size\",\n \"mime_type\",\n \"min_length\",\n \"min_size\",\n \"multiple_of\",\n \"number_format\",\n \"overwrite\",\n \"property\",\n \"regex\",\n \"size_equals\",\n \"string_format\",\n]);\n\nconst SUPPORTED_STRING_FORMATS: ReadonlySet<string> = new Set([\n \"base64\",\n \"base64url\",\n \"cuid\",\n \"cuid2\",\n \"date\",\n \"datetime\",\n \"duration\",\n \"e164\",\n \"email\",\n \"emoji\",\n \"ends_with\",\n \"guid\",\n \"includes\",\n \"ipv4\",\n \"ipv6\",\n \"jwt\",\n \"lowercase\",\n \"nanoid\",\n \"regex\",\n \"starts_with\",\n \"time\",\n \"ulid\",\n \"uppercase\",\n \"url\",\n \"uuid\",\n]);\n\nexport function collectZodWarnings(\n schema: ZodSchema\n): readonly ZodToJsonSchemaWarning[] {\n const collector: WarningCollector = {\n warnings: [],\n seen: new WeakSet(),\n };\n\n collectWarnings(schema, collector, []);\n\n return collector.warnings;\n}\n\nexport function createWarning(input: WarningInput): ZodToJsonSchemaWarning {\n return {\n code: input.code,\n schemaType: input.schemaType,\n path: formatPath(input.path),\n message: input.message,\n };\n}\n\nfunction collectWarnings(\n schema: ZodSchema,\n collector: WarningCollector,\n path: readonly string[]\n): void {\n if (!isZodSchema(schema) || collector.seen.has(schema)) {\n return;\n }\n\n collector.seen.add(schema);\n\n const def = getZodDef(schema);\n const schemaType = getSchemaType(schema);\n\n if (def === undefined) {\n return;\n }\n\n collectCheckWarnings(def, collector, path, schemaType);\n collectUnsupportedSchemaWarning(schemaType, collector, path);\n collectNestedWarnings(def, schemaType, collector, path);\n}\n\nfunction collectCheckWarnings(\n def: ZodDef,\n collector: WarningCollector,\n path: readonly string[],\n schemaType: string\n): void {\n if (schemaType === \"custom\" || schemaType === \"transform\") {\n return;\n }\n\n for (const check of getChecks(def)) {\n const checkDef = check._zod?.def;\n const checkType = checkDef?.check ?? checkDef?.type ?? \"unknown\";\n const format = checkDef?.format;\n\n if (isSupportedCheck(checkType, format)) {\n continue;\n }\n\n collector.warnings.push(\n createWarning({\n code: \"unsupported-check\",\n schemaType,\n path,\n message: `Zod ${schemaType} check ${checkType} cannot be represented exactly in JSON Schema.`,\n })\n );\n }\n}\n\nfunction isSupportedCheck(\n checkType: string,\n format: string | undefined\n): boolean {\n if (!SUPPORTED_CHECKS.has(checkType)) {\n return false;\n }\n\n return (\n checkType !== \"string_format\" ||\n format === undefined ||\n SUPPORTED_STRING_FORMATS.has(format)\n );\n}\n\nfunction getChecks(def: ZodDef): readonly ZodCheck[] {\n const ownCheck = def.check === undefined ? [] : [{ _zod: { def } }];\n\n return [...ownCheck, ...(def.checks ?? [])];\n}\n\nfunction collectUnsupportedSchemaWarning(\n schemaType: string,\n collector: WarningCollector,\n path: readonly string[]\n): void {\n if (SUPPORTED_SCHEMA_TYPES.has(schemaType)) {\n return;\n }\n\n collector.warnings.push(\n createWarning({\n code: \"unsupported-schema\",\n schemaType,\n path,\n message: `Zod ${schemaType} falls back to a broader JSON Schema representation.`,\n })\n );\n}\n\nfunction collectNestedWarnings(\n def: ZodDef,\n schemaType: string,\n collector: WarningCollector,\n path: readonly string[]\n): void {\n switch (schemaType) {\n case \"object\":\n collectObjectWarnings(def, collector, path);\n return;\n case \"array\":\n collectChild(def.element, collector, [...path, \"items\"]);\n return;\n case \"union\":\n collectOptionWarnings(def.options, collector, path, \"anyOf\");\n return;\n case \"intersection\":\n collectChild(def.left, collector, [...path, \"allOf\", \"0\"]);\n collectChild(def.right, collector, [...path, \"allOf\", \"1\"]);\n return;\n case \"tuple\":\n collectTupleWarnings(def, collector, path);\n return;\n case \"record\":\n collectChild(def.keyType, collector, [...path, \"propertyNames\"]);\n collectChild(def.valueType, collector, [...path, \"additionalProperties\"]);\n return;\n case \"lazy\":\n collectLazyWarnings(def, collector, path);\n return;\n case \"pipe\":\n collectChild(def.in, collector, [...path, \"x-typeweaver\", \"pipeIn\"]);\n collectChild(def.out, collector, [...path, \"x-typeweaver\", \"pipeOut\"]);\n return;\n case \"map\":\n collectChild(def.keyType, collector, [...path, \"x-typeweaver\", \"mapKey\"]);\n collectChild(def.valueType, collector, [\n ...path,\n \"x-typeweaver\",\n \"mapValue\",\n ]);\n return;\n case \"set\":\n collectChild(def.valueType, collector, [...path, \"items\"]);\n return;\n }\n\n if (isZodTransparentWrapperType(schemaType)) {\n collectChild(def.innerType, collector, path);\n }\n}\n\nfunction collectObjectWarnings(\n def: ZodDef,\n collector: WarningCollector,\n path: readonly string[]\n): void {\n for (const [key, value] of Object.entries(def.shape ?? {})) {\n collectChild(value, collector, [...path, \"properties\", key]);\n }\n\n collectChild(def.catchall, collector, [...path, \"additionalProperties\"]);\n}\n\nfunction collectOptionWarnings(\n options: readonly ZodSchema[] | undefined,\n collector: WarningCollector,\n path: readonly string[],\n keyword: string\n): void {\n for (const [index, option] of (options ?? []).entries()) {\n collectChild(option, collector, [...path, keyword, String(index)]);\n }\n}\n\nfunction collectTupleWarnings(\n def: ZodDef,\n collector: WarningCollector,\n path: readonly string[]\n): void {\n for (const [index, item] of (def.items ?? []).entries()) {\n collectChild(item, collector, [...path, \"prefixItems\", String(index)]);\n }\n\n collectChild(def.rest, collector, [...path, \"items\"]);\n}\n\nfunction collectLazyWarnings(\n def: ZodDef,\n collector: WarningCollector,\n path: readonly string[]\n): void {\n try {\n collectChild(def.getter?.(), collector, path);\n } catch (error) {\n collector.warnings.push(\n createWarning({\n code: \"conversion-error\",\n schemaType: \"lazy\",\n path,\n message:\n error instanceof Error\n ? error.message\n : \"Failed to convert schema to JSON Schema.\",\n })\n );\n }\n}\n\nfunction collectChild(\n value: unknown,\n collector: WarningCollector,\n path: readonly string[]\n): void {\n if (isZodSchema(value)) {\n collectWarnings(value, collector, path);\n }\n}\n\nfunction formatPath(path: readonly string[]): string {\n if (path.length === 0) {\n return \"\";\n }\n\n return `/${path.map(encodeJsonPointerSegment).join(\"/\")}`;\n}\n\nfunction encodeJsonPointerSegment(segment: string): string {\n return segment.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n}\n","import type { JsonSchema, JsonSchemaValue } from \"../types.js\";\n\nconst SCHEMA_CHILD_KEYS: ReadonlySet<string> = new Set([\n \"items\",\n \"contains\",\n \"propertyNames\",\n \"if\",\n \"then\",\n \"else\",\n \"not\",\n]);\n\nconst OBJECT_SCHEMA_CHILD_KEYS: ReadonlySet<string> = new Set([\n \"additionalProperties\",\n]);\n\nconst SCHEMA_CHILD_MAP_KEYS: ReadonlySet<string> = new Set([\n \"properties\",\n \"patternProperties\",\n \"$defs\",\n \"definitions\",\n]);\n\nconst SCHEMA_CHILD_ARRAY_KEYS: ReadonlySet<string> = new Set([\n \"prefixItems\",\n \"allOf\",\n \"anyOf\",\n \"oneOf\",\n]);\n\nexport function normalizeJsonSchema(schema: JsonSchema): JsonSchema {\n const normalizedSchema = Object.fromEntries(\n Object.entries(schema).map(([key, value]) => [\n key,\n normalizeSchemaKeyword(schema, key, value),\n ])\n ) as JsonSchema;\n\n if (!isTupleSchema(normalizedSchema)) {\n return normalizedSchema;\n }\n\n return normalizeTupleSchema(normalizedSchema);\n}\n\nfunction normalizeTupleSchema(\n schema: JsonSchema & { readonly prefixItems: readonly JsonSchemaValue[] }\n): JsonSchema {\n const itemCount = schema.prefixItems.length;\n const minItems = schema.minItems ?? itemCount;\n\n if (hasOwnSchemaKeyword(schema, \"items\")) {\n return { ...schema, minItems };\n }\n\n return {\n ...schema,\n items: schema.items ?? {},\n minItems,\n maxItems: schema.maxItems ?? itemCount,\n };\n}\n\nfunction normalizeSchemaKeyword(\n parent: JsonSchema,\n key: string,\n value: JsonSchemaValue\n): JsonSchemaValue {\n if (SCHEMA_CHILD_KEYS.has(key) && isJsonSchema(value)) {\n return normalizeJsonSchema(value);\n }\n\n if (\n OBJECT_SCHEMA_CHILD_KEYS.has(key) &&\n parent.type === \"object\" &&\n isJsonSchema(value)\n ) {\n return normalizeJsonSchema(value);\n }\n\n if (SCHEMA_CHILD_MAP_KEYS.has(key) && isJsonSchema(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([childKey, childValue]) => [\n childKey,\n isJsonSchema(childValue) ? normalizeJsonSchema(childValue) : childValue,\n ])\n );\n }\n\n if (SCHEMA_CHILD_ARRAY_KEYS.has(key) && Array.isArray(value)) {\n return value.map(entry =>\n isJsonSchema(entry) ? normalizeJsonSchema(entry) : entry\n );\n }\n\n return value;\n}\n\nfunction isTupleSchema(\n schema: JsonSchema\n): schema is JsonSchema & { readonly prefixItems: readonly JsonSchemaValue[] } {\n return schema.type === \"array\" && Array.isArray(schema.prefixItems);\n}\n\nfunction isJsonSchema(value: JsonSchemaValue): value is JsonSchema {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction hasOwnSchemaKeyword(schema: JsonSchema, keyword: string): boolean {\n return Object.prototype.hasOwnProperty.call(schema, keyword);\n}\n","import { z } from \"zod\";\nimport {\n collectZodWarnings,\n createWarning,\n} from \"./internal/collectZodWarnings.js\";\nimport { normalizeJsonSchema } from \"./internal/normalizeJsonSchema.js\";\nimport { getSchemaType } from \"./internal/zodIntrospection.js\";\nimport type {\n JsonSchema,\n ZodToJsonSchemaResult,\n ZodToJsonSchemaWarning,\n} from \"./types.js\";\n\nexport function fromZod(schema: z.core.$ZodType): ZodToJsonSchemaResult {\n const warnings = [...collectZodWarnings(schema)];\n\n try {\n const converted = z.toJSONSchema(schema as unknown as z.ZodType, {\n target: \"draft-2020-12\",\n unrepresentable: \"any\",\n }) as JsonSchema;\n\n return {\n schema: normalizeJsonSchema(stripRootSchemaDialect(converted)),\n warnings,\n };\n } catch (error) {\n if (!warnings.some(isRootConversionWarning)) {\n warnings.push(\n createWarning({\n code: \"conversion-error\",\n schemaType: getSchemaType(schema),\n path: [],\n message:\n error instanceof Error\n ? error.message\n : \"Failed to convert schema to JSON Schema.\",\n })\n );\n }\n\n return {\n schema: {},\n warnings,\n };\n }\n}\n\nfunction isRootConversionWarning(warning: ZodToJsonSchemaWarning): boolean {\n return warning.code === \"conversion-error\" && warning.path === \"\";\n}\n\nfunction stripRootSchemaDialect(schema: JsonSchema): JsonSchema {\n return Object.fromEntries(\n Object.entries(schema).filter(([key]) => key !== \"$schema\")\n ) as JsonSchema;\n}\n"],"mappings":";;AA6CA,MAAM,4BAAiD,IAAI,IAAI;CAC7D;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAgB,oBACd,QACoB;AACpB,KAAI,WAAW,KAAA,EACb;CAGF,MAAM,uBAAuB;AAK7B,QACG,qBAAqB,MAAM,OAC5B,qBAAqB,OACrB,qBAAqB;;AAIzB,SAAgB,UAAU,QAAuC;AAC/D,QAAO,oBAAoB,OAAO;;AAOpC,SAAgB,cACd,QACoB;AACpB,KAAI,WAAW,KAAA,EACb;AAGF,QAAO,oBAAoB,OAAO,EAAE,QAAQ;;AAG9C,SAAgB,4BACd,YACA,0BAA+C,2BACN;AACzC,QAAO,eAAe,KAAA,KAAa,wBAAwB,IAAI,WAAW;;AAG5E,SAAgB,YAAY,OAAoC;AAC9D,KAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,EAAE,UAAU,OAC7D,QAAO;CAGT,MAAM,cAAe,MAAsC;AAE3D,QACE,OAAO,gBAAgB,YACvB,gBAAgB,QAChB,SAAS,eACT,OAAQ,YAA2C,QAAQ,YAC1D,YAA2C,QAAQ;;;;ACvFxD,MAAM,yBAA8C,IAAI,IAAI;CAC1D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAM,mBAAwC,IAAI,IAAI;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAM,2BAAgD,IAAI,IAAI;CAC5D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA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,QAAO,MAAM,KAAI,UACf,aAAa,MAAM,GAAG,oBAAoB,MAAM,GAAG,MACpD;AAGH,QAAO;;AAGT,SAAS,cACP,QAC6E;AAC7E,QAAO,OAAO,SAAS,WAAW,MAAM,QAAQ,OAAO,YAAY;;AAGrE,SAAS,aAAa,OAA6C;AACjE,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;AAG7E,SAAS,oBAAoB,QAAoB,SAA0B;AACzE,QAAO,OAAO,UAAU,eAAe,KAAK,QAAQ,QAAQ;;;;AChG9D,SAAgB,QAAQ,QAAgD;CACtE,MAAM,WAAW,CAAC,GAAG,mBAAmB,OAAO,CAAC;AAEhD,KAAI;AAMF,SAAO;GACL,QAAQ,oBAAoB,uBANZ,EAAE,aAAa,QAAgC;IAC/D,QAAQ;IACR,iBAAiB;IAClB,CAAC,CAG6D,CAAC;GAC9D;GACD;UACM,OAAO;AACd,MAAI,CAAC,SAAS,KAAK,wBAAwB,CACzC,UAAS,KACP,cAAc;GACZ,MAAM;GACN,YAAY,cAAc,OAAO;GACjC,MAAM,EAAE;GACR,SACE,iBAAiB,QACb,MAAM,UACN;GACP,CAAC,CACH;AAGH,SAAO;GACL,QAAQ,EAAE;GACV;GACD;;;AAIL,SAAS,wBAAwB,SAA0C;AACzE,QAAO,QAAQ,SAAS,sBAAsB,QAAQ,SAAS;;AAGjE,SAAS,uBAAuB,QAAgC;AAC9D,QAAO,OAAO,YACZ,OAAO,QAAQ,OAAO,CAAC,QAAQ,CAAC,SAAS,QAAQ,UAAU,CAC5D"}
|
package/package.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rexeus/typeweaver-zod-to-json-schema",
|
|
3
|
+
"version": "0.11.0",
|
|
4
|
+
"description": "Converts Zod v4 schemas to JSON Schema Draft 2020-12. Powered by Typeweaver 🧵✨",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"main": "dist/index.cjs",
|
|
8
|
+
"module": "dist/index.mjs",
|
|
9
|
+
"types": "dist/index.d.mts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"import": {
|
|
13
|
+
"types": "./dist/index.d.mts",
|
|
14
|
+
"default": "./dist/index.mjs"
|
|
15
|
+
},
|
|
16
|
+
"require": {
|
|
17
|
+
"types": "./dist/index.d.cts",
|
|
18
|
+
"default": "./dist/index.cjs"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"package.json",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE",
|
|
27
|
+
"NOTICE"
|
|
28
|
+
],
|
|
29
|
+
"scripts": {
|
|
30
|
+
"typecheck": "tsc --noEmit -p tsconfig.typecheck.json",
|
|
31
|
+
"format": "oxfmt",
|
|
32
|
+
"build": "tsdown && cp ../../LICENSE ../../NOTICE ./dist/",
|
|
33
|
+
"test": "vitest --run",
|
|
34
|
+
"prepack": "npm run build",
|
|
35
|
+
"preversion": "npm run build"
|
|
36
|
+
},
|
|
37
|
+
"keywords": [
|
|
38
|
+
"zod",
|
|
39
|
+
"json-schema",
|
|
40
|
+
"openapi",
|
|
41
|
+
"conversion",
|
|
42
|
+
"generator",
|
|
43
|
+
"typeweaver"
|
|
44
|
+
],
|
|
45
|
+
"author": "Dennis Wentzien <dw@rexeus.com>",
|
|
46
|
+
"license": "Apache-2.0",
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/rexeus/typeweaver.git",
|
|
50
|
+
"directory": "packages/zod-to-json-schema"
|
|
51
|
+
},
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/rexeus/typeweaver/issues"
|
|
54
|
+
},
|
|
55
|
+
"homepage": "https://github.com/rexeus/typeweaver#readme",
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"zod": "^4.3.0"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"zod": "^4.3.6"
|
|
61
|
+
}
|
|
62
|
+
}
|