@gabrielbryk/json-schema-to-zod 2.7.4 → 2.9.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/CHANGELOG.md +23 -1
- package/dist/cjs/core/analyzeSchema.js +62 -0
- package/dist/cjs/core/emitZod.js +141 -0
- package/dist/cjs/generators/generateBundle.js +355 -0
- package/dist/cjs/index.js +6 -0
- package/dist/cjs/jsonSchemaToZod.js +5 -73
- package/dist/cjs/parsers/parseArray.js +34 -15
- package/dist/cjs/parsers/parseIfThenElse.js +2 -1
- package/dist/cjs/parsers/parseNumber.js +81 -39
- package/dist/cjs/parsers/parseObject.js +24 -0
- package/dist/cjs/parsers/parseSchema.js +147 -25
- package/dist/cjs/parsers/parseString.js +294 -54
- package/dist/cjs/utils/buildRefRegistry.js +56 -0
- package/dist/cjs/utils/cycles.js +113 -0
- package/dist/cjs/utils/resolveUri.js +16 -0
- package/dist/cjs/utils/withMessage.js +4 -5
- package/dist/esm/core/analyzeSchema.js +58 -0
- package/dist/esm/core/emitZod.js +137 -0
- package/dist/esm/generators/generateBundle.js +351 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/jsonSchemaToZod.js +5 -73
- package/dist/esm/parsers/parseArray.js +34 -15
- package/dist/esm/parsers/parseIfThenElse.js +2 -1
- package/dist/esm/parsers/parseNumber.js +81 -39
- package/dist/esm/parsers/parseObject.js +24 -0
- package/dist/esm/parsers/parseSchema.js +147 -25
- package/dist/esm/parsers/parseString.js +294 -54
- package/dist/esm/utils/buildRefRegistry.js +52 -0
- package/dist/esm/utils/cycles.js +107 -0
- package/dist/esm/utils/resolveUri.js +12 -0
- package/dist/esm/utils/withMessage.js +4 -5
- package/dist/types/Types.d.ts +36 -0
- package/dist/types/core/analyzeSchema.d.ts +24 -0
- package/dist/types/core/emitZod.d.ts +2 -0
- package/dist/types/generators/generateBundle.d.ts +62 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/jsonSchemaToZod.d.ts +1 -1
- package/dist/types/parsers/parseSchema.d.ts +2 -1
- package/dist/types/parsers/parseString.d.ts +2 -2
- package/dist/types/utils/buildRefRegistry.d.ts +12 -0
- package/dist/types/utils/cycles.d.ts +7 -0
- package/dist/types/utils/jsdocs.d.ts +1 -1
- package/dist/types/utils/resolveUri.d.ts +1 -0
- package/dist/types/utils/withMessage.d.ts +6 -1
- package/docs/proposals/bundle-refactor.md +43 -0
- package/docs/proposals/ref-anchor-support.md +65 -0
- package/eslint.config.js +26 -0
- package/package.json +10 -4
- /package/{jest.config.js → jest.config.cjs} +0 -0
- /package/{postcjs.js → postcjs.cjs} +0 -0
- /package/{postesm.js → postesm.cjs} +0 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { parseSchema } from "../parsers/parseSchema.js";
|
|
2
|
+
import { expandJsdocs } from "../utils/jsdocs.js";
|
|
3
|
+
const orderDeclarations = (entries, dependencies) => {
|
|
4
|
+
const valueByName = new Map(entries);
|
|
5
|
+
const depGraph = new Map();
|
|
6
|
+
for (const [from, set] of dependencies.entries()) {
|
|
7
|
+
const onlyKnown = new Set();
|
|
8
|
+
for (const dep of set) {
|
|
9
|
+
if (valueByName.has(dep) && dep !== from) {
|
|
10
|
+
onlyKnown.add(dep);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
if (onlyKnown.size)
|
|
14
|
+
depGraph.set(from, onlyKnown);
|
|
15
|
+
}
|
|
16
|
+
const names = Array.from(valueByName.keys());
|
|
17
|
+
for (const [name, value] of entries) {
|
|
18
|
+
const deps = depGraph.get(name) ?? new Set();
|
|
19
|
+
for (const candidate of names) {
|
|
20
|
+
if (candidate === name)
|
|
21
|
+
continue;
|
|
22
|
+
const matcher = new RegExp(`\\b${candidate}\\b`);
|
|
23
|
+
if (matcher.test(value)) {
|
|
24
|
+
deps.add(candidate);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (deps.size)
|
|
28
|
+
depGraph.set(name, deps);
|
|
29
|
+
}
|
|
30
|
+
const ordered = [];
|
|
31
|
+
const perm = new Set();
|
|
32
|
+
const temp = new Set();
|
|
33
|
+
const visit = (name) => {
|
|
34
|
+
if (perm.has(name))
|
|
35
|
+
return;
|
|
36
|
+
if (temp.has(name)) {
|
|
37
|
+
temp.delete(name);
|
|
38
|
+
perm.add(name);
|
|
39
|
+
ordered.push(name);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
temp.add(name);
|
|
43
|
+
const deps = depGraph.get(name);
|
|
44
|
+
if (deps) {
|
|
45
|
+
for (const dep of deps) {
|
|
46
|
+
if (valueByName.has(dep)) {
|
|
47
|
+
visit(dep);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
temp.delete(name);
|
|
52
|
+
perm.add(name);
|
|
53
|
+
ordered.push(name);
|
|
54
|
+
};
|
|
55
|
+
for (const name of valueByName.keys()) {
|
|
56
|
+
visit(name);
|
|
57
|
+
}
|
|
58
|
+
const unique = [];
|
|
59
|
+
const seen = new Set();
|
|
60
|
+
for (const name of ordered) {
|
|
61
|
+
if (!seen.has(name)) {
|
|
62
|
+
seen.add(name);
|
|
63
|
+
unique.push(name);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return unique.map((name) => [name, valueByName.get(name)]);
|
|
67
|
+
};
|
|
68
|
+
export const emitZod = (analysis) => {
|
|
69
|
+
const { schema, options, refNameByPointer, usedNames, cycleRefNames, cycleComponentByName, } = analysis;
|
|
70
|
+
const { module, name, type, noImport, exportRefs, withMeta, ...rest } = options;
|
|
71
|
+
const declarations = new Map();
|
|
72
|
+
const dependencies = new Map();
|
|
73
|
+
const parsedSchema = parseSchema(schema, {
|
|
74
|
+
module,
|
|
75
|
+
name,
|
|
76
|
+
path: [],
|
|
77
|
+
seen: new Map(),
|
|
78
|
+
declarations,
|
|
79
|
+
dependencies,
|
|
80
|
+
inProgress: new Set(),
|
|
81
|
+
refNameByPointer,
|
|
82
|
+
usedNames,
|
|
83
|
+
root: schema,
|
|
84
|
+
currentSchemaName: name,
|
|
85
|
+
cycleRefNames,
|
|
86
|
+
cycleComponentByName,
|
|
87
|
+
refRegistry: analysis.refRegistry,
|
|
88
|
+
rootBaseUri: analysis.rootBaseUri,
|
|
89
|
+
...rest,
|
|
90
|
+
withMeta,
|
|
91
|
+
});
|
|
92
|
+
const declarationBlock = declarations.size
|
|
93
|
+
? orderDeclarations(Array.from(declarations.entries()), dependencies)
|
|
94
|
+
.map(([refName, value]) => {
|
|
95
|
+
const shouldExport = exportRefs && module === "esm";
|
|
96
|
+
const decl = `${shouldExport ? "export " : ""}const ${refName} = ${value}`;
|
|
97
|
+
return decl;
|
|
98
|
+
})
|
|
99
|
+
.join("\n")
|
|
100
|
+
: "";
|
|
101
|
+
const jsdocs = rest.withJsdocs && typeof schema !== "boolean" && schema.description
|
|
102
|
+
? expandJsdocs(schema.description)
|
|
103
|
+
: "";
|
|
104
|
+
const lines = [];
|
|
105
|
+
if (module === "cjs" && !noImport) {
|
|
106
|
+
lines.push(`const { z } = require("zod")`);
|
|
107
|
+
}
|
|
108
|
+
if (module === "esm" && !noImport) {
|
|
109
|
+
lines.push(`import { z } from "zod"`);
|
|
110
|
+
}
|
|
111
|
+
if (declarationBlock) {
|
|
112
|
+
lines.push(declarationBlock);
|
|
113
|
+
}
|
|
114
|
+
if (module === "cjs") {
|
|
115
|
+
const payload = name ? `{ ${JSON.stringify(name)}: ${parsedSchema} }` : parsedSchema;
|
|
116
|
+
lines.push(`${jsdocs}module.exports = ${payload}`);
|
|
117
|
+
}
|
|
118
|
+
else if (module === "esm") {
|
|
119
|
+
const exportLine = `${jsdocs}export ${name ? `const ${name} =` : `default`} ${parsedSchema}`;
|
|
120
|
+
lines.push(exportLine);
|
|
121
|
+
}
|
|
122
|
+
else if (name) {
|
|
123
|
+
lines.push(`${jsdocs}const ${name} = ${parsedSchema}`);
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
lines.push(`${jsdocs}${parsedSchema}`);
|
|
127
|
+
}
|
|
128
|
+
let typeLine;
|
|
129
|
+
if (type && name) {
|
|
130
|
+
const typeName = typeof type === "string" ? type : `${name[0].toUpperCase()}${name.substring(1)}`;
|
|
131
|
+
typeLine = `export type ${typeName} = z.infer<typeof ${name}>`;
|
|
132
|
+
}
|
|
133
|
+
const joined = lines.filter(Boolean).join("\n\n");
|
|
134
|
+
const combined = typeLine ? `${joined}\n${typeLine}` : joined;
|
|
135
|
+
const shouldEndWithNewline = module === "esm" || module === "cjs";
|
|
136
|
+
return `${combined}${shouldEndWithNewline ? "\n" : ""}`;
|
|
137
|
+
};
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
import { analyzeSchema } from "../core/analyzeSchema.js";
|
|
2
|
+
import { emitZod } from "../core/emitZod.js";
|
|
3
|
+
export const generateSchemaBundle = (schema, options = {}) => {
|
|
4
|
+
const module = options.module ?? "esm";
|
|
5
|
+
if (!schema || typeof schema !== "object") {
|
|
6
|
+
throw new Error("generateSchemaBundle requires an object schema");
|
|
7
|
+
}
|
|
8
|
+
const defs = schema.$defs || {};
|
|
9
|
+
const definitions = schema.definitions || {};
|
|
10
|
+
const defNames = Object.keys(defs);
|
|
11
|
+
const { rootName, rootTypeName, defInfoMap } = buildBundleContext(defNames, defs, options);
|
|
12
|
+
const files = [];
|
|
13
|
+
const targets = planBundleTargets(schema, defs, definitions, defNames, options, rootName, rootTypeName);
|
|
14
|
+
for (const target of targets) {
|
|
15
|
+
const usedRefs = target.usedRefs;
|
|
16
|
+
const analysis = analyzeSchema(target.schemaWithDefs, {
|
|
17
|
+
...options,
|
|
18
|
+
module,
|
|
19
|
+
name: target.schemaName,
|
|
20
|
+
type: target.typeName,
|
|
21
|
+
parserOverride: createRefHandler(target.defName, defInfoMap, usedRefs, {
|
|
22
|
+
...(target.schemaWithDefs.$defs || {}),
|
|
23
|
+
...(target.schemaWithDefs.definitions || {}),
|
|
24
|
+
}, options),
|
|
25
|
+
});
|
|
26
|
+
const zodSchema = emitZod(analysis);
|
|
27
|
+
const finalSchema = buildSchemaFile(zodSchema, usedRefs, defInfoMap, module);
|
|
28
|
+
files.push({ fileName: target.fileName, contents: finalSchema });
|
|
29
|
+
}
|
|
30
|
+
// Nested types extraction (optional)
|
|
31
|
+
const nestedTypesEnabled = options.nestedTypes?.enable;
|
|
32
|
+
if (nestedTypesEnabled) {
|
|
33
|
+
const nestedTypes = collectNestedTypes(schema, defs, defNames, rootTypeName ?? rootName);
|
|
34
|
+
if (nestedTypes.length > 0) {
|
|
35
|
+
const nestedFileName = options.nestedTypes?.fileName ?? "nested-types.ts";
|
|
36
|
+
const nestedContent = generateNestedTypesFile(nestedTypes);
|
|
37
|
+
files.push({ fileName: nestedFileName, contents: nestedContent });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return { files, defNames };
|
|
41
|
+
};
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
// Internals
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
const toPascalCase = (str) => str
|
|
46
|
+
.split(/[-_]/)
|
|
47
|
+
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
|
48
|
+
.join("");
|
|
49
|
+
const buildDefInfoMap = (defNames, defs, options) => {
|
|
50
|
+
const map = new Map();
|
|
51
|
+
for (const defName of defNames) {
|
|
52
|
+
const dependencies = findRefDependencies(defs[defName], defNames);
|
|
53
|
+
const pascalName = toPascalCase(defName);
|
|
54
|
+
const schemaName = options.splitDefs?.schemaName?.(defName, { isRoot: false }) ?? `${pascalName}Schema`;
|
|
55
|
+
const typeName = options.splitDefs?.typeName?.(defName, { isRoot: false }) ?? pascalName;
|
|
56
|
+
map.set(defName, {
|
|
57
|
+
name: defName,
|
|
58
|
+
pascalName,
|
|
59
|
+
schemaName,
|
|
60
|
+
typeName,
|
|
61
|
+
dependencies,
|
|
62
|
+
hasCycle: false,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
return map;
|
|
66
|
+
};
|
|
67
|
+
const buildBundleContext = (defNames, defs, options) => {
|
|
68
|
+
const defInfoMap = buildDefInfoMap(defNames, defs, options);
|
|
69
|
+
const cycles = detectCycles(defInfoMap);
|
|
70
|
+
for (const defName of cycles) {
|
|
71
|
+
const info = defInfoMap.get(defName);
|
|
72
|
+
if (info)
|
|
73
|
+
info.hasCycle = true;
|
|
74
|
+
}
|
|
75
|
+
const rootName = options.splitDefs?.rootName ?? options.name ?? "RootSchema";
|
|
76
|
+
const rootTypeName = typeof options.type === "string"
|
|
77
|
+
? options.type
|
|
78
|
+
: options.splitDefs?.rootTypeName ?? (typeof options.type === "boolean" && options.type ? rootName : undefined);
|
|
79
|
+
return { defInfoMap, rootName, rootTypeName };
|
|
80
|
+
};
|
|
81
|
+
const createRefHandler = (currentDefName, defInfoMap, usedRefs, allDefs, options) => {
|
|
82
|
+
return (schema, refs) => {
|
|
83
|
+
if (typeof schema["$ref"] === "string") {
|
|
84
|
+
const refPath = schema["$ref"];
|
|
85
|
+
const match = refPath.match(/^#\/(?:\$defs|definitions)\/(.+)$/);
|
|
86
|
+
if (match) {
|
|
87
|
+
const refName = match[1];
|
|
88
|
+
// Only intercept top-level def refs (no nested path like a/$defs/x)
|
|
89
|
+
if (refName.includes("/")) {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
const refInfo = defInfoMap.get(refName);
|
|
93
|
+
if (refInfo) {
|
|
94
|
+
// Track imports when referencing other defs
|
|
95
|
+
if (refName !== currentDefName) {
|
|
96
|
+
usedRefs.add(refName);
|
|
97
|
+
}
|
|
98
|
+
const isCycle = refName === currentDefName || (refInfo.hasCycle && !!currentDefName);
|
|
99
|
+
const resolved = options.refResolution?.onRef?.({
|
|
100
|
+
ref: refPath,
|
|
101
|
+
refName,
|
|
102
|
+
currentDef: currentDefName,
|
|
103
|
+
path: refs.path,
|
|
104
|
+
isCycle,
|
|
105
|
+
});
|
|
106
|
+
if (resolved)
|
|
107
|
+
return resolved;
|
|
108
|
+
if (isCycle && options.refResolution?.lazyCrossRefs) {
|
|
109
|
+
return `z.lazy(() => ${refInfo.schemaName})`;
|
|
110
|
+
}
|
|
111
|
+
return refInfo.schemaName;
|
|
112
|
+
}
|
|
113
|
+
// If the ref points to a local/inline $def (not part of top-level defs),
|
|
114
|
+
// let the default parser resolve it normally.
|
|
115
|
+
if (allDefs && Object.prototype.hasOwnProperty.call(allDefs, refName)) {
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const unknown = options.refResolution?.onUnknownRef?.({ ref: refPath, currentDef: currentDefName });
|
|
120
|
+
if (unknown)
|
|
121
|
+
return unknown;
|
|
122
|
+
return options.useUnknown ? "z.unknown()" : "z.any()";
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
};
|
|
126
|
+
};
|
|
127
|
+
const buildSchemaFile = (zodCode, usedRefs, defInfoMap, module) => {
|
|
128
|
+
if (module !== "esm")
|
|
129
|
+
return zodCode;
|
|
130
|
+
const imports = [];
|
|
131
|
+
for (const refName of [...usedRefs].sort()) {
|
|
132
|
+
const refInfo = defInfoMap.get(refName);
|
|
133
|
+
if (refInfo) {
|
|
134
|
+
imports.push(`import { ${refInfo.schemaName} } from './${refName}.schema.js';`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (!imports.length)
|
|
138
|
+
return zodCode;
|
|
139
|
+
return zodCode.replace('import { z } from "zod"', `import { z } from "zod"\n${imports.join("\n")}`);
|
|
140
|
+
};
|
|
141
|
+
const planBundleTargets = (rootSchema, defs, definitions, defNames, options, rootName, rootTypeName) => {
|
|
142
|
+
const targets = [];
|
|
143
|
+
for (const defName of defNames) {
|
|
144
|
+
const defSchema = defs[defName];
|
|
145
|
+
const defSchemaWithDefs = {
|
|
146
|
+
...defSchema,
|
|
147
|
+
$defs: { ...defs, ...defSchema?.$defs },
|
|
148
|
+
definitions: {
|
|
149
|
+
...defSchema.definitions,
|
|
150
|
+
...definitions,
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
const pascalName = toPascalCase(defName);
|
|
154
|
+
const schemaName = options.splitDefs?.schemaName?.(defName, { isRoot: false }) ?? `${pascalName}Schema`;
|
|
155
|
+
const typeName = options.splitDefs?.typeName?.(defName, { isRoot: false }) ?? pascalName;
|
|
156
|
+
const fileName = options.splitDefs?.fileName?.(defName, { isRoot: false }) ?? `${defName}.schema.ts`;
|
|
157
|
+
targets.push({
|
|
158
|
+
defName,
|
|
159
|
+
schemaWithDefs: defSchemaWithDefs,
|
|
160
|
+
schemaName,
|
|
161
|
+
typeName,
|
|
162
|
+
fileName,
|
|
163
|
+
usedRefs: new Set(),
|
|
164
|
+
isRoot: false,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
if (options.splitDefs?.includeRoot ?? true) {
|
|
168
|
+
const rootFile = options.splitDefs?.fileName?.("root", { isRoot: true }) ?? "workflow.schema.ts";
|
|
169
|
+
targets.push({
|
|
170
|
+
defName: null,
|
|
171
|
+
schemaWithDefs: {
|
|
172
|
+
...rootSchema,
|
|
173
|
+
definitions: {
|
|
174
|
+
...rootSchema.definitions,
|
|
175
|
+
...definitions,
|
|
176
|
+
},
|
|
177
|
+
},
|
|
178
|
+
schemaName: rootName,
|
|
179
|
+
typeName: rootTypeName,
|
|
180
|
+
fileName: rootFile,
|
|
181
|
+
usedRefs: new Set(),
|
|
182
|
+
isRoot: true,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return targets;
|
|
186
|
+
};
|
|
187
|
+
const findRefDependencies = (schema, validDefNames) => {
|
|
188
|
+
const deps = new Set();
|
|
189
|
+
function traverse(obj) {
|
|
190
|
+
if (obj === null || typeof obj !== "object")
|
|
191
|
+
return;
|
|
192
|
+
if (Array.isArray(obj)) {
|
|
193
|
+
obj.forEach(traverse);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const record = obj;
|
|
197
|
+
if (typeof record["$ref"] === "string") {
|
|
198
|
+
const ref = record["$ref"];
|
|
199
|
+
const match = ref.match(/^#\/(?:\$defs|definitions)\/(.+)$/);
|
|
200
|
+
if (match && validDefNames.includes(match[1])) {
|
|
201
|
+
deps.add(match[1]);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
for (const value of Object.values(record)) {
|
|
205
|
+
traverse(value);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
traverse(schema);
|
|
209
|
+
return deps;
|
|
210
|
+
};
|
|
211
|
+
const detectCycles = (defInfoMap) => {
|
|
212
|
+
const cycleNodes = new Set();
|
|
213
|
+
const visited = new Set();
|
|
214
|
+
const recursionStack = new Set();
|
|
215
|
+
function dfs(node, path) {
|
|
216
|
+
if (recursionStack.has(node)) {
|
|
217
|
+
const cycleStart = path.indexOf(node);
|
|
218
|
+
for (let i = cycleStart; i < path.length; i++) {
|
|
219
|
+
cycleNodes.add(path[i]);
|
|
220
|
+
}
|
|
221
|
+
cycleNodes.add(node);
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
if (visited.has(node))
|
|
225
|
+
return false;
|
|
226
|
+
visited.add(node);
|
|
227
|
+
recursionStack.add(node);
|
|
228
|
+
const info = defInfoMap.get(node);
|
|
229
|
+
if (info) {
|
|
230
|
+
for (const dep of info.dependencies) {
|
|
231
|
+
dfs(dep, [...path, node]);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
recursionStack.delete(node);
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
for (const defName of defInfoMap.keys()) {
|
|
238
|
+
if (!visited.has(defName)) {
|
|
239
|
+
dfs(defName, []);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return cycleNodes;
|
|
243
|
+
};
|
|
244
|
+
const collectNestedTypes = (rootSchema, defs, defNames, rootTypeName) => {
|
|
245
|
+
const allNestedTypes = [];
|
|
246
|
+
for (const defName of defNames) {
|
|
247
|
+
const defSchema = defs[defName];
|
|
248
|
+
const parentTypeName = toPascalCase(defName);
|
|
249
|
+
const nestedTypes = findNestedTypesInSchema(defSchema, parentTypeName, defNames);
|
|
250
|
+
for (const nested of nestedTypes) {
|
|
251
|
+
nested.file = defName;
|
|
252
|
+
nested.parentType = parentTypeName;
|
|
253
|
+
allNestedTypes.push(nested);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const workflowNestedTypes = findNestedTypesInSchema({ properties: rootSchema.properties, required: rootSchema.required }, rootTypeName, defNames);
|
|
257
|
+
for (const nested of workflowNestedTypes) {
|
|
258
|
+
nested.file = "workflow";
|
|
259
|
+
nested.parentType = rootTypeName;
|
|
260
|
+
allNestedTypes.push(nested);
|
|
261
|
+
}
|
|
262
|
+
const uniqueNestedTypes = new Map();
|
|
263
|
+
for (const nested of allNestedTypes) {
|
|
264
|
+
if (!uniqueNestedTypes.has(nested.typeName) && nested.propertyPath.length > 0) {
|
|
265
|
+
uniqueNestedTypes.set(nested.typeName, nested);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return [...uniqueNestedTypes.values()];
|
|
269
|
+
};
|
|
270
|
+
const findNestedTypesInSchema = (schema, parentTypeName, defNames, currentPath = []) => {
|
|
271
|
+
const nestedTypes = [];
|
|
272
|
+
if (schema === null || typeof schema !== "object")
|
|
273
|
+
return nestedTypes;
|
|
274
|
+
const record = schema;
|
|
275
|
+
if (record.title && typeof record.title === "string") {
|
|
276
|
+
const title = record.title;
|
|
277
|
+
if (title !== parentTypeName && !defNames.map((d) => toPascalCase(d)).includes(title)) {
|
|
278
|
+
nestedTypes.push({
|
|
279
|
+
typeName: title,
|
|
280
|
+
parentType: parentTypeName,
|
|
281
|
+
propertyPath: [...currentPath],
|
|
282
|
+
file: "",
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
// inline $defs
|
|
287
|
+
if (record.$defs && typeof record.$defs === "object") {
|
|
288
|
+
for (const [_defName, defSchema] of Object.entries(record.$defs)) {
|
|
289
|
+
nestedTypes.push(...findNestedTypesInSchema(defSchema, parentTypeName, defNames, currentPath));
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (record.properties && typeof record.properties === "object") {
|
|
293
|
+
for (const [propName, propSchema] of Object.entries(record.properties)) {
|
|
294
|
+
nestedTypes.push(...findNestedTypesInSchema(propSchema, parentTypeName, defNames, [...currentPath, propName]));
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
if (Array.isArray(record.allOf)) {
|
|
298
|
+
for (const item of record.allOf) {
|
|
299
|
+
nestedTypes.push(...findNestedTypesInSchema(item, parentTypeName, defNames, currentPath));
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (record.items) {
|
|
303
|
+
nestedTypes.push(...findNestedTypesInSchema(record.items, parentTypeName, defNames, [...currentPath, "items"]));
|
|
304
|
+
}
|
|
305
|
+
if (record.additionalProperties && typeof record.additionalProperties === "object") {
|
|
306
|
+
nestedTypes.push(...findNestedTypesInSchema(record.additionalProperties, parentTypeName, defNames, [...currentPath, "additionalProperties"]));
|
|
307
|
+
}
|
|
308
|
+
return nestedTypes;
|
|
309
|
+
};
|
|
310
|
+
const generateNestedTypesFile = (nestedTypes) => {
|
|
311
|
+
const lines = [
|
|
312
|
+
"/**",
|
|
313
|
+
" * Auto-generated nested type exports",
|
|
314
|
+
" * ",
|
|
315
|
+
" * These types are inline within parent schemas but commonly needed separately.",
|
|
316
|
+
" * They are extracted using TypeScript indexed access types.",
|
|
317
|
+
" */",
|
|
318
|
+
"",
|
|
319
|
+
];
|
|
320
|
+
const byParent = new Map();
|
|
321
|
+
for (const info of nestedTypes) {
|
|
322
|
+
if (!byParent.has(info.parentType)) {
|
|
323
|
+
byParent.set(info.parentType, []);
|
|
324
|
+
}
|
|
325
|
+
byParent.get(info.parentType).push(info);
|
|
326
|
+
}
|
|
327
|
+
const imports = new Map(); // file -> type name
|
|
328
|
+
for (const info of nestedTypes) {
|
|
329
|
+
if (!imports.has(info.file)) {
|
|
330
|
+
imports.set(info.file, info.parentType);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
for (const [file, typeName] of [...imports.entries()].sort()) {
|
|
334
|
+
lines.push(`import type { ${typeName} } from './${file}.schema.js';`);
|
|
335
|
+
}
|
|
336
|
+
lines.push("");
|
|
337
|
+
for (const [parentType, types] of [...byParent.entries()].sort()) {
|
|
338
|
+
lines.push(`// From ${parentType}`);
|
|
339
|
+
for (const info of types.sort((a, b) => a.typeName.localeCompare(b.typeName))) {
|
|
340
|
+
if (info.propertyPath.length > 0) {
|
|
341
|
+
let accessExpr = parentType;
|
|
342
|
+
for (const prop of info.propertyPath) {
|
|
343
|
+
accessExpr = `NonNullable<${accessExpr}['${prop}']>`;
|
|
344
|
+
}
|
|
345
|
+
lines.push(`export type ${info.typeName} = ${accessExpr};`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
lines.push("");
|
|
349
|
+
}
|
|
350
|
+
return lines.join("\n");
|
|
351
|
+
};
|
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
export * from "./Types.js";
|
|
2
|
+
export * from "./core/analyzeSchema.js";
|
|
3
|
+
export * from "./core/emitZod.js";
|
|
4
|
+
export * from "./generators/generateBundle.js";
|
|
2
5
|
export * from "./jsonSchemaToZod.js";
|
|
3
6
|
export * from "./parsers/parseAllOf.js";
|
|
4
7
|
export * from "./parsers/parseAnyOf.js";
|
|
@@ -19,9 +22,12 @@ export * from "./parsers/parseSchema.js";
|
|
|
19
22
|
export * from "./parsers/parseSimpleDiscriminatedOneOf.js";
|
|
20
23
|
export * from "./parsers/parseString.js";
|
|
21
24
|
export * from "./utils/anyOrUnknown.js";
|
|
25
|
+
export * from "./utils/buildRefRegistry.js";
|
|
26
|
+
export * from "./utils/cycles.js";
|
|
22
27
|
export * from "./utils/half.js";
|
|
23
28
|
export * from "./utils/jsdocs.js";
|
|
24
29
|
export * from "./utils/omit.js";
|
|
30
|
+
export * from "./utils/resolveUri.js";
|
|
25
31
|
export * from "./utils/withMessage.js";
|
|
26
32
|
export * from "./zodToJsonSchema.js";
|
|
27
33
|
import { jsonSchemaToZod } from "./jsonSchemaToZod.js";
|
|
@@ -1,74 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
export const jsonSchemaToZod = (schema,
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
}
|
|
7
|
-
const declarations = new Map();
|
|
8
|
-
const refNameByPointer = new Map();
|
|
9
|
-
const usedNames = new Set();
|
|
10
|
-
const exportRefs = rest.exportRefs ?? true;
|
|
11
|
-
const withMeta = rest.withMeta ?? true;
|
|
12
|
-
if (name)
|
|
13
|
-
usedNames.add(name);
|
|
14
|
-
const parsedSchema = parseSchema(schema, {
|
|
15
|
-
module,
|
|
16
|
-
name,
|
|
17
|
-
path: [],
|
|
18
|
-
seen: new Map(),
|
|
19
|
-
declarations,
|
|
20
|
-
inProgress: new Set(),
|
|
21
|
-
refNameByPointer,
|
|
22
|
-
usedNames,
|
|
23
|
-
root: schema,
|
|
24
|
-
currentSchemaName: name,
|
|
25
|
-
...rest,
|
|
26
|
-
withMeta,
|
|
27
|
-
});
|
|
28
|
-
const declarationBlock = declarations.size
|
|
29
|
-
? Array.from(declarations.entries())
|
|
30
|
-
.map(([refName, value]) => {
|
|
31
|
-
const shouldExport = exportRefs && module === "esm";
|
|
32
|
-
const decl = `${shouldExport ? "export " : ""}const ${refName} = ${value}`;
|
|
33
|
-
return decl;
|
|
34
|
-
})
|
|
35
|
-
.join("\n")
|
|
36
|
-
: "";
|
|
37
|
-
const jsdocs = rest.withJsdocs && typeof schema !== "boolean" && schema.description
|
|
38
|
-
? expandJsdocs(schema.description)
|
|
39
|
-
: "";
|
|
40
|
-
const lines = [];
|
|
41
|
-
if (module === "cjs" && !noImport) {
|
|
42
|
-
lines.push(`const { z } = require("zod")`);
|
|
43
|
-
}
|
|
44
|
-
if (module === "esm" && !noImport) {
|
|
45
|
-
lines.push(`import { z } from "zod"`);
|
|
46
|
-
}
|
|
47
|
-
if (declarationBlock) {
|
|
48
|
-
lines.push(declarationBlock);
|
|
49
|
-
}
|
|
50
|
-
if (module === "cjs") {
|
|
51
|
-
const payload = name ? `{ ${JSON.stringify(name)}: ${parsedSchema} }` : parsedSchema;
|
|
52
|
-
lines.push(`${jsdocs}module.exports = ${payload}`);
|
|
53
|
-
}
|
|
54
|
-
else if (module === "esm") {
|
|
55
|
-
lines.push(`${jsdocs}export ${name ? `const ${name} =` : `default`} ${parsedSchema}`);
|
|
56
|
-
}
|
|
57
|
-
else if (name) {
|
|
58
|
-
lines.push(`${jsdocs}const ${name} = ${parsedSchema}`);
|
|
59
|
-
}
|
|
60
|
-
else {
|
|
61
|
-
lines.push(`${jsdocs}${parsedSchema}`);
|
|
62
|
-
}
|
|
63
|
-
let typeLine;
|
|
64
|
-
if (type && name) {
|
|
65
|
-
let typeName = typeof type === "string"
|
|
66
|
-
? type
|
|
67
|
-
: `${name[0].toUpperCase()}${name.substring(1)}`;
|
|
68
|
-
typeLine = `export type ${typeName} = z.infer<typeof ${name}>`;
|
|
69
|
-
}
|
|
70
|
-
const joined = lines.filter(Boolean).join("\n\n");
|
|
71
|
-
const combined = typeLine ? `${joined}\n${typeLine}` : joined;
|
|
72
|
-
const shouldEndWithNewline = module === "esm" || module === "cjs";
|
|
73
|
-
return `${combined}${shouldEndWithNewline ? "\n" : ""}`;
|
|
1
|
+
import { analyzeSchema } from "./core/analyzeSchema.js";
|
|
2
|
+
import { emitZod } from "./core/emitZod.js";
|
|
3
|
+
export const jsonSchemaToZod = (schema, options = {}) => {
|
|
4
|
+
const analysis = analyzeSchema(schema, options);
|
|
5
|
+
return emitZod(analysis);
|
|
74
6
|
};
|
|
@@ -29,22 +29,41 @@ export const parseArray = (schema, refs) => {
|
|
|
29
29
|
...refs,
|
|
30
30
|
path: [...refs.path, "items"],
|
|
31
31
|
})})`;
|
|
32
|
-
r += withMessage(schema, "minItems", ({ json }) =>
|
|
33
|
-
`.min(${json}`,
|
|
34
|
-
|
|
35
|
-
"
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
")",
|
|
41
|
-
|
|
32
|
+
r += withMessage(schema, "minItems", ({ json }) => ({
|
|
33
|
+
opener: `.min(${json}`,
|
|
34
|
+
closer: ")",
|
|
35
|
+
messagePrefix: ", { error: ",
|
|
36
|
+
messageCloser: " })",
|
|
37
|
+
}));
|
|
38
|
+
r += withMessage(schema, "maxItems", ({ json }) => ({
|
|
39
|
+
opener: `.max(${json}`,
|
|
40
|
+
closer: ")",
|
|
41
|
+
messagePrefix: ", { error: ",
|
|
42
|
+
messageCloser: " })",
|
|
43
|
+
}));
|
|
42
44
|
if (schema.uniqueItems === true) {
|
|
43
|
-
r +=
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
45
|
+
r += `.superRefine((arr, ctx) => {
|
|
46
|
+
const seen = new Set();
|
|
47
|
+
for (const [index, value] of arr.entries()) {
|
|
48
|
+
let key;
|
|
49
|
+
if (value && typeof value === "object") {
|
|
50
|
+
try {
|
|
51
|
+
key = JSON.stringify(value);
|
|
52
|
+
} catch {
|
|
53
|
+
key = String(value);
|
|
54
|
+
}
|
|
55
|
+
} else {
|
|
56
|
+
key = JSON.stringify(value);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (seen.has(key)) {
|
|
60
|
+
ctx.addIssue({ code: "custom", message: "Array items must be unique", path: [index] });
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
seen.add(key);
|
|
65
|
+
}
|
|
66
|
+
})`;
|
|
48
67
|
}
|
|
49
68
|
if (schema.contains) {
|
|
50
69
|
const containsSchema = parseSchema(schema.contains, {
|
|
@@ -14,7 +14,8 @@ export const parseIfThenElse = (schema, refs) => {
|
|
|
14
14
|
? ${$then}.safeParse(value)
|
|
15
15
|
: ${$else}.safeParse(value);
|
|
16
16
|
if (!result.success) {
|
|
17
|
-
result.error.
|
|
17
|
+
const issues = result.error.issues ?? result.error.errors ?? [];
|
|
18
|
+
issues.forEach((issue) => ctx.addIssue(issue))
|
|
18
19
|
}
|
|
19
20
|
})`;
|
|
20
21
|
// Store original if/then/else for JSON Schema round-trip
|