schema-truth 0.7.0 → 0.8.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.
Files changed (36) hide show
  1. package/dist/{ajv-DTP2FXRr.js → ajv-DS9gtNZC.js} +1 -1
  2. package/dist/ajv.d.ts +1 -1
  3. package/dist/ajv.js +1 -1
  4. package/dist/{arktype-BdvvaBQX.js → arktype-CBV4bg-0.js} +179 -75
  5. package/dist/arktype.d.ts +3 -3
  6. package/dist/arktype.js +1 -1
  7. package/dist/cli/ajv.js +2 -2
  8. package/dist/cli/arktype.js +2 -2
  9. package/dist/cli/effect.js +2 -2
  10. package/dist/cli/typebox.js +2 -2
  11. package/dist/cli/valibot.js +2 -2
  12. package/dist/cli/yup.js +2 -2
  13. package/dist/cli/zod.js +2 -2
  14. package/dist/{cli-CL2mSark.js → cli-CB9GJ7qa.js} +2 -2
  15. package/dist/{effect-mUknRPv_.js → effect-D9pvwi_6.js} +91 -31
  16. package/dist/effect.d.ts +3 -3
  17. package/dist/effect.js +1 -1
  18. package/dist/{helper-Cfvb5UDq.js → helper-S7SSsYwh.js} +777 -40
  19. package/dist/{index-C2L8Ty0-.d.ts → index-EK43HM_z.d.ts} +29 -25
  20. package/dist/{index-DbV3dEmN.d.ts → index-G7UqNQ4w.d.ts} +54 -2
  21. package/dist/index.d.ts +63 -25
  22. package/dist/index.js +9 -9
  23. package/dist/{typebox-BdWJv3ND.js → typebox-DGGKJLdP.js} +82 -42
  24. package/dist/typebox.d.ts +3 -3
  25. package/dist/typebox.js +1 -1
  26. package/dist/{utils-WNBq1HR0.js → utils-Bky98UmP.js} +160 -31
  27. package/dist/{valibot-CaJIynCH.js → valibot-B6y4VQFF.js} +107 -36
  28. package/dist/valibot.d.ts +3 -3
  29. package/dist/valibot.js +1 -1
  30. package/dist/{yup-CM2TSFig.js → yup-DuqQwHUv.js} +2 -2
  31. package/dist/yup.d.ts +2 -2
  32. package/dist/yup.js +1 -1
  33. package/dist/{zod-BsXLZfwK.js → zod-CXo9NFuF.js} +192 -115
  34. package/dist/zod.d.ts +3 -3
  35. package/dist/zod.js +1 -1
  36. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- import { B as isSchemaObject, D as isComposite, F as isPrimitive, H as isStringWireLocation, M as isNullable, N as isObjectPrototypeProperty, Ot as UNSAFE_GENERATED_MARKER, P as isPlainObject, S as hasFixedLength, T as hasType, V as isShapelessMember, X as DEFAULT_ROOT_NAME, b as hasConditional, c as normalizeTypes, g as zodErrorPart, h as zodError, j as isNullTypeMember, k as isDefaultOnlyMember, m as zodBaseError, o as issueMessageExpression, ot as ISO_4217_CURRENCY_CODES, s as makeSafeKey, y as hasCombinator } from "./utils-WNBq1HR0.js";
2
- import { A as emitOptionsOf, F as schemaNamer, H as findCodeExtensionKeysInSchema, L as hasRootSelfReference, M as planDocument, N as renderDefinitions, P as rootNameOf, S as wireNullText, T as timePattern, a as regexLiteral, b as unionPrimitiveTypes, c as parameterReaders, g as isPrimitiveUnion, h as isNullTextRead, i as typeDeclaration, l as withoutParameterSerialization, m as isNullMatchedFirst, o as refTarget, p as impliedWireType, s as hasParameterSerialization, t as zodWrap, u as notPredicate, x as wireArrayOnce, z as itemsSchemaOf } from "./helper-Cfvb5UDq.js";
1
+ import { At as UNSAFE_GENERATED_MARKER, B as isSchemaObject, D as isComposite, F as isPrimitive, H as isStringWireLocation, M as isNullable, N as isObjectPrototypeProperty, P as isPlainObject, S as hasFixedLength, T as hasType, V as isShapelessMember, X as DEFAULT_ROOT_NAME, b as hasConditional, c as normalizeTypes, g as zodErrorPart, h as zodError, j as isNullTypeMember, k as isDefaultOnlyMember, m as zodBaseError, o as issueMessageExpression, s as makeSafeKey, st as ISO_4217_CURRENCY_CODES, y as hasCombinator } from "./utils-Bky98UmP.js";
2
+ import { A as wireNullText, B as emitOptionsOf, C as isPrimitiveUnion, G as schemaNamer, H as planDocument, J as hasRootSelfReference, K as discriminatedMembers, O as unionPrimitiveTypes, P as timePattern, S as isNullTextRead, U as renderDefinitions, W as rootNameOf, X as itemsSchemaOf, at as foldAllOfMembers, b as integerWirePattern, c as withPolymorphicBases, ct as regexLiteral, d as propertyEmitOptions, f as withoutParameterSerialization, g as hoistNestedRefs, h as valueListLiteral, i as isEvaluatedKeyExpression, it as constraintPredicate, j as wireNumericKind, k as wireArrayOnce, l as hasParameterSerialization, m as notPredicate, o as typeDeclaration, ot as isKeywordOnlyMember, p as isBigintFormat, r as evaluatedProperties, rt as constraintMessage, s as refTarget, t as zodWrap, tt as findCodeExtensionKeysInSchema, u as parameterReaders, w as numberWirePattern, x as isNullMatchedFirst, y as impliedWireType, z as definitionsOf } from "./helper-S7SSsYwh.js";
3
3
  //#region src/generator/zod/type.ts
