@composio/json-schema-to-zod 0.3.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +344 -69
- package/package.json +8 -2
package/dist/index.d.mts
CHANGED
package/dist/index.mjs
CHANGED
|
@@ -1,11 +1,34 @@
|
|
|
1
1
|
import * as z$1 from "zod/v3";
|
|
2
2
|
import { z } from "zod/v3";
|
|
3
|
+
import { dequal } from "dequal/lite";
|
|
4
|
+
import { Validator, encodePointer } from "@cfworker/json-schema";
|
|
3
5
|
|
|
4
6
|
//#region src/utils/half.ts
|
|
5
7
|
const half = (arr) => {
|
|
6
8
|
return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
|
|
7
9
|
};
|
|
8
10
|
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/utils/its.ts
|
|
13
|
+
const its = {
|
|
14
|
+
an: {
|
|
15
|
+
object: (x) => x.type === "object" || !x.type && (x.properties !== void 0 || x.additionalProperties !== void 0 || x.patternProperties !== void 0),
|
|
16
|
+
array: (x) => x.type === "array",
|
|
17
|
+
anyOf: (x) => x.anyOf !== void 0,
|
|
18
|
+
allOf: (x) => x.allOf !== void 0,
|
|
19
|
+
enum: (x) => x.enum !== void 0
|
|
20
|
+
},
|
|
21
|
+
a: {
|
|
22
|
+
nullable: (x) => x.nullable === true,
|
|
23
|
+
multipleType: (x) => Array.isArray(x.type),
|
|
24
|
+
not: (x) => x.not !== void 0,
|
|
25
|
+
const: (x) => x.const !== void 0,
|
|
26
|
+
primitive: (x, p) => x.type === p,
|
|
27
|
+
conditional: (x) => Boolean("if" in x && x.if && "then" in x && "else" in x && x.then && x.else),
|
|
28
|
+
oneOf: (x) => x.oneOf !== void 0
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
9
32
|
//#endregion
|
|
10
33
|
//#region src/parsers/parse-all-of.ts
|
|
11
34
|
const originalIndex = Symbol("Original index");
|
|
@@ -25,10 +48,10 @@ const ensureOriginalIndex = (arr) => {
|
|
|
25
48
|
}
|
|
26
49
|
return newArr;
|
|
27
50
|
};
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
if (
|
|
31
|
-
const item =
|
|
51
|
+
const isClosedObjectBranch = (branch) => typeof branch === "object" && its.an.object(branch) && branch.properties !== void 0 && Object.keys(branch.properties).length > 0 && branch.additionalProperties === void 0 && branch.patternProperties === void 0 && !("$ref" in branch);
|
|
52
|
+
const intersect = (branches, refs) => {
|
|
53
|
+
if (branches.length === 1) {
|
|
54
|
+
const item = branches[0];
|
|
32
55
|
return parseSchema(item, {
|
|
33
56
|
...refs,
|
|
34
57
|
path: [
|
|
@@ -38,8 +61,28 @@ function parseAllOf(jsonSchema, refs) {
|
|
|
38
61
|
]
|
|
39
62
|
});
|
|
40
63
|
}
|
|
41
|
-
const [left, right] = half(
|
|
42
|
-
return z.intersection(
|
|
64
|
+
const [left, right] = half(branches);
|
|
65
|
+
return z.intersection(intersect(left, refs), intersect(right, refs));
|
|
66
|
+
};
|
|
67
|
+
function parseAllOf(jsonSchema, refs) {
|
|
68
|
+
if (jsonSchema.allOf.length === 0) return z.never();
|
|
69
|
+
if (jsonSchema.allOf.length === 1) return intersect(ensureOriginalIndex(jsonSchema.allOf), refs);
|
|
70
|
+
const opened = jsonSchema.allOf.map((branch) => isClosedObjectBranch(branch) ? {
|
|
71
|
+
...branch,
|
|
72
|
+
additionalProperties: true
|
|
73
|
+
} : branch);
|
|
74
|
+
const parsed = intersect(ensureOriginalIndex(opened), refs);
|
|
75
|
+
if (!jsonSchema.allOf.every(isClosedObjectBranch)) return parsed;
|
|
76
|
+
const declaredKeys = new Set(jsonSchema.allOf.flatMap((branch) => Object.keys(branch.properties ?? {})));
|
|
77
|
+
return parsed.superRefine((value, ctx) => {
|
|
78
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return;
|
|
79
|
+
const unrecognizedKeys = Object.keys(value).filter((key) => !declaredKeys.has(key));
|
|
80
|
+
if (unrecognizedKeys.length > 0) ctx.addIssue({
|
|
81
|
+
code: z.ZodIssueCode.unrecognized_keys,
|
|
82
|
+
keys: unrecognizedKeys,
|
|
83
|
+
message: `Unrecognized key(s) in object: ${unrecognizedKeys.map((key) => `'${key}'`).join(", ")}`
|
|
84
|
+
});
|
|
85
|
+
});
|
|
43
86
|
}
|
|
44
87
|
|
|
45
88
|
//#endregion
|
|
@@ -73,27 +116,6 @@ function extendSchemaWithMessage(zodSchema, jsonSchema, key, extend) {
|
|
|
73
116
|
return zodSchema;
|
|
74
117
|
}
|
|
75
118
|
|
|
76
|
-
//#endregion
|
|
77
|
-
//#region src/utils/its.ts
|
|
78
|
-
const its = {
|
|
79
|
-
an: {
|
|
80
|
-
object: (x) => x.type === "object" || !x.type && (x.properties !== void 0 || x.additionalProperties !== void 0 || x.patternProperties !== void 0),
|
|
81
|
-
array: (x) => x.type === "array",
|
|
82
|
-
anyOf: (x) => x.anyOf !== void 0,
|
|
83
|
-
allOf: (x) => x.allOf !== void 0,
|
|
84
|
-
enum: (x) => x.enum !== void 0
|
|
85
|
-
},
|
|
86
|
-
a: {
|
|
87
|
-
nullable: (x) => x.nullable === true,
|
|
88
|
-
multipleType: (x) => Array.isArray(x.type),
|
|
89
|
-
not: (x) => x.not !== void 0,
|
|
90
|
-
const: (x) => x.const !== void 0,
|
|
91
|
-
primitive: (x, p) => x.type === p,
|
|
92
|
-
conditional: (x) => Boolean("if" in x && x.if && "then" in x && "else" in x && x.then && x.else),
|
|
93
|
-
oneOf: (x) => x.oneOf !== void 0
|
|
94
|
-
}
|
|
95
|
-
};
|
|
96
|
-
|
|
97
119
|
//#endregion
|
|
98
120
|
//#region src/parsers/parse-array.ts
|
|
99
121
|
const parseArray = (jsonSchema, refs) => {
|
|
@@ -125,14 +147,30 @@ const parseArray = (jsonSchema, refs) => {
|
|
|
125
147
|
});
|
|
126
148
|
return parseSchema(newSchema, refs);
|
|
127
149
|
}
|
|
128
|
-
if (Array.isArray(jsonSchema.items))
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
150
|
+
if (Array.isArray(jsonSchema.items)) {
|
|
151
|
+
const parsedItems = jsonSchema.items.map((item, index) => parseSchema(item, {
|
|
152
|
+
...refs,
|
|
153
|
+
path: [
|
|
154
|
+
...refs.path,
|
|
155
|
+
"items",
|
|
156
|
+
index
|
|
157
|
+
]
|
|
158
|
+
}));
|
|
159
|
+
const prefixSchemas = parsedItems.map((_, length) => z.tuple(parsedItems.slice(0, length)));
|
|
160
|
+
const fullTuple = z.tuple(parsedItems);
|
|
161
|
+
let fullLengthSchema;
|
|
162
|
+
if (jsonSchema.additionalItems === false) fullLengthSchema = fullTuple;
|
|
163
|
+
else if (jsonSchema.additionalItems && jsonSchema.additionalItems !== true) fullLengthSchema = fullTuple.rest(parseSchema(jsonSchema.additionalItems, {
|
|
164
|
+
...refs,
|
|
165
|
+
path: [...refs.path, "additionalItems"]
|
|
166
|
+
}));
|
|
167
|
+
else fullLengthSchema = fullTuple.rest(z.any());
|
|
168
|
+
const variants = [...prefixSchemas, fullLengthSchema];
|
|
169
|
+
let tupleSchema = variants.length === 1 ? variants[0] : z.union(variants);
|
|
170
|
+
if (typeof jsonSchema.minItems === "number") tupleSchema = tupleSchema.refine((value) => value.length >= jsonSchema.minItems, { message: `Array must contain at least ${jsonSchema.minItems} element(s)` });
|
|
171
|
+
if (typeof jsonSchema.maxItems === "number") tupleSchema = tupleSchema.refine((value) => value.length <= jsonSchema.maxItems, { message: `Array must contain at most ${jsonSchema.maxItems} element(s)` });
|
|
172
|
+
return tupleSchema;
|
|
173
|
+
}
|
|
136
174
|
let zodSchema = !jsonSchema.items ? z.array(z.any()) : z.array(parseSchema(jsonSchema.items, {
|
|
137
175
|
...refs,
|
|
138
176
|
path: [...refs.path, "items"]
|
|
@@ -156,10 +194,26 @@ const parseBoolean = (_jsonSchema) => {
|
|
|
156
194
|
return z.boolean();
|
|
157
195
|
};
|
|
158
196
|
|
|
197
|
+
//#endregion
|
|
198
|
+
//#region src/parsers/parse-literal-values.ts
|
|
199
|
+
const parseLiteralValues = (values) => {
|
|
200
|
+
if (values.length === 0) return z.never();
|
|
201
|
+
if (values.every((value) => value === null || typeof value !== "object")) {
|
|
202
|
+
if (values.length === 1) return z.literal(values[0]);
|
|
203
|
+
if (values.every((value) => typeof value === "string")) return z.enum(values);
|
|
204
|
+
return z.union(values.map((value) => z.literal(value)));
|
|
205
|
+
}
|
|
206
|
+
return z.custom((value) => values.some((candidate) => dequal(value, candidate)));
|
|
207
|
+
};
|
|
208
|
+
|
|
159
209
|
//#endregion
|
|
160
210
|
//#region src/parsers/parse-const.ts
|
|
161
|
-
const parseConst = (jsonSchema) => {
|
|
162
|
-
|
|
211
|
+
const parseConst = (jsonSchema, refs) => {
|
|
212
|
+
const { const: value, ...baseSchema } = jsonSchema;
|
|
213
|
+
return parseSchema(baseSchema, {
|
|
214
|
+
...refs,
|
|
215
|
+
seen: new Map(refs.seen)
|
|
216
|
+
}, true).and(parseLiteralValues([value]));
|
|
163
217
|
};
|
|
164
218
|
|
|
165
219
|
//#endregion
|
|
@@ -170,11 +224,12 @@ const parseDefault = (_jsonSchema) => {
|
|
|
170
224
|
|
|
171
225
|
//#endregion
|
|
172
226
|
//#region src/parsers/parse-enum.ts
|
|
173
|
-
const parseEnum = (jsonSchema) => {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
227
|
+
const parseEnum = (jsonSchema, refs) => {
|
|
228
|
+
const { enum: values, ...baseSchema } = jsonSchema;
|
|
229
|
+
return parseSchema(baseSchema, {
|
|
230
|
+
...refs,
|
|
231
|
+
seen: new Map(refs.seen)
|
|
232
|
+
}, true).and(parseLiteralValues(values));
|
|
178
233
|
};
|
|
179
234
|
|
|
180
235
|
//#endregion
|
|
@@ -242,6 +297,30 @@ const parseNullable = (jsonSchema, refs) => {
|
|
|
242
297
|
|
|
243
298
|
//#endregion
|
|
244
299
|
//#region src/parsers/parse-number.ts
|
|
300
|
+
const toDecimalInteger = (value) => {
|
|
301
|
+
if (!Number.isFinite(value)) return void 0;
|
|
302
|
+
const negative = value < 0;
|
|
303
|
+
const [coefficient, exponentText] = Math.abs(value).toString().toLowerCase().split("e");
|
|
304
|
+
const exponent = exponentText === void 0 ? 0 : Number(exponentText);
|
|
305
|
+
const [whole, fraction = ""] = coefficient.split(".");
|
|
306
|
+
let digits = `${whole}${fraction}`.replace(/^0+(?=\d)/, "");
|
|
307
|
+
let scale = fraction.length - exponent;
|
|
308
|
+
if (scale < 0) {
|
|
309
|
+
digits += "0".repeat(-scale);
|
|
310
|
+
scale = 0;
|
|
311
|
+
}
|
|
312
|
+
return {
|
|
313
|
+
integer: BigInt(`${negative ? "-" : ""}${digits}`),
|
|
314
|
+
scale
|
|
315
|
+
};
|
|
316
|
+
};
|
|
317
|
+
const isJsonMultipleOf = (value, multiple) => {
|
|
318
|
+
const dividend = toDecimalInteger(value);
|
|
319
|
+
const divisor = toDecimalInteger(multiple);
|
|
320
|
+
if (!dividend || !divisor || divisor.integer === 0n) return false;
|
|
321
|
+
const scale = Math.max(dividend.scale, divisor.scale);
|
|
322
|
+
return dividend.integer * 10n ** BigInt(scale - dividend.scale) % (divisor.integer * 10n ** BigInt(scale - divisor.scale)) === 0n;
|
|
323
|
+
};
|
|
245
324
|
const parseNumber = (jsonSchema) => {
|
|
246
325
|
let zodSchema = z.number();
|
|
247
326
|
let isInteger = false;
|
|
@@ -252,19 +331,12 @@ const parseNumber = (jsonSchema) => {
|
|
|
252
331
|
isInteger = true;
|
|
253
332
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, _, errorMsg) => zs.int(errorMsg));
|
|
254
333
|
}
|
|
255
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "multipleOf", (zs, multipleOf, errorMsg) => {
|
|
256
|
-
if (multipleOf === 1) {
|
|
257
|
-
if (isInteger) return zs;
|
|
258
|
-
return zs.int(errorMsg);
|
|
259
|
-
}
|
|
260
|
-
return zs.multipleOf(multipleOf, errorMsg);
|
|
261
|
-
});
|
|
262
334
|
if (typeof jsonSchema.minimum === "number") if (jsonSchema.exclusiveMinimum === true) zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => zs.gt(minimum, errorMsg));
|
|
263
335
|
else zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg));
|
|
264
|
-
|
|
336
|
+
if (typeof jsonSchema.exclusiveMinimum === "number") zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMinimum", (zs, exclusiveMinimum, errorMsg) => zs.gt(exclusiveMinimum, errorMsg));
|
|
265
337
|
if (typeof jsonSchema.maximum === "number") if (jsonSchema.exclusiveMaximum === true) zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => zs.lt(maximum, errorMsg));
|
|
266
338
|
else zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg));
|
|
267
|
-
|
|
339
|
+
if (typeof jsonSchema.exclusiveMaximum === "number") zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMaximum", (zs, exclusiveMaximum, errorMsg) => zs.lt(exclusiveMaximum, errorMsg));
|
|
268
340
|
if (typeof jsonSchema.min === "number" && typeof jsonSchema.minimum !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
269
341
|
...jsonSchema,
|
|
270
342
|
minimum: jsonSchema.min
|
|
@@ -273,6 +345,11 @@ const parseNumber = (jsonSchema) => {
|
|
|
273
345
|
...jsonSchema,
|
|
274
346
|
maximum: jsonSchema.max
|
|
275
347
|
}, "maximum", (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg));
|
|
348
|
+
if (typeof jsonSchema.multipleOf === "number") {
|
|
349
|
+
const errorMessage = jsonSchema.errorMessage?.multipleOf;
|
|
350
|
+
if (jsonSchema.multipleOf === 1) return isInteger ? zodSchema : zodSchema.int(errorMessage);
|
|
351
|
+
return zodSchema.refine((value) => isJsonMultipleOf(value, jsonSchema.multipleOf), { message: errorMessage ?? `Number must be a multiple of ${jsonSchema.multipleOf}` });
|
|
352
|
+
}
|
|
276
353
|
return zodSchema;
|
|
277
354
|
};
|
|
278
355
|
|
|
@@ -484,17 +561,206 @@ const parseString = (jsonSchema) => {
|
|
|
484
561
|
});
|
|
485
562
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "contentEncoding", (zs, _, errorMsg) => zs.base64(errorMsg));
|
|
486
563
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "pattern", (zs, pattern, errorMsg) => zs.regex(new RegExp(pattern), errorMsg));
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
564
|
+
const errorMessages = jsonSchema.errorMessage;
|
|
565
|
+
const minLength = typeof jsonSchema.minLength === "number" ? jsonSchema.minLength : typeof jsonSchema.min === "number" ? jsonSchema.min : void 0;
|
|
566
|
+
const maxLength = typeof jsonSchema.maxLength === "number" ? jsonSchema.maxLength : typeof jsonSchema.max === "number" ? jsonSchema.max : void 0;
|
|
567
|
+
let result = zodSchema;
|
|
568
|
+
if (minLength !== void 0) result = result.refine((value) => codePointLength(value) >= minLength, { message: errorMessages?.minLength ?? `String must contain at least ${minLength} character(s)` });
|
|
569
|
+
if (maxLength !== void 0) result = result.refine((value) => codePointLength(value) <= maxLength, { message: errorMessages?.maxLength ?? `String must contain at most ${maxLength} character(s)` });
|
|
570
|
+
return result;
|
|
571
|
+
};
|
|
572
|
+
const codePointLength = (value) => [...value].length;
|
|
573
|
+
|
|
574
|
+
//#endregion
|
|
575
|
+
//#region src/parsers/parse-typeless-constraints.ts
|
|
576
|
+
const SCALAR_CONSTRAINT_KEYS = [
|
|
577
|
+
"minLength",
|
|
578
|
+
"maxLength",
|
|
579
|
+
"pattern",
|
|
580
|
+
"minimum",
|
|
581
|
+
"maximum",
|
|
582
|
+
"exclusiveMinimum",
|
|
583
|
+
"exclusiveMaximum",
|
|
584
|
+
"multipleOf"
|
|
585
|
+
];
|
|
586
|
+
const hasTypelessScalarConstraints = (schema) => schema.type === void 0 && SCALAR_CONSTRAINT_KEYS.some((key) => schema[key] !== void 0);
|
|
587
|
+
/**
|
|
588
|
+
* Draft 7 applies scalar constraints to matching instance types even when the
|
|
589
|
+
* schema declares no `type`: `{ "minLength": 2 }` restricts strings while
|
|
590
|
+
* leaving every non-string value untouched.
|
|
591
|
+
*/
|
|
592
|
+
const parseTypelessConstraints = (schema) => {
|
|
593
|
+
const stringSchema = parseString({
|
|
594
|
+
...schema,
|
|
595
|
+
type: "string"
|
|
596
|
+
});
|
|
597
|
+
const numberSchema = parseNumber({
|
|
598
|
+
...schema,
|
|
599
|
+
type: "number"
|
|
600
|
+
});
|
|
601
|
+
return z.any().superRefine((value, ctx) => {
|
|
602
|
+
const applicable = typeof value === "string" ? stringSchema : typeof value === "number" ? numberSchema : void 0;
|
|
603
|
+
if (applicable === void 0) return;
|
|
604
|
+
const result = applicable.safeParse(value);
|
|
605
|
+
if (!result.success) for (const issue of result.error.issues) ctx.addIssue(issue);
|
|
606
|
+
});
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
//#endregion
|
|
610
|
+
//#region src/whole-schema-validation.ts
|
|
611
|
+
const REQUIRES_WHOLE_SCHEMA_VALIDATION = /* @__PURE__ */ new Set([
|
|
612
|
+
"$ref",
|
|
613
|
+
"additionalItems",
|
|
614
|
+
"allOf",
|
|
615
|
+
"anyOf",
|
|
616
|
+
"contains",
|
|
617
|
+
"dependencies",
|
|
618
|
+
"else",
|
|
619
|
+
"if",
|
|
620
|
+
"maxProperties",
|
|
621
|
+
"minProperties",
|
|
622
|
+
"not",
|
|
623
|
+
"oneOf",
|
|
624
|
+
"propertyNames",
|
|
625
|
+
"then",
|
|
626
|
+
"uniqueItems"
|
|
627
|
+
]);
|
|
628
|
+
const TYPELESS_TYPE_SCOPED_KEYWORDS = /* @__PURE__ */ new Set([
|
|
629
|
+
"properties",
|
|
630
|
+
"patternProperties",
|
|
631
|
+
"additionalProperties",
|
|
632
|
+
"propertyNames",
|
|
633
|
+
"required",
|
|
634
|
+
"dependencies",
|
|
635
|
+
"minProperties",
|
|
636
|
+
"maxProperties",
|
|
637
|
+
"items",
|
|
638
|
+
"additionalItems",
|
|
639
|
+
"contains",
|
|
640
|
+
"minItems",
|
|
641
|
+
"maxItems",
|
|
642
|
+
"uniqueItems"
|
|
643
|
+
]);
|
|
644
|
+
const SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([
|
|
645
|
+
"$defs",
|
|
646
|
+
"definitions",
|
|
647
|
+
"dependencies",
|
|
648
|
+
"patternProperties",
|
|
649
|
+
"properties"
|
|
650
|
+
]);
|
|
651
|
+
const SCHEMA_ARRAY_KEYWORDS = /* @__PURE__ */ new Set([
|
|
652
|
+
"allOf",
|
|
653
|
+
"anyOf",
|
|
654
|
+
"oneOf"
|
|
655
|
+
]);
|
|
656
|
+
const SCHEMA_VALUE_KEYWORDS = /* @__PURE__ */ new Set([
|
|
657
|
+
"additionalItems",
|
|
658
|
+
"additionalProperties",
|
|
659
|
+
"contains",
|
|
660
|
+
"else",
|
|
661
|
+
"if",
|
|
662
|
+
"items",
|
|
663
|
+
"not",
|
|
664
|
+
"propertyNames",
|
|
665
|
+
"then"
|
|
666
|
+
]);
|
|
667
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
668
|
+
const hasRequiredDefault = (schema) => {
|
|
669
|
+
if (!Array.isArray(schema.required) || !isObject(schema.properties)) return false;
|
|
670
|
+
return schema.required.some((name) => {
|
|
671
|
+
const property = schema.properties?.[name];
|
|
672
|
+
return isObject(property) && property.default !== void 0;
|
|
673
|
+
});
|
|
674
|
+
};
|
|
675
|
+
const hasUnparsedRequiredProperty = (schema) => {
|
|
676
|
+
if (!Array.isArray(schema.required)) return false;
|
|
677
|
+
const declared = new Set(Object.keys(schema.properties ?? {}));
|
|
678
|
+
return schema.required.some((name) => !declared.has(name));
|
|
679
|
+
};
|
|
680
|
+
/**
|
|
681
|
+
* The native parsers preserve useful Zod structure and materialize defaults,
|
|
682
|
+
* but some JSON Schema assertions cannot be represented by their first-match
|
|
683
|
+
* dispatch. Only those schemas receive an authoritative Draft 7 guard.
|
|
684
|
+
*/
|
|
685
|
+
const requiresWholeSchemaValidation = (schema, seen = /* @__PURE__ */ new WeakSet()) => {
|
|
686
|
+
if (!isObject(schema) || seen.has(schema)) return false;
|
|
687
|
+
seen.add(schema);
|
|
688
|
+
if (Object.keys(schema).some((key) => REQUIRES_WHOLE_SCHEMA_VALIDATION.has(key)) || schema.type === void 0 && Object.keys(schema).some((key) => TYPELESS_TYPE_SCOPED_KEYWORDS.has(key)) || hasUnparsedRequiredProperty(schema) || hasRequiredDefault(schema)) return true;
|
|
689
|
+
for (const [key, child] of Object.entries(schema)) if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) {
|
|
690
|
+
if (Object.values(child).some((value) => requiresWholeSchemaValidation(value, seen))) return true;
|
|
691
|
+
} else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) {
|
|
692
|
+
if (child.some((value) => requiresWholeSchemaValidation(value, seen))) return true;
|
|
693
|
+
} else if (SCHEMA_VALUE_KEYWORDS.has(key)) {
|
|
694
|
+
if ((Array.isArray(child) ? child : [child]).some((value) => requiresWholeSchemaValidation(value, seen))) return true;
|
|
695
|
+
}
|
|
696
|
+
return false;
|
|
697
|
+
};
|
|
698
|
+
/**
|
|
699
|
+
* Some schemas are valid for JSON instance types that the native parser does
|
|
700
|
+
* not materialize. Such a node is parsed as `z.any()` so the Draft 7 guard
|
|
701
|
+
* that every one of these keywords also activates (see
|
|
702
|
+
* `requiresWholeSchemaValidation`) stays the acceptance authority without
|
|
703
|
+
* piping into a narrower Zod schema. The check is deliberately local: a
|
|
704
|
+
* permissive descendant must not widen its enclosing parser, or sibling
|
|
705
|
+
* defaults would stop materializing.
|
|
706
|
+
*/
|
|
707
|
+
const requiresPermissiveMaterialization = (schema) => isObject(schema) && ("$ref" in schema || schema.type === void 0 && (Object.keys(schema).some((key) => TYPELESS_TYPE_SCOPED_KEYWORDS.has(key)) || [
|
|
708
|
+
"if",
|
|
709
|
+
"then",
|
|
710
|
+
"else",
|
|
711
|
+
"not"
|
|
712
|
+
].some((key) => key in schema)));
|
|
713
|
+
/**
|
|
714
|
+
* The guard schema for a node nested at `path` inside `root`: the enclosing
|
|
715
|
+
* document pointed at that node, so local `$ref`s resolve exactly as they do
|
|
716
|
+
* for the document root. Draft 7 ignores the keywords next to `$ref`, which
|
|
717
|
+
* is what lets the root's own assertions be reused as the pointer carrier.
|
|
718
|
+
*/
|
|
719
|
+
const guardSchemaAt = (node, refs) => isObject(refs.root) && refs.path.length > 0 ? {
|
|
720
|
+
...refs.root,
|
|
721
|
+
$ref: `#/${refs.path.map((part) => encodePointer(String(part))).join("/")}`
|
|
722
|
+
} : node;
|
|
723
|
+
/**
|
|
724
|
+
* OpenAPI 3.0 / Draft 4 spell exclusive bounds as a boolean flag next to
|
|
725
|
+
* `minimum`/`maximum`. The Draft 7 interpreter ignores the flag, so the guard
|
|
726
|
+
* receives the numeric spelling the native number parser already honors.
|
|
727
|
+
*/
|
|
728
|
+
const normalizeExclusiveBounds = (value, seen) => {
|
|
729
|
+
if (!isObject(value) || seen.has(value)) return;
|
|
730
|
+
seen.add(value);
|
|
731
|
+
if (value.exclusiveMinimum === true && typeof value.minimum === "number") {
|
|
732
|
+
value.exclusiveMinimum = value.minimum;
|
|
733
|
+
delete value.minimum;
|
|
734
|
+
} else if (typeof value.exclusiveMinimum === "boolean") delete value.exclusiveMinimum;
|
|
735
|
+
if (value.exclusiveMaximum === true && typeof value.maximum === "number") {
|
|
736
|
+
value.exclusiveMaximum = value.maximum;
|
|
737
|
+
delete value.maximum;
|
|
738
|
+
} else if (typeof value.exclusiveMaximum === "boolean") delete value.exclusiveMaximum;
|
|
739
|
+
for (const [key, child] of Object.entries(value)) if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) Object.values(child).forEach((nested) => normalizeExclusiveBounds(nested, seen));
|
|
740
|
+
else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) child.forEach((nested) => normalizeExclusiveBounds(nested, seen));
|
|
741
|
+
else if (SCHEMA_VALUE_KEYWORDS.has(key)) (Array.isArray(child) ? child : [child]).forEach((nested) => normalizeExclusiveBounds(nested, seen));
|
|
742
|
+
};
|
|
743
|
+
const withWholeSchemaValidation = (jsonSchema, parsedSchema) => {
|
|
744
|
+
const interpreterSchema = structuredClone(jsonSchema);
|
|
745
|
+
normalizeExclusiveBounds(interpreterSchema, /* @__PURE__ */ new WeakSet());
|
|
746
|
+
const validator = new Validator(interpreterSchema, "7", false);
|
|
747
|
+
const guardedSchema = z.any().superRefine((value, ctx) => {
|
|
748
|
+
let result;
|
|
749
|
+
try {
|
|
750
|
+
result = validator.validate(value);
|
|
751
|
+
} catch (cause) {
|
|
752
|
+
ctx.addIssue({
|
|
753
|
+
code: z.ZodIssueCode.custom,
|
|
754
|
+
message: `JSON Schema validation failed: ${String(cause)}`
|
|
755
|
+
});
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
if (!result.valid) ctx.addIssue({
|
|
759
|
+
code: z.ZodIssueCode.custom,
|
|
760
|
+
message: result.errors[0]?.error ?? "Input does not satisfy the complete JSON Schema."
|
|
761
|
+
});
|
|
762
|
+
}).pipe(parsedSchema);
|
|
763
|
+
return parsedSchema.description ? guardedSchema.describe(parsedSchema.description) : guardedSchema;
|
|
498
764
|
};
|
|
499
765
|
|
|
500
766
|
//#endregion
|
|
@@ -530,15 +796,17 @@ const addAnnotations = (jsonSchema, zodSchema) => {
|
|
|
530
796
|
return zodSchema;
|
|
531
797
|
};
|
|
532
798
|
const selectParser = (schema, refs) => {
|
|
533
|
-
if (
|
|
799
|
+
if (requiresPermissiveMaterialization(schema)) return withWholeSchemaValidation(guardSchemaAt(schema, refs), z$1.any());
|
|
800
|
+
else if (its.a.nullable(schema)) return parseNullable(schema, refs);
|
|
801
|
+
else if (its.an.enum(schema)) return parseEnum(schema, refs);
|
|
802
|
+
else if (its.a.const(schema)) return parseConst(schema, refs);
|
|
534
803
|
else if (its.an.object(schema)) return parseObject(schema, refs);
|
|
535
804
|
else if (its.an.array(schema)) return parseArray(schema, refs);
|
|
536
805
|
else if (its.an.anyOf(schema)) return parseAnyOf(schema, refs);
|
|
537
806
|
else if (its.an.allOf(schema)) return parseAllOf(schema, refs);
|
|
538
807
|
else if (its.a.oneOf(schema)) return parseOneOf(schema, refs);
|
|
539
808
|
else if (its.a.not(schema)) return parseNot(schema, refs);
|
|
540
|
-
else if (
|
|
541
|
-
else if (its.a.const(schema)) return parseConst(schema);
|
|
809
|
+
else if (hasTypelessScalarConstraints(schema)) return parseTypelessConstraints(schema);
|
|
542
810
|
else if (its.a.multipleType(schema)) return parseMultipleType(schema, refs);
|
|
543
811
|
else if (its.a.primitive(schema, "string")) return parseString(schema);
|
|
544
812
|
else if (its.a.primitive(schema, "number") || its.a.primitive(schema, "integer")) return parseNumber(schema);
|
|
@@ -595,14 +863,17 @@ function parseObjectShape(objectSchema, refs) {
|
|
|
595
863
|
const properties = {};
|
|
596
864
|
for (const key of propertyKeys) {
|
|
597
865
|
const propJsonSchema = objectSchema.properties[key];
|
|
598
|
-
const
|
|
866
|
+
const propRefs = {
|
|
599
867
|
...refs,
|
|
868
|
+
root: refs.root ?? objectSchema,
|
|
600
869
|
path: [
|
|
601
870
|
...refs.path,
|
|
602
871
|
"properties",
|
|
603
872
|
key
|
|
604
873
|
]
|
|
605
|
-
}
|
|
874
|
+
};
|
|
875
|
+
const parsedProperty = parseSchema(propJsonSchema, propRefs);
|
|
876
|
+
const propZodSchema = requiresWholeSchemaValidation(propJsonSchema) ? withWholeSchemaValidation(guardSchemaAt(propJsonSchema, propRefs), parsedProperty) : parsedProperty;
|
|
606
877
|
const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : false;
|
|
607
878
|
if (!required && propJsonSchema && typeof propJsonSchema === "object" && "default" in propJsonSchema) if (propJsonSchema.default === null) {
|
|
608
879
|
const hasAnyOfWithNull = propJsonSchema.anyOf && Array.isArray(propJsonSchema.anyOf) && propJsonSchema.anyOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
|
|
@@ -619,11 +890,13 @@ function parseObjectShape(objectSchema, refs) {
|
|
|
619
890
|
//#endregion
|
|
620
891
|
//#region src/json-schema-to-zod.ts
|
|
621
892
|
const jsonSchemaToZod = (schema, options = {}) => {
|
|
622
|
-
|
|
893
|
+
const parsedSchema = parseSchema(schema, {
|
|
623
894
|
path: [],
|
|
624
895
|
seen: /* @__PURE__ */ new Map(),
|
|
896
|
+
root: schema,
|
|
625
897
|
...options
|
|
626
898
|
});
|
|
899
|
+
return requiresWholeSchemaValidation(schema) ? withWholeSchemaValidation(schema, parsedSchema) : parsedSchema;
|
|
627
900
|
};
|
|
628
901
|
/**
|
|
629
902
|
* Converts a JSON Schema object to a Zod raw shape.
|
|
@@ -639,9 +912,11 @@ const jsonSchemaToZod = (schema, options = {}) => {
|
|
|
639
912
|
*/
|
|
640
913
|
const jsonSchemaToZodShape = (schema, options = {}) => {
|
|
641
914
|
if (typeof schema !== "object" || schema === null) return {};
|
|
642
|
-
|
|
915
|
+
const objectSchema = schema;
|
|
916
|
+
return parseObjectShape(objectSchema, {
|
|
643
917
|
path: [],
|
|
644
918
|
seen: /* @__PURE__ */ new Map(),
|
|
919
|
+
root: objectSchema,
|
|
645
920
|
...options
|
|
646
921
|
});
|
|
647
922
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@composio/json-schema-to-zod",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.mjs",
|
|
6
6
|
"type": "module",
|
|
@@ -37,7 +37,9 @@
|
|
|
37
37
|
"license": "ISC",
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@types/json-schema": "^7.0.15",
|
|
40
|
-
"@types/node": "^26.
|
|
40
|
+
"@types/node": "^26.3.0",
|
|
41
|
+
"ajv": "^8.20.0",
|
|
42
|
+
"fast-check": "^4.9.0",
|
|
41
43
|
"tsdown": "^0.22.14",
|
|
42
44
|
"typescript": "^7.0.2",
|
|
43
45
|
"vitest": "^4.1.11",
|
|
@@ -46,6 +48,10 @@
|
|
|
46
48
|
"peerDependencies": {
|
|
47
49
|
"zod": ">=3.25.76 <5"
|
|
48
50
|
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"@cfworker/json-schema": "^4.1.1",
|
|
53
|
+
"dequal": "^2.0.3"
|
|
54
|
+
},
|
|
49
55
|
"scripts": {
|
|
50
56
|
"clean": "git clean -xdf node_modules",
|
|
51
57
|
"build": "tsdown",
|