schema-truth 0.0.0-stage → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +143 -2
- package/dist/ajv-DS9gtNZC.js +105 -0
- package/dist/ajv.d.ts +24 -0
- package/dist/ajv.js +1 -0
- package/dist/arktype-CRZ8vXZ5.js +803 -0
- package/dist/arktype.d.ts +10 -0
- package/dist/arktype.js +1 -0
- package/dist/cli/ajv.d.ts +1 -0
- package/dist/cli/ajv.js +15 -0
- package/dist/cli/arktype.d.ts +1 -0
- package/dist/cli/arktype.js +15 -0
- package/dist/cli/effect.d.ts +1 -0
- package/dist/cli/effect.js +15 -0
- package/dist/cli/typebox.d.ts +1 -0
- package/dist/cli/typebox.js +15 -0
- package/dist/cli/valibot.d.ts +1 -0
- package/dist/cli/valibot.js +15 -0
- package/dist/cli/yup.d.ts +1 -0
- package/dist/cli/yup.js +15 -0
- package/dist/cli/zod.d.ts +1 -0
- package/dist/cli/zod.js +15 -0
- package/dist/cli-eAY8LqwP.js +124 -0
- package/dist/effect-BkWovUi3.js +678 -0
- package/dist/effect.d.ts +12 -0
- package/dist/effect.js +1 -0
- package/dist/helper-CbeedY35.js +1798 -0
- package/dist/index-DYzAccyT.d.ts +69 -0
- package/dist/index-G7UqNQ4w.d.ts +603 -0
- package/dist/index.d.ts +332 -0
- package/dist/index.js +10 -0
- package/dist/parser-CyJ2auea.js +36 -0
- package/dist/typebox-wYeJqy7T.js +563 -0
- package/dist/typebox.d.ts +21 -0
- package/dist/typebox.js +1 -0
- package/dist/utils-Bky98UmP.js +1146 -0
- package/dist/valibot-DQUEDYKt.js +705 -0
- package/dist/valibot.d.ts +9 -0
- package/dist/valibot.js +1 -0
- package/dist/yup-BMpa9Co1.js +92 -0
- package/dist/yup.d.ts +17 -0
- package/dist/yup.js +1 -0
- package/dist/zod-Dq9LtqPL.js +816 -0
- package/dist/zod.d.ts +9 -0
- package/dist/zod.js +1 -0
- package/package.json +112 -4
|
@@ -0,0 +1,816 @@
|
|
|
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, O as unionPrimitiveTypes, P as timePattern, Q as findCodeExtensionKeysInSchema, S as isNullTextRead, U as renderDefinitions, W as rootNameOf, Y as itemsSchemaOf, at as regexLiteral, b as integerWirePattern, c as withPolymorphicBases, d as propertyEmitOptions, et as constraintMessage, f as withoutParameterSerialization, g as hoistNestedRefs, h as valueListLiteral, i as isEvaluatedKeyExpression, j as wireNumericKind, k as wireArrayOnce, l as hasParameterSerialization, m as notPredicate, nt as foldAllOfMembers, o as typeDeclaration, p as isBigintFormat, q as hasRootSelfReference, r as evaluatedProperties, rt as isKeywordOnlyMember, s as refTarget, t as zodWrap, tt as constraintPredicate, u as parameterReaders, w as numberWirePattern, x as isNullMatchedFirst, y as impliedWireType, z as definitionsOf } from "./helper-CbeedY35.js";
|
|
3
|
+
//#region src/generator/zod/type.ts
|
|
4
|
+
/** The TypeScript type declared beside a recursive Zod schema. */
|
|
5
|
+
function type(schema, rootName = DEFAULT_ROOT_NAME) {
|
|
6
|
+
return typeDeclaration(schema, {
|
|
7
|
+
inferRoot: (name) => `z.infer<typeof ${name}>`,
|
|
8
|
+
readonly: false
|
|
9
|
+
}, rootName);
|
|
10
|
+
}
|
|
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
|
|
77
|
+
//#region src/generator/zod/integer.ts
|
|
78
|
+
/** Whether a node is a 64-bit integer: a value beyond 2^53 that Zod reads as a bigint. */
|
|
79
|
+
function isInt64(schema) {
|
|
80
|
+
return schema.format === "int64" || schema.format === "uint64";
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* What reads a 64-bit integer into a bigint ahead of the check. On the string wire the text
|
|
84
|
+
* is coerced; in a JSON body the value is a safe-integer number, or the string of digits
|
|
85
|
+
* that is the only lossless way to carry a larger one, and nothing else.
|
|
86
|
+
*/
|
|
87
|
+
function int64Input(isWire, baseErrorArg = "") {
|
|
88
|
+
if (isWire) return `z.coerce.bigint(${baseErrorArg})`;
|
|
89
|
+
const errorPart = baseErrorArg ? `,${baseErrorArg}` : "";
|
|
90
|
+
return String.raw`z.union([z.bigint(),z.number().int(),z.string().regex(/^-?\d+$/)]${errorPart}).transform((val)=>BigInt(val))`;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Generates a Zod schema for integer types (int / int32 / uint32 / int64 / bigint), with
|
|
94
|
+
* min/max/multipleOf constraints and `x-*-message` vendor extensions translated
|
|
95
|
+
* to Zod v4 `{error: "msg"}` parameters.
|
|
96
|
+
*/
|
|
97
|
+
function integer(schema, options) {
|
|
98
|
+
const isWire = options?.wire === true;
|
|
99
|
+
const errorMessage = schema["x-error-message"];
|
|
100
|
+
const requiredMessage = schema["x-required-message"];
|
|
101
|
+
const isCoerce = schema["x-coerce"] === true && !isWire;
|
|
102
|
+
const readsText = isCoerce || isWire;
|
|
103
|
+
const baseErrorArg = zodBaseError(errorMessage, readsText ? void 0 : requiredMessage);
|
|
104
|
+
const isBigint = schema.format === "bigint";
|
|
105
|
+
const isInt32 = schema.format === "int32" || schema.format === "uint32";
|
|
106
|
+
const is64 = isInt64(schema);
|
|
107
|
+
const bigintBase = readsText && isBigint;
|
|
108
|
+
const numberPipe = isCoerce && isInt32;
|
|
109
|
+
const numberChain = isCoerce && !isBigint && !is64 && !isInt32;
|
|
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})`;
|
|
111
|
+
const lit = (n) => {
|
|
112
|
+
if (schema.format === "bigint") return `BigInt(${n})`;
|
|
113
|
+
if (is64) return `${n}n`;
|
|
114
|
+
return `${n}`;
|
|
115
|
+
};
|
|
116
|
+
const minimumMessage = schema["x-minimum-message"] ?? errorMessage;
|
|
117
|
+
const exclusiveMinMessage = schema["x-exclusiveMinimum-message"] ?? errorMessage;
|
|
118
|
+
const minErrorArg = minimumMessage ? zodError(minimumMessage) : "";
|
|
119
|
+
const minErrorPart = minErrorArg ? `,${minErrorArg}` : "";
|
|
120
|
+
const exMinErrorArg = exclusiveMinMessage ? zodError(exclusiveMinMessage) : "";
|
|
121
|
+
const exMinErrorPart = exMinErrorArg ? `,${exMinErrorArg}` : "";
|
|
122
|
+
const minimum = (() => {
|
|
123
|
+
if (schema.minimum === void 0 && schema.exclusiveMinimum === void 0) return;
|
|
124
|
+
const value = schema.minimum ?? schema.exclusiveMinimum;
|
|
125
|
+
if (value === 0 && schema.exclusiveMinimum === true) return `.positive(${exMinErrorArg})`;
|
|
126
|
+
if (value === 0 && schema.exclusiveMinimum === false) return `.nonnegative(${minErrorArg})`;
|
|
127
|
+
if ((schema.exclusiveMinimum === true || schema.minimum === void 0) && typeof value === "number") return `.gt(${lit(value)}${exMinErrorPart})`;
|
|
128
|
+
if (typeof schema.minimum === "number") return `.min(${lit(schema.minimum)}${minErrorPart})`;
|
|
129
|
+
})();
|
|
130
|
+
const maximumMessage = schema["x-maximum-message"] ?? errorMessage;
|
|
131
|
+
const exclusiveMaxMessage = schema["x-exclusiveMaximum-message"] ?? errorMessage;
|
|
132
|
+
const maxErrorArg = maximumMessage ? zodError(maximumMessage) : "";
|
|
133
|
+
const maxErrorPart = maxErrorArg ? `,${maxErrorArg}` : "";
|
|
134
|
+
const exMaxErrorArg = exclusiveMaxMessage ? zodError(exclusiveMaxMessage) : "";
|
|
135
|
+
const exMaxErrorPart = exMaxErrorArg ? `,${exMaxErrorArg}` : "";
|
|
136
|
+
const maximum = (() => {
|
|
137
|
+
if (schema.maximum === void 0 && schema.exclusiveMaximum === void 0) return;
|
|
138
|
+
const value = schema.maximum ?? schema.exclusiveMaximum;
|
|
139
|
+
if (value === 0 && schema.exclusiveMaximum === true) return `.negative(${exMaxErrorArg})`;
|
|
140
|
+
if (value === 0 && schema.exclusiveMaximum === false) return `.nonpositive(${maxErrorArg})`;
|
|
141
|
+
if ((schema.exclusiveMaximum === true || schema.maximum === void 0) && typeof value === "number") return `.lt(${lit(value)}${exMaxErrorPart})`;
|
|
142
|
+
if (typeof schema.maximum === "number") return `.max(${lit(schema.maximum)}${maxErrorPart})`;
|
|
143
|
+
})();
|
|
144
|
+
const multipleOfMessage = schema["x-multipleOf-message"] ?? errorMessage;
|
|
145
|
+
const multipleOfErrorArg = zodErrorPart(multipleOfMessage);
|
|
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("");
|
|
152
|
+
const innerChain = [
|
|
153
|
+
base,
|
|
154
|
+
minimum,
|
|
155
|
+
maximum,
|
|
156
|
+
multipleOf
|
|
157
|
+
].filter((v) => v !== void 0).join("");
|
|
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})`;
|
|
162
|
+
}
|
|
163
|
+
if (numberChain) return `z.coerce.number(${baseErrorArg}).int(${errorMessage ? zodError(errorMessage) : ""})${constraints}`;
|
|
164
|
+
if (numberPipe) return `z.coerce.number(${baseErrorArg}).pipe(${innerChain})`;
|
|
165
|
+
if (is64) return `${int64Input(readsText, baseErrorArg)}.pipe(${innerChain})`;
|
|
166
|
+
return innerChain;
|
|
167
|
+
}
|
|
168
|
+
//#endregion
|
|
169
|
+
//#region src/generator/zod/enum.ts
|
|
170
|
+
/**
|
|
171
|
+
* Generates a Zod enum schema. String enums map to `z.enum`, number/integer/
|
|
172
|
+
* boolean enums to `z.union([z.literal(...), ...])`, array enums to `z.tuple`
|
|
173
|
+
* or `z.union`, single values to `z.literal`.
|
|
174
|
+
*
|
|
175
|
+
* `x-error-message` (whole-enum) is applied **only to the outermost
|
|
176
|
+
* wrapper** (z.enum / z.union / z.tuple, or the bare z.literal in the
|
|
177
|
+
* single-value case). Inner z.literal entries inside a wrapper never
|
|
178
|
+
* receive a duplicate `error:` arg — Zod's outer wrapper already shadows
|
|
179
|
+
* inner messages on validation failure, so the inner copy was dead.
|
|
180
|
+
*
|
|
181
|
+
* Per-literal `x-enum-error-messages` was removed entirely: a rejected
|
|
182
|
+
* value by definition isn't in the enum, so a per-literal
|
|
183
|
+
* `value === 'admin'` branch can never match. Whole-enum messages
|
|
184
|
+
* come from `x-error-message`; finer-grained business rules belong in
|
|
185
|
+
* handler code, not the schema.
|
|
186
|
+
*/
|
|
187
|
+
function lit(v, isBigint) {
|
|
188
|
+
if (v === null) return "null";
|
|
189
|
+
if (typeof v === "string") return `'${v.replaceAll("'", "\\'")}'`;
|
|
190
|
+
if (typeof v === "number" && isBigint) return `${v}n`;
|
|
191
|
+
if (typeof v === "number" || typeof v === "boolean") return String(v);
|
|
192
|
+
return JSON.stringify(v) ?? "null";
|
|
193
|
+
}
|
|
194
|
+
function _enum(schema) {
|
|
195
|
+
const isBigint = isInt64(schema);
|
|
196
|
+
if (!schema.enum || schema.enum.length === 0) return "z.any()";
|
|
197
|
+
const errorMessage = schema["x-enum-message"] ?? schema["x-error-message"];
|
|
198
|
+
const errorArg = zodErrorPart(errorMessage);
|
|
199
|
+
const valueSchema = (v) => {
|
|
200
|
+
if (Array.isArray(v)) return `z.tuple([${v.map(valueSchema).join(",")}])`;
|
|
201
|
+
if (isPlainObject(v)) return `z.strictObject({${Object.entries(v).map(([k, val]) => `${makeSafeKey(k)}:${valueSchema(val)}`).join(",")}})`;
|
|
202
|
+
return `z.literal(${lit(v, isBigint)})`;
|
|
203
|
+
};
|
|
204
|
+
const innerLit = (v) => valueSchema(v);
|
|
205
|
+
const outerLit = (v) => isComposite(v) ? valueSchema(v) : `z.literal(${lit(v, isBigint)}${errorArg})`;
|
|
206
|
+
const innerTuple = (arr) => `z.tuple([${arr.map(innerLit).join(",")}])`;
|
|
207
|
+
const outerTuple = (arr) => `z.tuple([${arr.map(innerLit).join(",")}]${errorArg})`;
|
|
208
|
+
if (hasType(schema, "number") || hasType(schema, "integer") || hasType(schema, "boolean")) return schema.enum.length > 1 ? `z.union([${schema.enum.map(innerLit).join(",")}]${errorArg})` : outerLit(schema.enum[0]);
|
|
209
|
+
if (hasType(schema, "array")) {
|
|
210
|
+
if (schema.enum.length === 1 && Array.isArray(schema.enum[0])) return outerTuple(schema.enum[0]);
|
|
211
|
+
return `z.union([${schema.enum.map((v) => Array.isArray(v) ? innerTuple(v) : innerLit(v)).join(",")}]${errorArg})`;
|
|
212
|
+
}
|
|
213
|
+
if (schema.enum.every((v) => typeof v === "string")) {
|
|
214
|
+
if (schema.enum.length > 1) return `z.enum(${JSON.stringify(schema.enum)}${errorArg})`;
|
|
215
|
+
return outerLit(schema.enum[0]);
|
|
216
|
+
}
|
|
217
|
+
if (schema.enum.length > 1) return `z.union([${schema.enum.map(innerLit).join(",")}]${errorArg})`;
|
|
218
|
+
return outerLit(schema.enum[0]);
|
|
219
|
+
}
|
|
220
|
+
//#endregion
|
|
221
|
+
//#region src/generator/zod/object.ts
|
|
222
|
+
/**
|
|
223
|
+
* A parameter object answers an `Object.prototype` name it was not sent with the inherited
|
|
224
|
+
* member. Copied onto a null-prototype object, it holds only what the request carried.
|
|
225
|
+
*/
|
|
226
|
+
const OWN_PROPERTIES_PREPROCESS = "(val)=>(typeof val===\"object\"&&val!==null&&!Array.isArray(val)?Object.assign(Object.create(null),val):val)";
|
|
227
|
+
/**
|
|
228
|
+
* Generate a Zod object schema for a JSON Schema object node.
|
|
229
|
+
*
|
|
230
|
+
* Dispatches `additionalProperties` to `z.looseObject` (true), `z.strictObject`
|
|
231
|
+
* (false), `z.record` (Schema), or default `z.object`. Combinators
|
|
232
|
+
* (oneOf/anyOf/allOf/not) delegate to the main `zod` entry. JSON Schema 2020-12
|
|
233
|
+
* keywords (`minProperties`, `maxProperties`, `propertyNames`,
|
|
234
|
+
* `patternProperties`, `dependentRequired`) are emitted as `.refine(...)`
|
|
235
|
+
* chains.
|
|
236
|
+
*/
|
|
237
|
+
function object(schema, rootName, isZod, options) {
|
|
238
|
+
if (hasCombinator(schema)) return zod(schema, rootName, isZod, options);
|
|
239
|
+
const errorMessage = schema["x-error-message"];
|
|
240
|
+
const errorArg = zodErrorPart(errorMessage);
|
|
241
|
+
const minPropsMessage = schema["x-minProperties-message"];
|
|
242
|
+
const minErrorArg = zodErrorPart(minPropsMessage);
|
|
243
|
+
const maxPropsMessage = schema["x-maxProperties-message"];
|
|
244
|
+
const maxErrorArg = zodErrorPart(maxPropsMessage);
|
|
245
|
+
const patternPropsMessage = schema["x-patternProperties-message"];
|
|
246
|
+
const patternErrorArg = zodErrorPart(patternPropsMessage);
|
|
247
|
+
const propNamesMessage = schema["x-propertyNames-message"];
|
|
248
|
+
const propNamesErrorArg = zodErrorPart(propNamesMessage);
|
|
249
|
+
const depReqMessage = schema["x-dependentRequired-message"];
|
|
250
|
+
const depReqErrorArg = depReqMessage ? `,${zodError(depReqMessage)}` : errorArg;
|
|
251
|
+
const depSchMessage = schema["x-dependentSchemas-message"];
|
|
252
|
+
const depSchErrorArg = depSchMessage ? `,${zodError(depSchMessage)}` : errorArg;
|
|
253
|
+
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]) => {
|
|
254
|
+
const z = zod(propSchema, rootName, isZod, options);
|
|
255
|
+
return `.refine((val)=>Object.entries(val).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||${z}.safeParse(value).success)${patternErrorArg})`;
|
|
256
|
+
}).join("") : ""}`;
|
|
257
|
+
if (!schema.properties) {
|
|
258
|
+
if (schema.additionalProperties === true) return "z.any()";
|
|
259
|
+
return "z.object({})";
|
|
260
|
+
}
|
|
261
|
+
const conditionalKeysReferenced = hasConditional(schema);
|
|
262
|
+
const objectType = schema.additionalProperties === true ? "looseObject" : schema.additionalProperties === false || schema.unevaluatedProperties === false ? "strictObject" : conditionalKeysReferenced ? "looseObject" : "object";
|
|
263
|
+
const required = new Set(schema.required);
|
|
264
|
+
const props = Object.entries(schema.properties).map(([key, propSchema]) => {
|
|
265
|
+
const parsed = zod(propSchema, rootName, isZod, propertyEmitOptions(key, propSchema, options) ?? options);
|
|
266
|
+
if (!parsed) return null;
|
|
267
|
+
return `${makeSafeKey(key)}:${parsed}${required.has(key) ? "" : ".exactOptional()"}`;
|
|
268
|
+
}).filter((v) => v !== null);
|
|
269
|
+
const strictMessage = schema["x-additionalProperties-message"] ?? (schema.unevaluatedProperties === false ? schema["x-unevaluatedProperties-message"] : void 0);
|
|
270
|
+
const objectParams = objectType === "strictObject" && strictMessage ? `,{error:(issue)=>issue.code==='unrecognized_keys'?${JSON.stringify(strictMessage)}:${errorMessage ? JSON.stringify(errorMessage) : "undefined"}}` : "";
|
|
271
|
+
const rawBase = `z.${objectType}({${props.join(",")}}${objectParams})`;
|
|
272
|
+
const propsMessage = schema["x-properties-message"];
|
|
273
|
+
const objectExpr = `${propsMessage ? (() => {
|
|
274
|
+
const msgExpr = issueMessageExpression(propsMessage);
|
|
275
|
+
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)})()`;
|
|
276
|
+
})() : 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 z = zod(propSchema, rootName, isZod, options);
|
|
278
|
+
return `.refine((val)=>Object.entries(val).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||${z}.safeParse(value).success)${patternErrorArg})`;
|
|
279
|
+
}).join("") : ""}${schema.dependentRequired ? Object.entries(schema.dependentRequired).map(([key, deps]) => {
|
|
280
|
+
return `.refine((val)=>!('${key}' in val)||(${deps.map((d) => `'${d}' in val`).join("&&")})${depReqErrorArg})`;
|
|
281
|
+
}).join("") : ""}${schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
|
|
282
|
+
return `.refine((val)=>!('${key}' in val)||${zod(subSchema, rootName, isZod, options)}.safeParse(val).success${depSchErrorArg})`;
|
|
283
|
+
}).join("") : ""}${(() => {
|
|
284
|
+
if (!schema.if) return "";
|
|
285
|
+
const ifS = zod(schema.if, rootName, isZod, options);
|
|
286
|
+
const thenS = schema.then ? zod(schema.then, rootName, isZod, options) : void 0;
|
|
287
|
+
const elseS = schema.else ? zod(schema.else, rootName, isZod, options) : void 0;
|
|
288
|
+
if (!thenS && !elseS) return "";
|
|
289
|
+
const ifMessage = schema["x-if-message"];
|
|
290
|
+
const thenMessage = schema["x-then-message"] ?? ifMessage;
|
|
291
|
+
const elseMessage = schema["x-else-message"] ?? ifMessage;
|
|
292
|
+
const parts = [];
|
|
293
|
+
if (thenS) {
|
|
294
|
+
const arg = zodErrorPart(thenMessage);
|
|
295
|
+
parts.push(`.refine((val)=>!${ifS}.safeParse(val).success||${thenS}.safeParse(val).success${arg})`);
|
|
296
|
+
}
|
|
297
|
+
if (elseS) {
|
|
298
|
+
const arg = zodErrorPart(elseMessage);
|
|
299
|
+
parts.push(`.refine((val)=>${ifS}.safeParse(val).success||${elseS}.safeParse(val).success${arg})`);
|
|
300
|
+
}
|
|
301
|
+
return parts.join("");
|
|
302
|
+
})()}`;
|
|
303
|
+
const hasInheritedName = Object.keys(schema.properties).some(isObjectPrototypeProperty);
|
|
304
|
+
return isStringWireLocation(options?.paramIn) && hasInheritedName ? `z.preprocess(${OWN_PROPERTIES_PREPROCESS},${objectExpr})` : objectExpr;
|
|
305
|
+
}
|
|
306
|
+
//#endregion
|
|
307
|
+
//#region src/generator/zod/parameter.ts
|
|
308
|
+
/**
|
|
309
|
+
* Wraps the root expression of a parameter's schema in what reads the parameter's
|
|
310
|
+
* serialization: `allowEmptyValue`, a JSON `content`, or its `style` / `explode`.
|
|
311
|
+
*
|
|
312
|
+
* @see https://spec.openapis.org/oas/v3.2.0.html#style-examples
|
|
313
|
+
*/
|
|
314
|
+
function parameter(schema, inner, options) {
|
|
315
|
+
return parameterReaders(schema, options, "val").reduceRight((acc, step) => `z.preprocess(${step},${acc})`, inner);
|
|
316
|
+
}
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/generator/zod/string.ts
|
|
319
|
+
/** The formats Zod checks with a top-level validator, keyed by the lower-cased format. */
|
|
320
|
+
const FORMAT_STRING = {
|
|
321
|
+
email: "email()",
|
|
322
|
+
guid: "guid()",
|
|
323
|
+
uuid: "uuid()",
|
|
324
|
+
uuidv4: "uuidv4()",
|
|
325
|
+
uuidv6: "uuidv6()",
|
|
326
|
+
uuidv7: "uuidv7()",
|
|
327
|
+
uri: "url()",
|
|
328
|
+
url: "url()",
|
|
329
|
+
httpurl: "httpUrl()",
|
|
330
|
+
hostname: "hostname()",
|
|
331
|
+
hex: "hex()",
|
|
332
|
+
e164: "e164()",
|
|
333
|
+
ksuid: "ksuid()",
|
|
334
|
+
xid: "xid()",
|
|
335
|
+
emoji: "emoji()",
|
|
336
|
+
base64: "base64()",
|
|
337
|
+
base64url: "base64url()",
|
|
338
|
+
nanoid: "nanoid()",
|
|
339
|
+
cuid: "cuid()",
|
|
340
|
+
cuid2: "cuid2()",
|
|
341
|
+
ulid: "ulid()",
|
|
342
|
+
ipv4: "ipv4()",
|
|
343
|
+
ipv6: "ipv6()",
|
|
344
|
+
mac: "mac()",
|
|
345
|
+
cidrv4: "cidrv4()",
|
|
346
|
+
cidrv6: "cidrv6()",
|
|
347
|
+
date: "iso.date()",
|
|
348
|
+
"date-time": "iso.datetime()",
|
|
349
|
+
duration: "iso.duration()",
|
|
350
|
+
binary: "file()",
|
|
351
|
+
jwt: "jwt()"
|
|
352
|
+
};
|
|
353
|
+
/** The formats that normalise the value rather than check it, keyed by the lower-cased format. */
|
|
354
|
+
const TRANSFORM_FORMATS = {
|
|
355
|
+
trim: ".trim()",
|
|
356
|
+
tolowercase: ".toLowerCase()",
|
|
357
|
+
touppercase: ".toUpperCase()"
|
|
358
|
+
};
|
|
359
|
+
const LUHN_CHECK = `(val)=>{let sum=0;for(let i=0;i<val.length;i++){let digit=Number(val[val.length-1-i]);if(i%2===1){digit*=2;if(digit>9)digit-=9}sum+=digit}return sum%10===0}`;
|
|
360
|
+
const IBAN_CHECK = `(val)=>{let rest=0;for(const char of val.slice(4)+val.slice(0,4)){const n=Number.parseInt(char,36);rest=(n>9?rest*100+n:rest*10+n)%97}return rest===1}`;
|
|
361
|
+
/**
|
|
362
|
+
* The checks chained onto `z.string()` for a format Zod has no validator of its own for,
|
|
363
|
+
* or `undefined` when the format is not one of them.
|
|
364
|
+
*/
|
|
365
|
+
function formatChecks(schema, format) {
|
|
366
|
+
const errorMessage = schema["x-error-message"];
|
|
367
|
+
const errorPart = zodErrorPart(errorMessage);
|
|
368
|
+
if (format === "time" && schema["x-isoOffset"] !== false) {
|
|
369
|
+
const precision = schema["x-isoPrecision"];
|
|
370
|
+
return `.regex(${timePattern(typeof precision === "number" ? precision : void 0, true)}${errorPart})`;
|
|
371
|
+
}
|
|
372
|
+
if (format === "creditcard") return `${String.raw`.regex(/^\d{12,19}$/${errorPart})`}.refine(${LUHN_CHECK}${errorPart})`;
|
|
373
|
+
if (format === "iban") return `${String.raw`.regex(/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/${errorPart})`}.refine(${IBAN_CHECK}${errorPart})`;
|
|
374
|
+
if (format === "currencycode") return `.regex(/^(?:${ISO_4217_CURRENCY_CODES.join("|")})$/${errorPart})`;
|
|
375
|
+
}
|
|
376
|
+
/** The Zod format call of a node, as `z.` would be followed by, or `undefined`. */
|
|
377
|
+
function formatCall(schema, format) {
|
|
378
|
+
if (format === "time") return schema["x-isoOffset"] === false ? "iso.time()" : void 0;
|
|
379
|
+
return FORMAT_STRING[format];
|
|
380
|
+
}
|
|
381
|
+
const EMAIL_PATTERN_MAP = {
|
|
382
|
+
html5: "z.regexes.html5Email",
|
|
383
|
+
rfc5322: "z.regexes.rfc5322Email",
|
|
384
|
+
browser: "z.regexes.browserEmail",
|
|
385
|
+
unicode: "z.regexes.unicodeEmail"
|
|
386
|
+
};
|
|
387
|
+
function buildFormatOptions(schema, format) {
|
|
388
|
+
const parts = [];
|
|
389
|
+
if (format === "email") {
|
|
390
|
+
const emailPattern = schema["x-emailPattern"];
|
|
391
|
+
const emailRegex = schema["x-emailRegex"];
|
|
392
|
+
if (typeof emailPattern === "string" && EMAIL_PATTERN_MAP[emailPattern] !== void 0) parts.push(`pattern:${EMAIL_PATTERN_MAP[emailPattern]}`);
|
|
393
|
+
else if (typeof emailRegex === "string") parts.push(`pattern:${regexLiteral(emailRegex)}`);
|
|
394
|
+
return parts;
|
|
395
|
+
}
|
|
396
|
+
if (format === "uuid") {
|
|
397
|
+
const uuidVersion = schema["x-uuidVersion"];
|
|
398
|
+
if (typeof uuidVersion === "string") parts.push(`version:${JSON.stringify(uuidVersion)}`);
|
|
399
|
+
return parts;
|
|
400
|
+
}
|
|
401
|
+
if (format === "uri" || format === "url" || format === "httpurl") {
|
|
402
|
+
const urlProtocol = schema["x-urlProtocol"];
|
|
403
|
+
if (typeof urlProtocol === "string") parts.push(`protocol:${regexLiteral(urlProtocol)}`);
|
|
404
|
+
const urlHostname = schema["x-urlHostname"];
|
|
405
|
+
if (typeof urlHostname === "string") parts.push(`hostname:${regexLiteral(urlHostname)}`);
|
|
406
|
+
if (schema["x-urlNormalize"] === true) parts.push("normalize:true");
|
|
407
|
+
else if (schema["x-urlNormalize"] === false) parts.push("normalize:false");
|
|
408
|
+
return parts;
|
|
409
|
+
}
|
|
410
|
+
if (format === "date-time") {
|
|
411
|
+
const precision = schema["x-isoPrecision"];
|
|
412
|
+
if (typeof precision === "number") parts.push(`precision:${precision}`);
|
|
413
|
+
if (schema["x-isoOffset"] !== false) parts.push("offset:true");
|
|
414
|
+
const local = schema["x-isoLocal"];
|
|
415
|
+
if (typeof local === "boolean") parts.push(`local:${local}`);
|
|
416
|
+
return parts;
|
|
417
|
+
}
|
|
418
|
+
if (format === "time") {
|
|
419
|
+
const precision = schema["x-isoPrecision"];
|
|
420
|
+
if (typeof precision === "number") parts.push(`precision:${precision}`);
|
|
421
|
+
return parts;
|
|
422
|
+
}
|
|
423
|
+
if (format === "jwt") {
|
|
424
|
+
const alg = schema["x-jwtAlg"];
|
|
425
|
+
if (typeof alg === "string") parts.push(`alg:${JSON.stringify(alg)}`);
|
|
426
|
+
return parts;
|
|
427
|
+
}
|
|
428
|
+
if (format === "mac") {
|
|
429
|
+
const delimiter = schema["x-macDelimiter"];
|
|
430
|
+
if (typeof delimiter === "string") parts.push(`delimiter:${JSON.stringify(delimiter)}`);
|
|
431
|
+
return parts;
|
|
432
|
+
}
|
|
433
|
+
return parts;
|
|
434
|
+
}
|
|
435
|
+
function hashBase(schema, baseErrorArg) {
|
|
436
|
+
if (schema.format !== "hash") return void 0;
|
|
437
|
+
const algo = schema["x-hashAlg"];
|
|
438
|
+
if (algo === void 0) return baseErrorArg ? `z.string(${baseErrorArg})` : "z.string()";
|
|
439
|
+
const enc = schema["x-hashEnc"];
|
|
440
|
+
const errorPart = baseErrorArg ? baseErrorArg.slice(1, -1) : "";
|
|
441
|
+
const opts = [enc !== void 0 ? `enc:${JSON.stringify(enc)}` : void 0, errorPart || void 0].filter((v) => v !== void 0);
|
|
442
|
+
const optsStr = opts.length > 0 ? `,{${opts.join(",")}}` : "";
|
|
443
|
+
return `z.hash(${JSON.stringify(algo)}${optsStr})`;
|
|
444
|
+
}
|
|
445
|
+
function mergeOptions(formatOptions, baseErrorArg) {
|
|
446
|
+
if (formatOptions.length === 0) return baseErrorArg;
|
|
447
|
+
const errorPart = baseErrorArg ? baseErrorArg.slice(1, -1) : "";
|
|
448
|
+
return `{${(errorPart ? [...formatOptions, errorPart] : [...formatOptions]).join(",")}}`;
|
|
449
|
+
}
|
|
450
|
+
function stringbool(schema) {
|
|
451
|
+
const flag = schema["x-stringbool"];
|
|
452
|
+
if (flag === void 0 || flag === false) return void 0;
|
|
453
|
+
const opts = typeof flag === "object" ? flag : {};
|
|
454
|
+
const parts = [];
|
|
455
|
+
if (Array.isArray(opts.truthy)) parts.push(`truthy:[${opts.truthy.map((s) => JSON.stringify(s)).join(",")}]`);
|
|
456
|
+
if (Array.isArray(opts.falsy)) parts.push(`falsy:[${opts.falsy.map((s) => JSON.stringify(s)).join(",")}]`);
|
|
457
|
+
if (opts.case === "sensitive" || opts.case === "insensitive") parts.push(`case:${JSON.stringify(opts.case)}`);
|
|
458
|
+
const error = opts.error ?? schema["x-error-message"];
|
|
459
|
+
if (typeof error === "string") parts.push(`error:${JSON.stringify(error)}`);
|
|
460
|
+
return parts.length === 0 ? "z.stringbool()" : `z.stringbool({${parts.join(",")}})`;
|
|
461
|
+
}
|
|
462
|
+
function string(schema) {
|
|
463
|
+
const stringboolExpr = stringbool(schema);
|
|
464
|
+
if (stringboolExpr !== void 0) return stringboolExpr;
|
|
465
|
+
const errorMessage = schema["x-error-message"];
|
|
466
|
+
const requiredMessage = schema["x-required-message"];
|
|
467
|
+
const coerce = schema["x-coerce"] === true;
|
|
468
|
+
const baseErrorArg = zodBaseError(errorMessage, coerce ? void 0 : requiredMessage);
|
|
469
|
+
const patternMessage = schema["x-pattern-message"];
|
|
470
|
+
const patternErrorPart = zodErrorPart(patternMessage);
|
|
471
|
+
const minLengthMessage = schema["x-minLength-message"];
|
|
472
|
+
const minErrorPart = zodErrorPart(minLengthMessage);
|
|
473
|
+
const maxLengthMessage = schema["x-maxLength-message"];
|
|
474
|
+
const maxErrorPart = zodErrorPart(maxLengthMessage);
|
|
475
|
+
const fixedLengthErrorPart = zodErrorPart(minLengthMessage ?? maxLengthMessage);
|
|
476
|
+
const hash = hashBase(schema, baseErrorArg);
|
|
477
|
+
const formatName = schema.format?.toLowerCase();
|
|
478
|
+
const format = formatName !== void 0 ? formatCall(schema, formatName) : void 0;
|
|
479
|
+
const checks = formatName !== void 0 ? formatChecks(schema, formatName) : void 0;
|
|
480
|
+
const transformFormat = formatName !== void 0 ? TRANSFORM_FORMATS[formatName] : void 0;
|
|
481
|
+
const coercePrefix = coerce && !format && !hash ? "coerce." : "";
|
|
482
|
+
const formatOptions = format && formatName !== void 0 ? buildFormatOptions(schema, formatName) : [];
|
|
483
|
+
const baseCallArg = format ? mergeOptions(formatOptions, baseErrorArg) : baseErrorArg;
|
|
484
|
+
const formatBase = hash ?? (format ? `z.${format.replace(/\(\)$/u, `(${baseCallArg})`)}` : void 0);
|
|
485
|
+
const pattern = schema.pattern ? `.regex(${regexLiteral(schema.pattern)}${patternErrorPart})` : void 0;
|
|
486
|
+
const isFixedLength = hasFixedLength(schema);
|
|
487
|
+
const trim = schema["x-trim"] === true || transformFormat === ".trim()" ? ".trim()" : void 0;
|
|
488
|
+
const toLowerCase = schema["x-toLowerCase"] === true || transformFormat === ".toLowerCase()" ? ".toLowerCase()" : void 0;
|
|
489
|
+
const toUpperCase = schema["x-toUpperCase"] === true || transformFormat === ".toUpperCase()" ? ".toUpperCase()" : void 0;
|
|
490
|
+
const normalize = typeof schema["x-normalize"] === "string" ? `.normalize(${JSON.stringify(schema["x-normalize"])})` : void 0;
|
|
491
|
+
const startsWith = typeof schema["x-startsWith"] === "string" ? `.startsWith(${JSON.stringify(schema["x-startsWith"])})` : void 0;
|
|
492
|
+
const endsWith = typeof schema["x-endsWith"] === "string" ? `.endsWith(${JSON.stringify(schema["x-endsWith"])})` : void 0;
|
|
493
|
+
const includes = typeof schema["x-includes"] === "string" ? `.includes(${JSON.stringify(schema["x-includes"])})` : void 0;
|
|
494
|
+
const lowercaseValidate = schema["x-lowercase"] === true ? ".lowercase()" : void 0;
|
|
495
|
+
const uppercaseValidate = schema["x-uppercase"] === true ? ".uppercase()" : void 0;
|
|
496
|
+
const transforms = [
|
|
497
|
+
trim,
|
|
498
|
+
toLowerCase,
|
|
499
|
+
toUpperCase,
|
|
500
|
+
normalize
|
|
501
|
+
].filter((v) => v !== void 0).join("");
|
|
502
|
+
const restChecks = [
|
|
503
|
+
checks,
|
|
504
|
+
startsWith,
|
|
505
|
+
endsWith,
|
|
506
|
+
includes,
|
|
507
|
+
pattern,
|
|
508
|
+
isFixedLength ? `.length(${schema.minLength}${fixedLengthErrorPart})` : void 0,
|
|
509
|
+
!isFixedLength && schema.minLength !== void 0 ? `.min(${schema.minLength}${minErrorPart})` : void 0,
|
|
510
|
+
!isFixedLength && schema.maxLength !== void 0 ? `.max(${schema.maxLength}${maxErrorPart})` : void 0,
|
|
511
|
+
lowercaseValidate,
|
|
512
|
+
uppercaseValidate
|
|
513
|
+
].filter((v) => v !== void 0).join("");
|
|
514
|
+
if (formatBase === void 0) return `z.${coercePrefix}string(${baseCallArg})${transforms}${restChecks}`;
|
|
515
|
+
if (transforms !== "") return `z.string(${baseErrorArg})${transforms}.pipe(${formatBase}${restChecks})`;
|
|
516
|
+
return `${formatBase}${restChecks}`;
|
|
517
|
+
}
|
|
518
|
+
//#endregion
|
|
519
|
+
//#region src/generator/zod/zod.ts
|
|
520
|
+
/**
|
|
521
|
+
* Zod v4 issue codes, in the order `zod/v4/core/errors.d.ts` declares them. The
|
|
522
|
+
* `x-allOf-message` wrapper matches each in turn and replaces its message.
|
|
523
|
+
*/
|
|
524
|
+
const ZOD_ISSUE_CODES = [
|
|
525
|
+
"invalid_type",
|
|
526
|
+
"too_big",
|
|
527
|
+
"too_small",
|
|
528
|
+
"invalid_format",
|
|
529
|
+
"not_multiple_of",
|
|
530
|
+
"unrecognized_keys",
|
|
531
|
+
"invalid_union",
|
|
532
|
+
"invalid_key",
|
|
533
|
+
"invalid_element",
|
|
534
|
+
"invalid_value",
|
|
535
|
+
"custom"
|
|
536
|
+
];
|
|
537
|
+
/**
|
|
538
|
+
* The `not` predicate of an inner schema, as the source of a `(val) => ...` arrow, or
|
|
539
|
+
* `undefined` when the inner schema has none this generator can express.
|
|
540
|
+
*/
|
|
541
|
+
function zodNotPredicate(inner, parent) {
|
|
542
|
+
if (inner.$ref) return void 0;
|
|
543
|
+
const bigint = isBigintFormat(parent);
|
|
544
|
+
const shared = notPredicate(inner, "val", "val", bigint);
|
|
545
|
+
if (shared !== void 0) return shared;
|
|
546
|
+
if (Array.isArray(inner.enum)) return `(val) => !${valueListLiteral(inner.enum, bigint)}.includes(val)`;
|
|
547
|
+
if (inner.oneOf || inner.anyOf || inner.allOf) return `(val) => !${zod(inner)}.safeParse(val).success`;
|
|
548
|
+
}
|
|
549
|
+
function elementMessageWrap(inner, msg) {
|
|
550
|
+
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)})()`;
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Generate Zod schema code from JSON Schema.
|
|
554
|
+
*
|
|
555
|
+
* @example
|
|
556
|
+
* ```ts
|
|
557
|
+
* zod({ type: 'string' }, 'MySchema') // 'z.string()'
|
|
558
|
+
* ```
|
|
559
|
+
*/
|
|
560
|
+
function zod(schema, rootName = DEFAULT_ROOT_NAME, isZod = false, options) {
|
|
561
|
+
if (hasParameterSerialization(options)) return parameter(schema, zod(schema, rootName, isZod, withoutParameterSerialization(options)), options);
|
|
562
|
+
const expression = node(schema, rootName, isZod, options);
|
|
563
|
+
if (!(isStringWireLocation(options?.paramIn) && schema["x-coerce"] !== false) || !isNullTextRead(schema)) return expression;
|
|
564
|
+
const nullFirst = isNullMatchedFirst(schema) ? expression : `${expression}.nullable()`;
|
|
565
|
+
return `z.preprocess(${wireNullText("val")},${nullFirst})`;
|
|
566
|
+
}
|
|
567
|
+
/** A keyword-only `allOf` member: the keywords apply when the value has their type. */
|
|
568
|
+
function keywordConstraint(schema) {
|
|
569
|
+
return `z.any().refine((val) => ${constraintPredicate(schema, "val")}${zodErrorPart(constraintMessage(schema))})`;
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* An `allOf` with `unevaluatedProperties` beside it: the members' objects strip what they
|
|
573
|
+
* do not declare, so the keys no member evaluates are checked on the input before it is
|
|
574
|
+
* parsed. `inner` as given when the keyword is absent or every key is evaluated.
|
|
575
|
+
*/
|
|
576
|
+
function unevaluatedPropertiesCheck(inner, schema, rootName, isZod, options) {
|
|
577
|
+
const unevaluated = schema.unevaluatedProperties;
|
|
578
|
+
if (unevaluated !== false && (typeof unevaluated !== "object" || unevaluated === null)) return inner;
|
|
579
|
+
const evaluated = evaluatedProperties(schema, options?.definitions);
|
|
580
|
+
if (evaluated === void 0) return inner;
|
|
581
|
+
const isEvaluated = isEvaluatedKeyExpression(evaluated, "k");
|
|
582
|
+
const message = schema["x-unevaluatedProperties-message"];
|
|
583
|
+
return `(()=>{const Schema=${inner};return z.unknown().check((ctx)=>{const o=ctx.value;if(typeof o!=='object'||o===null||Array.isArray(o))return;${unevaluated === false ? `for(const k of Object.keys(o)){if(${isEvaluated})continue;ctx.issues.push({code:'custom',input:o,path:[k],message:${message === void 0 ? "`Unrecognized key: \"${k}\"`" : JSON.stringify(message)}})}` : `const Unevaluated=${zod(unevaluated, rootName, isZod, options)};for(const [k,v] of Object.entries(o)){if(${isEvaluated})continue;const result=Unevaluated.safeParse(v);if(!result.success){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)}})}}}`}}).pipe(Schema)})()`;
|
|
584
|
+
}
|
|
585
|
+
function node(schema, rootName, isZod, options) {
|
|
586
|
+
const isStringWireParam = isStringWireLocation(options?.paramIn);
|
|
587
|
+
const isWireCoerced = isStringWireParam && schema["x-coerce"] !== false;
|
|
588
|
+
const codeExtOpts = options?.unsafeCodeExtensions === true ? { unsafeCodeExtensions: true } : {};
|
|
589
|
+
const zodWrap$1 = (zodStr, s) => zodWrap(zodStr, s, {
|
|
590
|
+
...codeExtOpts,
|
|
591
|
+
...options?.definitions !== void 0 && { definitions: options.definitions }
|
|
592
|
+
});
|
|
593
|
+
const readonly = (v) => options?.readonly ? `${v}.readonly()` : v;
|
|
594
|
+
const wireArray = (v) => isStringWireParam ? `z.preprocess(${wireArrayOnce("val")},${v})` : v;
|
|
595
|
+
const literalInput = (values) => {
|
|
596
|
+
if (values.every((v) => typeof v === "number")) {
|
|
597
|
+
if (isInt64(schema)) return int64Input(isWireCoerced);
|
|
598
|
+
if (isWireCoerced) return zodWireNumber(wireNumericKind(schema, values));
|
|
599
|
+
}
|
|
600
|
+
if (isWireCoerced && values.every((v) => typeof v === "boolean")) return "z.stringbool()";
|
|
601
|
+
};
|
|
602
|
+
const ref = (s, rn, iz) => {
|
|
603
|
+
if (s.$ref === void 0) return "z.any()";
|
|
604
|
+
const target = refTarget(s.$ref, rn, iz, options?.openapi);
|
|
605
|
+
if (target.kind === "lazy") return `z.lazy(() => ${target.name})`;
|
|
606
|
+
if (target.kind === "value") return target.name;
|
|
607
|
+
return target.kind === "unknown" ? "z.unknown()" : "z.any()";
|
|
608
|
+
};
|
|
609
|
+
if (schema.$ref) {
|
|
610
|
+
const items = itemsSchemaOf(schema.items);
|
|
611
|
+
if (schema.type === "array" && items?.$ref) return `z.array(${zodWrap$1(ref(items, rootName, isZod), items)})`;
|
|
612
|
+
return zodWrap$1(ref(schema, rootName, isZod), schema);
|
|
613
|
+
}
|
|
614
|
+
const impliedType = isWireCoerced ? impliedWireType(schema) : void 0;
|
|
615
|
+
if (impliedType !== void 0) return node({
|
|
616
|
+
...schema,
|
|
617
|
+
type: impliedType
|
|
618
|
+
}, rootName, isZod, options);
|
|
619
|
+
if (schema.oneOf) {
|
|
620
|
+
if (schema.oneOf.length === 0) return zodWrap$1("z.any()", schema);
|
|
621
|
+
const schemas = schema.oneOf.map((s) => zod(s, rootName, isZod, options));
|
|
622
|
+
const oneOfMessage = schema["x-oneOf-message"];
|
|
623
|
+
const errorPart = zodErrorPart(oneOfMessage);
|
|
624
|
+
const discriminator = schema.discriminator?.propertyName;
|
|
625
|
+
const hasRefOrAllOf = schema.oneOf.some((s) => s.$ref !== void 0 || s.allOf !== void 0);
|
|
626
|
+
return zodWrap$1(discriminator && !hasRefOrAllOf ? `z.discriminatedUnion('${discriminator}',[${schemas.join(",")}]${errorPart})` : isWireCoerced ? `z.union([${schemas.join(",")}]${errorPart})` : `z.xor([${schemas.join(",")}]${errorPart})`, schema);
|
|
627
|
+
}
|
|
628
|
+
if (schema.anyOf) {
|
|
629
|
+
if (schema.anyOf.length === 0) return zodWrap$1("z.any()", schema);
|
|
630
|
+
const schemas = schema.anyOf.map((s) => zod(s, rootName, isZod, options));
|
|
631
|
+
const anyOfMessage = schema["x-implication-message"] ?? schema["x-anyOf-message"];
|
|
632
|
+
const errorPart = zodErrorPart(anyOfMessage);
|
|
633
|
+
return zodWrap$1(`z.union([${schemas.join(",")}]${errorPart})`, schema);
|
|
634
|
+
}
|
|
635
|
+
if (schema.allOf) {
|
|
636
|
+
if (schema.allOf.length === 0) return zodWrap$1("z.any()", schema);
|
|
637
|
+
const nullable = isNullable(schema) || schema.allOf.some(isNullTypeMember);
|
|
638
|
+
const defaultValue = schema.allOf.find(isDefaultOnlyMember)?.default;
|
|
639
|
+
const schemas = foldAllOfMembers(schema.allOf.filter((s) => !isShapelessMember(s)), isWireCoerced).map((s) => isKeywordOnlyMember(s) ? keywordConstraint(s) : zod(s, rootName, isZod, options));
|
|
640
|
+
if (schemas.length === 0) return zodWrap$1("z.any()", {
|
|
641
|
+
...schema,
|
|
642
|
+
nullable
|
|
643
|
+
});
|
|
644
|
+
const intersected = schemas.length === 1 ? schemas[0] : schemas.reduce((acc, s) => `z.intersection(${acc},${s})`);
|
|
645
|
+
const allOfMessage = schema["x-allOf-message"];
|
|
646
|
+
const checked = unevaluatedPropertiesCheck(allOfMessage ? (() => {
|
|
647
|
+
const msgExpr = issueMessageExpression(allOfMessage);
|
|
648
|
+
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("");
|
|
649
|
+
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)})()`;
|
|
650
|
+
})() : intersected, schema, rootName, isZod, options);
|
|
651
|
+
const mergedDefault = defaultValue !== void 0 ? defaultValue : schema.default;
|
|
652
|
+
return zodWrap$1(checked, {
|
|
653
|
+
...schema,
|
|
654
|
+
nullable,
|
|
655
|
+
...mergedDefault !== void 0 && { default: mergedDefault }
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
if (schema.not) {
|
|
659
|
+
const notMessage = schema["x-not-message"];
|
|
660
|
+
const errorPart = zodErrorPart(notMessage);
|
|
661
|
+
const { not: inner, ...withoutNot } = schema;
|
|
662
|
+
if (typeof inner !== "object" || inner === null) return zodWrap$1("z.any()", schema);
|
|
663
|
+
const predicate = inner.$ref ? `(val) => !${ref(inner, "", false)}.safeParse(val).success` : zodNotPredicate(inner, withoutNot);
|
|
664
|
+
if (withoutNot.type !== void 0) {
|
|
665
|
+
const base = zod(withoutNot, rootName, isZod, options);
|
|
666
|
+
return predicate ? `${base}.refine(${predicate}${errorPart})` : base;
|
|
667
|
+
}
|
|
668
|
+
if (predicate) return zodWrap$1(`z.any().refine(${predicate}${errorPart})`, schema);
|
|
669
|
+
return zodWrap$1("z.any()", schema);
|
|
670
|
+
}
|
|
671
|
+
if (schema.const !== void 0) {
|
|
672
|
+
const value = schema.const;
|
|
673
|
+
const constMessage = schema["x-const-message"] ?? schema["x-error-message"];
|
|
674
|
+
const errorPart = zodErrorPart(constMessage);
|
|
675
|
+
const literal = typeof value === "number" && isInt64(schema) ? `z.literal(${value}n${errorPart})` : isPrimitive(value) ? `z.literal(${JSON.stringify(value)}${errorPart})` : `z.custom<${JSON.stringify(value)}>()`;
|
|
676
|
+
const input = literalInput([value]);
|
|
677
|
+
return zodWrap$1(input ? `${input}.pipe(${literal})` : literal, schema);
|
|
678
|
+
}
|
|
679
|
+
if (schema.enum) {
|
|
680
|
+
const values = schema.enum.filter((value) => value !== null);
|
|
681
|
+
const input = values.length > 0 ? literalInput(values) : void 0;
|
|
682
|
+
if (input === void 0) return zodWrap$1(_enum(schema), schema);
|
|
683
|
+
const hasNull = values.length < schema.enum.length;
|
|
684
|
+
const piped = `${input}.pipe(${_enum({
|
|
685
|
+
...schema,
|
|
686
|
+
enum: values
|
|
687
|
+
})})`;
|
|
688
|
+
return zodWrap$1(hasNull && !isNullable(schema) ? `${piped}.nullable()` : piped, schema);
|
|
689
|
+
}
|
|
690
|
+
if (schema.properties) return readonly(zodWrap$1(object(schema, rootName, isZod, options), schema));
|
|
691
|
+
const types = normalizeTypes(schema.type);
|
|
692
|
+
const primitive = (t) => {
|
|
693
|
+
if (t === "string") return string(schema);
|
|
694
|
+
if (t === "number") return number(schema, { wire: isWireCoerced });
|
|
695
|
+
if (t === "integer") return integer(schema, { wire: isWireCoerced });
|
|
696
|
+
if (t !== "boolean") return void 0;
|
|
697
|
+
const errorMessage = schema["x-error-message"];
|
|
698
|
+
const errorArg = errorMessage ? zodError(errorMessage) : "";
|
|
699
|
+
if (isStringWireParam) return `z.stringbool(${errorArg ? `{error:${errorArg.replaceAll(/^{error:|}$/g, "")}}` : ""})`;
|
|
700
|
+
return `z.${schema["x-coerce"] === true ? "coerce." : ""}boolean(${errorArg})`;
|
|
701
|
+
};
|
|
702
|
+
if (isPrimitiveUnion(types, isWireCoerced)) return zodWrap$1(`z.union([${unionPrimitiveTypes(types, isWireCoerced).map(primitive).filter((m) => m !== void 0).join(",")}])`, schema);
|
|
703
|
+
for (const t of [
|
|
704
|
+
"string",
|
|
705
|
+
"number",
|
|
706
|
+
"integer",
|
|
707
|
+
"boolean"
|
|
708
|
+
]) {
|
|
709
|
+
if (!types.includes(t)) continue;
|
|
710
|
+
const expression = primitive(t);
|
|
711
|
+
if (expression !== void 0) return zodWrap$1(expression, schema);
|
|
712
|
+
}
|
|
713
|
+
if (types.includes("array")) {
|
|
714
|
+
const errorMessage = schema["x-error-message"];
|
|
715
|
+
const baseError = zodErrorPart(errorMessage);
|
|
716
|
+
const lengthMessage = schema["x-length-message"];
|
|
717
|
+
const minItemsMessage = schema["x-minItems-message"] ?? lengthMessage;
|
|
718
|
+
const minError = zodErrorPart(minItemsMessage);
|
|
719
|
+
const maxItemsMessage = schema["x-maxItems-message"] ?? lengthMessage;
|
|
720
|
+
const maxError = zodErrorPart(maxItemsMessage);
|
|
721
|
+
const fixedItemsError = zodErrorPart(minItemsMessage ?? maxItemsMessage);
|
|
722
|
+
const uniqueMessage = schema["x-uniqueItems-message"];
|
|
723
|
+
const uniqueError = zodErrorPart(uniqueMessage);
|
|
724
|
+
if (schema.prefixItems?.length) {
|
|
725
|
+
const items = schema.prefixItems.map((s) => zod(s, rootName, isZod, options));
|
|
726
|
+
const u = schema.unevaluatedItems;
|
|
727
|
+
const unevaluatedItemsMessage = schema["x-unevaluatedItems-message"];
|
|
728
|
+
const unevaluatedItemsError = zodErrorPart(unevaluatedItemsMessage);
|
|
729
|
+
const rest = isSchemaObject(u) ? zod(u, rootName, isZod, options) : void 0;
|
|
730
|
+
const tupleExpr = `z.tuple(${rest ? `[${items.join(",")}],${rest}` : `[${items.join(",")}]`}${u === false && unevaluatedItemsMessage ? unevaluatedItemsError : baseError})`;
|
|
731
|
+
const prefixItemsMessage = schema["x-prefixItems-message"];
|
|
732
|
+
return readonly(zodWrap$1(wireArray(prefixItemsMessage ? elementMessageWrap(tupleExpr, prefixItemsMessage) : tupleExpr), schema));
|
|
733
|
+
}
|
|
734
|
+
const itemSchema = itemsSchemaOf(schema.items);
|
|
735
|
+
const item = itemSchema ? zod(itemSchema, rootName, isZod, options) : "z.any()";
|
|
736
|
+
const itemsMessage = schema["x-items-message"];
|
|
737
|
+
const arrayBase = `z.array(${item}${baseError})`;
|
|
738
|
+
const base = itemsMessage ? elementMessageWrap(arrayBase, itemsMessage) : arrayBase;
|
|
739
|
+
const unique = schema.uniqueItems === true ? `.refine((val)=>new Set(val).size===val.length${uniqueError})` : "";
|
|
740
|
+
const containsChain = (() => {
|
|
741
|
+
const c = schema.contains;
|
|
742
|
+
if (!c) return "";
|
|
743
|
+
const containsZod = zod(c, rootName, isZod, options);
|
|
744
|
+
const minC = schema.minContains;
|
|
745
|
+
const maxC = schema.maxContains;
|
|
746
|
+
const fallback = schema["x-contains-message"] ?? errorMessage;
|
|
747
|
+
const parts = [];
|
|
748
|
+
if (minC === void 0 && maxC === void 0) {
|
|
749
|
+
const containsArg = zodErrorPart(fallback);
|
|
750
|
+
parts.push(`.refine((val)=>{const Schema=${containsZod};return val.some((item)=>Schema.safeParse(item).success)}${containsArg})`);
|
|
751
|
+
} else {
|
|
752
|
+
const effectiveMin = minC ?? 1;
|
|
753
|
+
if (effectiveMin > 0) {
|
|
754
|
+
const minContainsMessage = schema["x-minContains-message"] ?? fallback;
|
|
755
|
+
const minContainsArg = zodErrorPart(minContainsMessage);
|
|
756
|
+
parts.push(`.refine((val)=>{const Schema=${containsZod};return val.filter((item)=>Schema.safeParse(item).success).length>=${effectiveMin}}${minContainsArg})`);
|
|
757
|
+
}
|
|
758
|
+
if (maxC !== void 0) {
|
|
759
|
+
const maxContainsMessage = schema["x-maxContains-message"] ?? fallback;
|
|
760
|
+
const maxContainsArg = zodErrorPart(maxContainsMessage);
|
|
761
|
+
parts.push(`.refine((val)=>{const Schema=${containsZod};return val.filter((item)=>Schema.safeParse(item).success).length<=${maxC}}${maxContainsArg})`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
return parts.join("");
|
|
765
|
+
})();
|
|
766
|
+
const { minItems, maxItems } = schema;
|
|
767
|
+
return readonly(zodWrap$1(wireArray(typeof minItems === "number" && typeof maxItems === "number" ? minItems === maxItems ? `${base}.length(${minItems}${fixedItemsError})${unique}${containsChain}` : `${base}.min(${minItems}${minError}).max(${maxItems}${maxError})${unique}${containsChain}` : typeof minItems === "number" ? `${base}.min(${minItems}${minError})${unique}${containsChain}` : typeof maxItems === "number" ? `${base}.max(${maxItems}${maxError})${unique}${containsChain}` : `${base}${unique}${containsChain}`), schema));
|
|
768
|
+
}
|
|
769
|
+
if (types.includes("object")) return readonly(zodWrap$1(object(schema, rootName, isZod, options), schema));
|
|
770
|
+
if (types.includes("date")) {
|
|
771
|
+
const errorMessage = schema["x-error-message"];
|
|
772
|
+
const errorArg = errorMessage ? zodError(errorMessage) : "";
|
|
773
|
+
return zodWrap$1(`z.${schema["x-coerce"] === true || isStringWireParam ? "coerce." : ""}date(${errorArg})`, schema);
|
|
774
|
+
}
|
|
775
|
+
if (types.length === 1 && types[0] === "null") {
|
|
776
|
+
const errorMessage = schema["x-error-message"];
|
|
777
|
+
return zodWrap$1(`z.null(${errorMessage ? zodError(errorMessage) : ""})`, schema);
|
|
778
|
+
}
|
|
779
|
+
if (typeof schema.additionalProperties === "object") return readonly(zodWrap$1(object(schema, rootName, isZod, options), schema));
|
|
780
|
+
return zodWrap$1("z.any()", schema);
|
|
781
|
+
}
|
|
782
|
+
//#endregion
|
|
783
|
+
//#region src/generator/zod/index.ts
|
|
784
|
+
/**
|
|
785
|
+
* A whole JSON Schema document as a Zod module: imports, `$defs` in dependency order,
|
|
786
|
+
* the root export, and the inferred type.
|
|
787
|
+
*/
|
|
788
|
+
function schemaToZod(input, options) {
|
|
789
|
+
const schema = withPolymorphicBases(hoistNestedRefs(input));
|
|
790
|
+
const exportType = options?.exportType ?? true;
|
|
791
|
+
const baseOptions = emitOptionsOf(options);
|
|
792
|
+
const codeExtensionsPresent = baseOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0;
|
|
793
|
+
const toName = schemaNamer(baseOptions.openapi);
|
|
794
|
+
const plan = planDocument(schema, rootNameOf(schema, toName));
|
|
795
|
+
const definitions = definitionsOf(baseOptions, plan.definitions);
|
|
796
|
+
const emitOptions = definitions === void 0 ? baseOptions : {
|
|
797
|
+
...baseOptions,
|
|
798
|
+
definitions
|
|
799
|
+
};
|
|
800
|
+
const { rootName } = plan;
|
|
801
|
+
const needsTypeDef = plan.hasDefinitions || hasRootSelfReference(schema);
|
|
802
|
+
const typeDefsCode = needsTypeDef ? [`type _${rootName} = ${type(plan.root, rootName)}`, renderDefinitions(plan, toName, (def, name) => `type _${name} = ${type(def, name)}`)].filter(Boolean).join("\n\n") : "";
|
|
803
|
+
const schemaDefsCode = renderDefinitions(plan, toName, (def, name) => `const ${name}: z.ZodType<_${name}> = ${zod(def, name, true, emitOptions)}`);
|
|
804
|
+
const rootSchema = zod(plan.root, rootName, true, emitOptions);
|
|
805
|
+
const rootExport = needsTypeDef ? `export const ${rootName}: z.ZodType<_${rootName}> = ${rootSchema}` : `export const ${rootName} = ${rootSchema}`;
|
|
806
|
+
return [
|
|
807
|
+
...codeExtensionsPresent ? [UNSAFE_GENERATED_MARKER] : [],
|
|
808
|
+
`import * as z from 'zod'`,
|
|
809
|
+
typeDefsCode,
|
|
810
|
+
schemaDefsCode,
|
|
811
|
+
rootExport,
|
|
812
|
+
...exportType ? [`export type ${rootName} = z.infer<typeof ${rootName}>`] : []
|
|
813
|
+
].filter(Boolean).join("\n\n");
|
|
814
|
+
}
|
|
815
|
+
//#endregion
|
|
816
|
+
export { zod as n, schemaToZod as t };
|