4
4
  /** The TypeScript type declared beside a recursive Zod schema. */
5
5
  function type(schema, rootName = DEFAULT_ROOT_NAME) {
@@ -9,6 +9,71 @@ function type(schema, rootName = DEFAULT_ROOT_NAME) {
9
9
  }, rootName);
10
10
  }
11
11
  //#endregion
12
+ //#region src/generator/zod/number.ts
13
+ /**
14
+ * Wire text checked against the integer or JSON number grammar, then read with `Number`.
15
+ * `z.coerce.number()` uses `Number` on its own, which accepts `""`, `" "` and `"0x10"`.
16
+ */
17
+ function zodWireNumber(kind, errorArg = "") {
18
+ return `z.string().regex(${kind === "integer" ? integerWirePattern() : numberWirePattern()}${errorArg === "" ? "" : `,${errorArg}`}).transform((val)=>Number(val))`;
19
+ }
20
+ /**
21
+ * Generates a Zod schema for number types (number / float32 / float64), with
22
+ * min/max/multipleOf constraints and `x-*-message` vendor extensions translated
23
+ * to Zod v4 `{error: "msg"}` parameters.
24
+ */
25
+ function number(schema, options) {
26
+ const isWire = options?.wire === true;
27
+ const errorMessage = schema["x-error-message"];
28
+ const requiredMessage = schema["x-required-message"];
29
+ const isCoerce = schema["x-coerce"] === true && !isWire;
30
+ const baseErrorArg = zodBaseError(errorMessage, isCoerce || isWire ? void 0 : requiredMessage);
31
+ const isFloat32 = schema.format === "float" || schema.format === "float32";
32
+ const isFloat64 = schema.format === "float64";
33
+ const base = isFloat32 ? `z.float32(${baseErrorArg})` : isFloat64 ? `z.float64(${baseErrorArg})` : isCoerce ? `z.coerce.number(${baseErrorArg})` : `z.number(${baseErrorArg})`;
34
+ const minimumMessage = schema["x-minimum-message"];
35
+ const exclusiveMinMessage = schema["x-exclusiveMinimum-message"];
36
+ const minErrorArg = minimumMessage ? zodError(minimumMessage) : "";
37
+ const minErrorPart = minErrorArg ? `,${minErrorArg}` : "";
38
+ const exMinErrorArg = exclusiveMinMessage ? zodError(exclusiveMinMessage) : "";
39
+ const exMinErrorPart = exMinErrorArg ? `,${exMinErrorArg}` : "";
40
+ const minimum = (() => {
41
+ if (schema.minimum !== void 0) {
42
+ if (schema.minimum === 0 && schema.exclusiveMinimum === true) return `.positive(${exMinErrorArg})`;
43
+ if (schema.minimum === 0 && schema.exclusiveMinimum === false) return `.nonnegative(${minErrorArg})`;
44
+ if (schema.exclusiveMinimum === true) return `.gt(${schema.minimum}${exMinErrorPart})`;
45
+ return `.min(${schema.minimum}${minErrorPart})`;
46
+ }
47
+ if (typeof schema.exclusiveMinimum === "number") return `.gt(${schema.exclusiveMinimum}${exMinErrorPart})`;
48
+ })();
49
+ const maximumMessage = schema["x-maximum-message"];
50
+ const exclusiveMaxMessage = schema["x-exclusiveMaximum-message"];
51
+ const maxErrorArg = maximumMessage ? zodError(maximumMessage) : "";
52
+ const maxErrorPart = maxErrorArg ? `,${maxErrorArg}` : "";
53
+ const exMaxErrorArg = exclusiveMaxMessage ? zodError(exclusiveMaxMessage) : "";
54
+ const exMaxErrorPart = exMaxErrorArg ? `,${exMaxErrorArg}` : "";
55
+ const maximum = (() => {
56
+ if (schema.maximum !== void 0) {
57
+ if (schema.maximum === 0 && schema.exclusiveMaximum === true) return `.negative(${exMaxErrorArg})`;
58
+ if (schema.maximum === 0 && schema.exclusiveMaximum === false) return `.nonpositive(${maxErrorArg})`;
59
+ if (schema.exclusiveMaximum === true) return `.lt(${schema.maximum}${exMaxErrorPart})`;
60
+ return `.max(${schema.maximum}${maxErrorPart})`;
61
+ }
62
+ if (typeof schema.exclusiveMaximum === "number") return `.lt(${schema.exclusiveMaximum}${exMaxErrorPart})`;
63
+ })();
64
+ const multipleOfMessage = schema["x-multipleOf-message"];
65
+ const multipleOfErrorArg = multipleOfMessage ? `,${zodError(multipleOfMessage)}` : baseErrorArg ? `,${baseErrorArg}` : "";
66
+ const innerChain = [
67
+ base,
68
+ minimum,
69
+ maximum,
70
+ schema.multipleOf !== void 0 ? `.multipleOf(${schema.multipleOf}${multipleOfErrorArg})` : void 0
71
+ ].filter((v) => v !== void 0).join("");
72
+ if (isWire) return `${zodWireNumber("number", baseErrorArg)}.pipe(${innerChain})`;
73
+ if (isCoerce && (isFloat32 || isFloat64)) return `z.coerce.number(${baseErrorArg}).pipe(${innerChain})`;
74
+ return innerChain;
75
+ }
76
+ //#endregion
12
77
  //#region src/generator/zod/integer.ts
13
78
  /** Whether a node is a 64-bit integer: a value beyond 2^53 that Zod reads as a bigint. */
14
79
  function isInt64(schema) {
@@ -29,15 +94,17 @@ function int64Input(isWire, baseErrorArg = "") {
29
94
  * min/max/multipleOf constraints and `x-*-message` vendor extensions translated
30
95
  * to Zod v4 `{error: "msg"}` parameters.
31
96
  */
32
- function integer(schema) {
97
+ function integer(schema, options) {
98
+ const isWire = options?.wire === true;
33
99
  const errorMessage = schema["x-error-message"];
34
100
  const requiredMessage = schema["x-required-message"];
35
- const isCoerce = schema["x-coerce"] === true;
36
- const baseErrorArg = zodBaseError(errorMessage, isCoerce ? void 0 : requiredMessage);
101
+ const isCoerce = schema["x-coerce"] === true && !isWire;
102
+ const readsText = isCoerce || isWire;
103
+ const baseErrorArg = zodBaseError(errorMessage, readsText ? void 0 : requiredMessage);
37
104
  const isBigint = schema.format === "bigint";
38
105
  const isInt32 = schema.format === "int32" || schema.format === "uint32";
39
106
  const is64 = isInt64(schema);
40
- const bigintBase = isCoerce && isBigint;
107
+ const bigintBase = readsText && isBigint;
41
108
  const numberPipe = isCoerce && isInt32;
42
109
  const numberChain = isCoerce && !isBigint && !is64 && !isInt32;
43
110
  const base = bigintBase ? `z.coerce.bigint(${baseErrorArg})` : isInt32 ? `z.${schema.format === "uint32" ? "uint32" : "int32"}(${baseErrorArg})` : is64 ? `z.${schema.format === "uint64" ? "uint64" : "int64"}(${baseErrorArg})` : isBigint ? `z.bigint(${baseErrorArg})` : `z.int(${baseErrorArg})`;
@@ -77,22 +144,25 @@ function integer(schema) {
77
144
  const multipleOfMessage = schema["x-multipleOf-message"] ?? errorMessage;
78
145
  const multipleOfErrorArg = zodErrorPart(multipleOfMessage);
79
146
  const multipleOf = typeof schema.multipleOf === "number" ? `.multipleOf(${lit(schema.multipleOf)}${multipleOfErrorArg})` : void 0;
147
+ const constraints = [
148
+ minimum,
149
+ maximum,
150
+ multipleOf
151
+ ].filter((v) => v !== void 0).join("");
80
152
  const innerChain = [
81
153
  base,
82
154
  minimum,
83
155
  maximum,
84
156
  multipleOf
85
157
  ].filter((v) => v !== void 0).join("");
86
- if (numberChain) {
87
- const constraints = [
88
- minimum,
89
- maximum,
90
- multipleOf
91
- ].filter((v) => v !== void 0).join("");
92
- return `z.coerce.number(${baseErrorArg}).int(${errorMessage ? zodError(errorMessage) : ""})${constraints}`;
158
+ if (isWire && !isBigint && !is64) {
159
+ const intErrorArg = errorMessage ? zodError(errorMessage) : "";
160
+ const inner = isInt32 ? innerChain : `z.number(${baseErrorArg}).int(${intErrorArg})${constraints}`;
161
+ return `${zodWireNumber("integer", baseErrorArg)}.pipe(${inner})`;
93
162
  }
163
+ if (numberChain) return `z.coerce.number(${baseErrorArg}).int(${errorMessage ? zodError(errorMessage) : ""})${constraints}`;
94
164
  if (numberPipe) return `z.coerce.number(${baseErrorArg}).pipe(${innerChain})`;
95
- if (is64) return `${int64Input(isCoerce, baseErrorArg)}.pipe(${innerChain})`;
165
+ if (is64) return `${int64Input(readsText, baseErrorArg)}.pipe(${innerChain})`;
96
166
  return innerChain;
97
167
  }
98
168
  //#endregion
@@ -148,62 +218,6 @@ function _enum(schema) {
148
218
  return outerLit(schema.enum[0]);
149
219
  }
150
220
  //#endregion
151
- //#region src/generator/zod/number.ts
152
- /**
153
- * Generates a Zod schema for number types (number / float32 / float64), with
154
- * min/max/multipleOf constraints and `x-*-message` vendor extensions translated
155
- * to Zod v4 `{error: "msg"}` parameters.
156
- */
157
- function number(schema) {
158
- const errorMessage = schema["x-error-message"];
159
- const requiredMessage = schema["x-required-message"];
160
- const isCoerce = schema["x-coerce"] === true;
161
- const baseErrorArg = zodBaseError(errorMessage, isCoerce ? void 0 : requiredMessage);
162
- const isFloat32 = schema.format === "float" || schema.format === "float32";
163
- const isFloat64 = schema.format === "float64";
164
- const wirePipe = isCoerce && (isFloat32 || isFloat64);
165
- const base = isCoerce && !isFloat32 && !isFloat64 ? `z.coerce.number(${baseErrorArg})` : isFloat32 ? `z.float32(${baseErrorArg})` : isFloat64 ? `z.float64(${baseErrorArg})` : `z.number(${baseErrorArg})`;
166
- const minimumMessage = schema["x-minimum-message"];
167
- const exclusiveMinMessage = schema["x-exclusiveMinimum-message"];
168
- const minErrorArg = minimumMessage ? zodError(minimumMessage) : "";
169
- const minErrorPart = minErrorArg ? `,${minErrorArg}` : "";
170
- const exMinErrorArg = exclusiveMinMessage ? zodError(exclusiveMinMessage) : "";
171
- const exMinErrorPart = exMinErrorArg ? `,${exMinErrorArg}` : "";
172
- const minimum = (() => {
173
- if (schema.minimum !== void 0) {
174
- if (schema.minimum === 0 && schema.exclusiveMinimum === true) return `.positive(${exMinErrorArg})`;
175
- if (schema.minimum === 0 && schema.exclusiveMinimum === false) return `.nonnegative(${minErrorArg})`;
176
- if (schema.exclusiveMinimum === true) return `.gt(${schema.minimum}${exMinErrorPart})`;
177
- return `.min(${schema.minimum}${minErrorPart})`;
178
- }
179
- if (typeof schema.exclusiveMinimum === "number") return `.gt(${schema.exclusiveMinimum}${exMinErrorPart})`;
180
- })();
181
- const maximumMessage = schema["x-maximum-message"];
182
- const exclusiveMaxMessage = schema["x-exclusiveMaximum-message"];
183
- const maxErrorArg = maximumMessage ? zodError(maximumMessage) : "";
184
- const maxErrorPart = maxErrorArg ? `,${maxErrorArg}` : "";
185
- const exMaxErrorArg = exclusiveMaxMessage ? zodError(exclusiveMaxMessage) : "";
186
- const exMaxErrorPart = exMaxErrorArg ? `,${exMaxErrorArg}` : "";
187
- const maximum = (() => {
188
- if (schema.maximum !== void 0) {
189
- if (schema.maximum === 0 && schema.exclusiveMaximum === true) return `.negative(${exMaxErrorArg})`;
190
- if (schema.maximum === 0 && schema.exclusiveMaximum === false) return `.nonpositive(${maxErrorArg})`;
191
- if (schema.exclusiveMaximum === true) return `.lt(${schema.maximum}${exMaxErrorPart})`;
192
- return `.max(${schema.maximum}${maxErrorPart})`;
193
- }
194
- if (typeof schema.exclusiveMaximum === "number") return `.lt(${schema.exclusiveMaximum}${exMaxErrorPart})`;
195
- })();
196
- const multipleOfMessage = schema["x-multipleOf-message"];
197
- const multipleOfErrorArg = multipleOfMessage ? `,${zodError(multipleOfMessage)}` : baseErrorArg ? `,${baseErrorArg}` : "";
198
- const innerChain = [
199
- base,
200
- minimum,
201
- maximum,
202
- schema.multipleOf !== void 0 ? `.multipleOf(${schema.multipleOf}${multipleOfErrorArg})` : void 0
203
- ].filter((v) => v !== void 0).join("");
204
- return wirePipe ? `z.coerce.number(${baseErrorArg}).pipe(${innerChain})` : innerChain;
205
- }
206
- //#endregion
207
221
  //#region src/generator/zod/object.ts
208
222
  /**
209
223
  * A parameter object answers an `Object.prototype` name it was not sent with the inherited
@@ -236,19 +250,23 @@ function object(schema, rootName, isZod, options) {
236
250
  const depReqErrorArg = depReqMessage ? `,${zodError(depReqMessage)}` : errorArg;
237
251
  const depSchMessage = schema["x-dependentSchemas-message"];
238
252
  const depSchErrorArg = depSchMessage ? `,${zodError(depSchMessage)}` : errorArg;
239
- if (typeof schema.additionalProperties === "object") return `${`z.record(z.string(),${zod(schema.additionalProperties, rootName, isZod, options)})`}${schema.propertyNames?.pattern ? `.refine((val)=>Object.keys(val).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})` : schema.propertyNames?.enum ? `.refine((val)=>Object.keys(val).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})` : ""}${schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
240
- const z = zod(propSchema, rootName, isZod, options);
241
- return `.refine((val)=>Object.entries(val).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||${z}.safeParse(value).success)${patternErrorArg})`;
242
- }).join("") : ""}`;
253
+ if (typeof schema.additionalProperties === "object" && schema.properties === void 0 && schema.patternProperties === void 0) return `${`z.record(z.string(),${zod(schema.additionalProperties, rootName, isZod, options)})`}${schema.propertyNames?.pattern ? `.refine((val)=>Object.keys(val).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})` : schema.propertyNames?.enum ? `.refine((val)=>Object.keys(val).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})` : ""}`;
254
+ const properties = schema.properties ?? {};
255
+ const undeclaredRequired = (schema.required ?? []).filter((key) => !Object.hasOwn(properties, key));
256
+ const unevaluated = schema.unevaluatedProperties;
257
+ const closed = schema.additionalProperties === false || unevaluated === false;
258
+ const closedByCheck = closed && schema.patternProperties !== void 0;
259
+ const extraSchema = typeof schema.additionalProperties === "object" ? schema.additionalProperties : typeof unevaluated === "object" ? unevaluated : void 0;
260
+ const extraMessage = typeof schema.additionalProperties === "object" ? schema["x-additionalProperties-message"] : schema["x-unevaluatedProperties-message"];
243
261
  if (!schema.properties) {
244
262
  if (schema.additionalProperties === true) return "z.any()";
245
- return "z.object({})";
263
+ if (!(undeclaredRequired.length > 0 || schema.patternProperties !== void 0 || extraSchema !== void 0 || closed)) return "z.object({})";
246
264
  }
247
- const conditionalKeysReferenced = hasConditional(schema);
248
- const objectType = schema.additionalProperties === true ? "looseObject" : schema.additionalProperties === false || schema.unevaluatedProperties === false ? "strictObject" : conditionalKeysReferenced ? "looseObject" : "object";
265
+ const readsUndeclaredKeys = hasConditional(schema) || schema.patternProperties !== void 0 || schema.propertyNames !== void 0 || schema.minProperties !== void 0 || schema.maxProperties !== void 0 || schema.dependentRequired !== void 0 || schema.dependentSchemas !== void 0 || undeclaredRequired.length > 0 || extraSchema !== void 0 || closedByCheck;
266
+ const objectType = schema.additionalProperties === true ? "looseObject" : closed && !closedByCheck ? "strictObject" : readsUndeclaredKeys ? "looseObject" : "object";
249
267
  const required = new Set(schema.required);
250
- const props = Object.entries(schema.properties).map(([key, propSchema]) => {
251
- const parsed = zod(propSchema, rootName, isZod, options);
268
+ const props = Object.entries(properties).map(([key, propSchema]) => {
269
+ const parsed = zod(propSchema, rootName, isZod, propertyEmitOptions(key, propSchema, options) ?? options);
252
270
  if (!parsed) return null;
253
271
  return `${makeSafeKey(key)}:${parsed}${required.has(key) ? "" : ".exactOptional()"}`;
254
272
  }).filter((v) => v !== null);
@@ -256,17 +274,21 @@ function object(schema, rootName, isZod, options) {
256
274
  const objectParams = objectType === "strictObject" && strictMessage ? `,{error:(issue)=>issue.code==='unrecognized_keys'?${JSON.stringify(strictMessage)}:${errorMessage ? JSON.stringify(errorMessage) : "undefined"}}` : "";
257
275
  const rawBase = `z.${objectType}({${props.join(",")}}${objectParams})`;
258
276
  const propsMessage = schema["x-properties-message"];
259
- const objectExpr = `${propsMessage ? (() => {
260
- const msgExpr = issueMessageExpression(propsMessage);
261
- return `(()=>{const Schema=${rawBase};return z.unknown().check((ctx)=>{const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){if(issue.path.length>0){ctx.issues.push({...issue,message:${msgExpr}})}else{ctx.issues.push(issue)}}}}).pipe(Schema)})()`;
262
- })() : rawBase}${typeof schema.minProperties === "number" ? `.refine((val)=>Object.keys(val).length>=${schema.minProperties}${minErrorArg})` : ""}${typeof schema.maxProperties === "number" ? `.refine((val)=>Object.keys(val).length<=${schema.maxProperties}${maxErrorArg})` : ""}${schema.propertyNames?.pattern ? `.refine((val)=>Object.keys(val).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})` : schema.propertyNames?.enum ? `.refine((val)=>Object.keys(val).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})` : ""}${schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
277
+ const partialBase = propsMessage ? nestedIssueMessageWrap(rawBase, propsMessage) : rawBase;
278
+ const minProperties = typeof schema.minProperties === "number" ? `.refine((val)=>Object.keys(val).length>=${schema.minProperties}${minErrorArg})` : "";
279
+ const maxProperties = typeof schema.maxProperties === "number" ? `.refine((val)=>Object.keys(val).length<=${schema.maxProperties}${maxErrorArg})` : "";
280
+ const propertyNames = schema.propertyNames?.pattern ? `.refine((val)=>Object.keys(val).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})` : schema.propertyNames?.enum ? `.refine((val)=>Object.keys(val).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})` : "";
281
+ const patternProperties = schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
263
282
  const z = zod(propSchema, rootName, isZod, options);
264
283
  return `.refine((val)=>Object.entries(val).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||${z}.safeParse(value).success)${patternErrorArg})`;
265
- }).join("") : ""}${schema.dependentRequired ? Object.entries(schema.dependentRequired).map(([key, deps]) => {
284
+ }).join("") : "";
285
+ const dependentRequired = schema.dependentRequired ? Object.entries(schema.dependentRequired).map(([key, deps]) => {
266
286
  return `.refine((val)=>!('${key}' in val)||(${deps.map((d) => `'${d}' in val`).join("&&")})${depReqErrorArg})`;
267
- }).join("") : ""}${schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
287
+ }).join("") : "";
288
+ const dependentSchemas = schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
268
289
  return `.refine((val)=>!('${key}' in val)||${zod(subSchema, rootName, isZod, options)}.safeParse(val).success${depSchErrorArg})`;
269
- }).join("") : ""}${(() => {
290
+ }).join("") : "";
291
+ const ifThenElse = (() => {
270
292
  if (!schema.if) return "";
271
293
  const ifS = zod(schema.if, rootName, isZod, options);
272
294
  const thenS = schema.then ? zod(schema.then, rootName, isZod, options) : void 0;
@@ -285,8 +307,14 @@ function object(schema, rootName, isZod, options) {
285
307
  parts.push(`.refine((val)=>${ifS}.safeParse(val).success||${elseS}.safeParse(val).success${arg})`);
286
308
  }
287
309
  return parts.join("");
288
- })()}`;
289
- const hasInheritedName = Object.keys(schema.properties).some(isObjectPrototypeProperty);
310
+ })();
311
+ const requiredPresent = undeclaredRequired.length > 0 ? `.refine((val)=>${JSON.stringify(undeclaredRequired)}.every((key)=>key in val)${errorArg})` : "";
312
+ const isEvaluated = isEvaluatedKeyExpression({
313
+ names: Object.keys(properties),
314
+ patterns: Object.keys(schema.patternProperties ?? {})
315
+ }, "key");
316
+ const objectExpr = `${partialBase}${minProperties}${maxProperties}${propertyNames}${patternProperties}${requiredPresent}${closedByCheck ? `.refine((val)=>Object.keys(val).every((key)=>${isEvaluated})${zodErrorPart(strictMessage ?? errorMessage)})` : extraSchema !== void 0 ? `.refine((val)=>Object.entries(val).every(([key,value])=>${isEvaluated}||${zod(extraSchema, rootName, isZod, options)}.safeParse(value).success)${zodErrorPart(extraMessage ?? errorMessage)})` : ""}${dependentRequired}${dependentSchemas}${ifThenElse}`;
317
+ const hasInheritedName = Object.keys(properties).some(isObjectPrototypeProperty);
290
318
  return isStringWireLocation(options?.paramIn) && hasInheritedName ? `z.preprocess(${OWN_PROPERTIES_PREPROCESS},${objectExpr})` : objectExpr;
291
319
  }
292
320
  //#endregion
@@ -524,15 +552,27 @@ const ZOD_ISSUE_CODES = [
524
552
  * The `not` predicate of an inner schema, as the source of a `(val) => ...` arrow, or
525
553
  * `undefined` when the inner schema has none this generator can express.
526
554
  */
527
- function zodNotPredicate(inner) {
555
+ function zodNotPredicate(inner, parent) {
528
556
  if (inner.$ref) return void 0;
529
- const shared = notPredicate(inner, "val");
557
+ const bigint = isBigintFormat(parent);
558
+ const shared = notPredicate(inner, "val", "val", bigint);
530
559
  if (shared !== void 0) return shared;
531
- if (Array.isArray(inner.enum)) return `(val) => !${JSON.stringify(inner.enum)}.includes(val)`;
560
+ if (Array.isArray(inner.enum)) return `(val) => !${valueListLiteral(inner.enum, bigint)}.includes(val)`;
532
561
  if (inner.oneOf || inner.anyOf || inner.allOf) return `(val) => !${zod(inner)}.safeParse(val).success`;
533
562
  }
563
+ /**
564
+ * Re-push `issue` into `ctx` with `message`. Each issue code is narrowed first: the union of
565
+ * parsed issues does not type-check as a raw issue, while each member does.
566
+ */
567
+ function forwardIssue(message) {
568
+ return ZOD_ISSUE_CODES.map((c, i) => `${i === 0 ? "" : "else "}if(issue.code==='${c}'){ctx.issues.push({...issue,input:issue.input,message:${message}})}`).join("");
569
+ }
570
+ /** A message for the issues under the value (with a path); the root's own issues keep theirs. */
571
+ function nestedIssueMessageWrap(inner, msg) {
572
+ return `(()=>{const Schema=${inner};return z.unknown().check((ctx)=>{const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){${forwardIssue(`issue.path.length>0?${issueMessageExpression(msg)}:issue.message`)}}}}).pipe(Schema)})()`;
573
+ }
534
574
  function elementMessageWrap(inner, msg) {
535
- return `(()=>{const Schema=${inner};return z.unknown().check((ctx)=>{const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){if(issue.path.length>0){ctx.issues.push({...issue,message:${issueMessageExpression(msg)}})}else{ctx.issues.push(issue)}}}}).pipe(Schema)})()`;
575
+ return nestedIssueMessageWrap(inner, msg);
536
576
  }
537
577
  /**
538
578
  * Generate Zod schema code from JSON Schema.
@@ -549,21 +589,45 @@ function zod(schema, rootName = DEFAULT_ROOT_NAME, isZod = false, options) {
549
589
  const nullFirst = isNullMatchedFirst(schema) ? expression : `${expression}.nullable()`;
550
590
  return `z.preprocess(${wireNullText("val")},${nullFirst})`;
551
591
  }
592
+ /** A keyword-only `allOf` member: the keywords apply when the value has their type. */
593
+ function keywordConstraint(schema) {
594
+ return `z.any().refine((val) => ${constraintPredicate(schema, "val")}${zodErrorPart(constraintMessage(schema))})`;
595
+ }
596
+ /** Push a key's issues (`result`, for the value `v` under key `k`) under that key. */
597
+ function forwardKeyIssues(message) {
598
+ return `for(const issue of result.error.issues){ctx.issues.push({code:'custom',input:v,path:[k,...issue.path],message:${message === void 0 ? "issue.message" : JSON.stringify(message)}})}`;
599
+ }
600
+ /**
601
+ * An `allOf` with `patternProperties` or `unevaluatedProperties` beside it: the members'
602
+ * objects strip what they do not declare, so the keys are checked on the input before it
603
+ * is parsed — a key a pattern matches against that pattern's schema, a key no member
604
+ * evaluates against `unevaluatedProperties`. `inner` as given when there is nothing to check.
605
+ */
606
+ function objectKeysCheck(inner, schema, rootName, isZod, options) {
607
+ const patterns = Object.entries(schema.patternProperties ?? {});
608
+ const unevaluated = schema.unevaluatedProperties;
609
+ const unevaluatedSchema = typeof unevaluated === "object" ? unevaluated : void 0;
610
+ const evaluated = unevaluated === false || unevaluatedSchema !== void 0 ? evaluatedProperties(schema, options?.definitions) : void 0;
611
+ if (patterns.length === 0 && evaluated === void 0) return inner;
612
+ const patternMessage = schema["x-patternProperties-message"];
613
+ const patternChecks = patterns.map(([pattern, propSchema]) => `if(new RegExp(${JSON.stringify(pattern)}).test(k)){const result=${zod(propSchema, rootName, isZod, options)}.safeParse(v);if(!result.success){${forwardKeyIssues(patternMessage)}}}`).join("");
614
+ const message = schema["x-unevaluatedProperties-message"];
615
+ return `(()=>{const Schema=${inner};return z.unknown().check((ctx)=>{const o=ctx.value;if(typeof o!=='object'||o===null||Array.isArray(o))return;for(const [k,v] of Object.entries(o)){${patternChecks}${evaluated === void 0 ? "" : `if(!(${isEvaluatedKeyExpression(evaluated, "k")})){${unevaluatedSchema === void 0 ? `ctx.issues.push({code:'custom',input:o,path:[k],message:${message === void 0 ? "`Unrecognized key: \"${k}\"`" : JSON.stringify(message)}})` : `const result=${zod(unevaluatedSchema, rootName, isZod, options)}.safeParse(v);if(!result.success){${forwardKeyIssues(message)}}`}}`}}}).pipe(Schema)})()`;
616
+ }
552
617
  function node(schema, rootName, isZod, options) {
553
618
  const isStringWireParam = isStringWireLocation(options?.paramIn);
554
619
  const isWireCoerced = isStringWireParam && schema["x-coerce"] !== false;
555
- const withForcedCoerce = (s) => isStringWireParam && s["x-coerce"] !== false ? {
556
- ...s,
557
- "x-coerce": true
558
- } : s;
559
620
  const codeExtOpts = options?.unsafeCodeExtensions === true ? { unsafeCodeExtensions: true } : {};
560
- const zodWrap$1 = (zodStr, s) => zodWrap(zodStr, s, codeExtOpts);
621
+ const zodWrap$1 = (zodStr, s) => zodWrap(zodStr, s, {
622
+ ...codeExtOpts,
623
+ ...options?.definitions !== void 0 && { definitions: options.definitions }
624
+ });
561
625
  const readonly = (v) => options?.readonly ? `${v}.readonly()` : v;
562
626
  const wireArray = (v) => isStringWireParam ? `z.preprocess(${wireArrayOnce("val")},${v})` : v;
563
627
  const literalInput = (values) => {
564
628
  if (values.every((v) => typeof v === "number")) {
565
629
  if (isInt64(schema)) return int64Input(isWireCoerced);
566
- if (isWireCoerced) return "z.coerce.number()";
630
+ if (isWireCoerced) return zodWireNumber(wireNumericKind(schema, values));
567
631
  }
568
632
  if (isWireCoerced && values.every((v) => typeof v === "boolean")) return "z.stringbool()";
569
633
  };
@@ -586,11 +650,18 @@ function node(schema, rootName, isZod, options) {
586
650
  }, rootName, isZod, options);
587
651
  if (schema.oneOf) {
588
652
  if (schema.oneOf.length === 0) return zodWrap$1("z.any()", schema);
589
- const schemas = schema.oneOf.map((s) => zod(s, rootName, isZod, options));
590
- const oneOfMessage = schema["x-oneOf-message"];
591
- const errorPart = zodErrorPart(oneOfMessage);
592
653
  const discriminator = schema.discriminator?.propertyName;
593
654
  const hasRefOrAllOf = schema.oneOf.some((s) => s.$ref !== void 0 || s.allOf !== void 0);
655
+ const discriminated = hasRefOrAllOf ? discriminatedMembers(schema, schema.oneOf) : void 0;
656
+ const schemas = schema.oneOf.map((s, i) => {
657
+ const member = zod(s, rootName, isZod, options);
658
+ const values = discriminated?.members[i]?.values;
659
+ if (discriminated === void 0 || values === void 0) return member;
660
+ const literal = values.length === 1 ? `z.literal(${JSON.stringify(values[0])})` : `z.enum(${JSON.stringify(values)})`;
661
+ return `z.intersection(${member},z.object({${makeSafeKey(discriminated.propertyName)}:${literal}}))`;
662
+ });
663
+ const oneOfMessage = schema["x-oneOf-message"];
664
+ const errorPart = zodErrorPart(oneOfMessage);
594
665
  return zodWrap$1(discriminator && !hasRefOrAllOf ? `z.discriminatedUnion('${discriminator}',[${schemas.join(",")}]${errorPart})` : isWireCoerced ? `z.union([${schemas.join(",")}]${errorPart})` : `z.xor([${schemas.join(",")}]${errorPart})`, schema);
595
666
  }
596
667
  if (schema.anyOf) {
@@ -604,20 +675,19 @@ function node(schema, rootName, isZod, options) {
604
675
  if (schema.allOf.length === 0) return zodWrap$1("z.any()", schema);
605
676
  const nullable = isNullable(schema) || schema.allOf.some(isNullTypeMember);
606
677
  const defaultValue = schema.allOf.find(isDefaultOnlyMember)?.default;
607
- const schemas = schema.allOf.filter((s) => !isShapelessMember(s)).map((s) => zod(s, rootName, isZod, options));
678
+ const schemas = foldAllOfMembers(schema.allOf.filter((s) => !isShapelessMember(s)), isWireCoerced).map((s) => isKeywordOnlyMember(s) ? keywordConstraint(s) : zod(s, rootName, isZod, options));
608
679
  if (schemas.length === 0) return zodWrap$1("z.any()", {
609
680
  ...schema,
610
681
  nullable
611
682
  });
612
683
  const intersected = schemas.length === 1 ? schemas[0] : schemas.reduce((acc, s) => `z.intersection(${acc},${s})`);
613
684
  const allOfMessage = schema["x-allOf-message"];
614
- const baseResult = allOfMessage ? (() => {
615
- const msgExpr = issueMessageExpression(allOfMessage);
616
- const branches = ZOD_ISSUE_CODES.map((c, i) => `${i === 0 ? "" : "else "}if(issue.code==='${c}'){ctx.issues.push({...issue,input:issue.input,message:${msgExpr}})}`).join("");
685
+ const checked = objectKeysCheck(allOfMessage ? (() => {
686
+ const branches = forwardIssue(issueMessageExpression(allOfMessage));
617
687
  return `(()=>{const Schema=${intersected};return z.unknown().check((ctx)=>{const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){${branches}}}}).pipe(Schema)})()`;
618
- })() : intersected;
688
+ })() : intersected, schema, rootName, isZod, options);
619
689
  const mergedDefault = defaultValue !== void 0 ? defaultValue : schema.default;
620
- return zodWrap$1(baseResult, {
690
+ return zodWrap$1(checked, {
621
691
  ...schema,
622
692
  nullable,
623
693
  ...mergedDefault !== void 0 && { default: mergedDefault }
@@ -628,7 +698,7 @@ function node(schema, rootName, isZod, options) {
628
698
  const errorPart = zodErrorPart(notMessage);
629
699
  const { not: inner, ...withoutNot } = schema;
630
700
  if (typeof inner !== "object" || inner === null) return zodWrap$1("z.any()", schema);
631
- const predicate = inner.$ref ? `(val) => !${ref(inner, "", false)}.safeParse(val).success` : zodNotPredicate(inner);
701
+ const predicate = inner.$ref ? `(val) => !${ref(inner, "", false)}.safeParse(val).success` : zodNotPredicate(inner, withoutNot);
632
702
  if (withoutNot.type !== void 0) {
633
703
  const base = zod(withoutNot, rootName, isZod, options);
634
704
  return predicate ? `${base}.refine(${predicate}${errorPart})` : base;
@@ -659,8 +729,8 @@ function node(schema, rootName, isZod, options) {
659
729
  const types = normalizeTypes(schema.type);
660
730
  const primitive = (t) => {
661
731
  if (t === "string") return string(schema);
662
- if (t === "number") return number(withForcedCoerce(schema));
663
- if (t === "integer") return integer(withForcedCoerce(schema));
732
+ if (t === "number") return number(schema, { wire: isWireCoerced });
733
+ if (t === "integer") return integer(schema, { wire: isWireCoerced });
664
734
  if (t !== "boolean") return void 0;
665
735
  const errorMessage = schema["x-error-message"];
666
736
  const errorArg = errorMessage ? zodError(errorMessage) : "";
@@ -744,6 +814,7 @@ function node(schema, rootName, isZod, options) {
744
814
  const errorMessage = schema["x-error-message"];
745
815
  return zodWrap$1(`z.null(${errorMessage ? zodError(errorMessage) : ""})`, schema);
746
816
  }
817
+ if (typeof schema.additionalProperties === "object") return readonly(zodWrap$1(object(schema, rootName, isZod, options), schema));
747
818
  return zodWrap$1("z.any()", schema);
748
819
  }
749
820
  //#endregion
@@ -752,12 +823,18 @@ function node(schema, rootName, isZod, options) {
752
823
  * A whole JSON Schema document as a Zod module: imports, `$defs` in dependency order,
753
824
  * the root export, and the inferred type.
754
825
  */
755
- function schemaToZod(schema, options) {
826
+ function schemaToZod(input, options) {
827
+ const schema = withPolymorphicBases(hoistNestedRefs(input));
756
828
  const exportType = options?.exportType ?? true;
757
- const emitOptions = emitOptionsOf(options);
758
- const codeExtensionsPresent = emitOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0;
759
- const toName = schemaNamer(emitOptions.openapi);
829
+ const baseOptions = emitOptionsOf(options);
830
+ const codeExtensionsPresent = baseOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0;
831
+ const toName = schemaNamer(baseOptions.openapi);
760
832
  const plan = planDocument(schema, rootNameOf(schema, toName));
833
+ const definitions = definitionsOf(baseOptions, plan.definitions);
834
+ const emitOptions = definitions === void 0 ? baseOptions : {
835
+ ...baseOptions,
836
+ definitions
837
+ };
761
838
  const { rootName } = plan;
762
839
  const needsTypeDef = plan.hasDefinitions || hasRootSelfReference(schema);
763
840
  const typeDefsCode = needsTypeDef ? [`type _${rootName} = ${type(plan.root, rootName)}`, renderDefinitions(plan, toName, (def, name) => `type _${name} = ${type(def, name)}`)].filter(Boolean).join("\n\n") : "";
@@ -774,4 +851,4 @@ function schemaToZod(schema, options) {
774
851
  ].filter(Boolean).join("\n\n");
775
852
  }
776
853
  //#endregion
777
- export { zod as n, schemaToZod as t };
854
+ export { zod as i, forwardIssue as n, nestedIssueMessageWrap as r, schemaToZod as t };
package/dist/zod.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { r as JSONSchema } from "./index-DbV3dEmN.js";
2
- import { n as GenerateOptions } from "./index-C2L8Ty0-.js";
1
+ import { r as JSONSchema } from "./index-G7UqNQ4w.js";
2
+ import { n as GenerateOptions } from "./index-EK43HM_z.js";
3
3
  //#region src/generator/zod/index.d.ts
4
4
  /**
5
5
  * A whole JSON Schema document as a Zod module: imports, `$defs` in dependency order,
6
6
  * the root export, and the inferred type.
7
7
  */
8
- export declare function schemaToZod(schema: JSONSchema, options?: GenerateOptions): string;
8
+ export declare function schemaToZod(input: JSONSchema, options?: GenerateOptions): string;
9
9
  //#endregion
package/dist/zod.js CHANGED
@@ -1 +1 @@
1
- export { t as schemaToZod } from "./zod-BsXLZfwK.js";
1
+ export { t as schemaToZod } from "./zod-CXo9NFuF.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "schema-truth",
3
- "version": "0.7.0",
3
+ "version": "0.8.2",
4
4
  "description": "Generate Zod/Valibot/Effect/TypeBox/ArkType/Ajv/Yup schemas from JSON or YAML files",
5
5
  "keywords": [
6
6
  "ajv",