schema-truth 0.7.0 → 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/dist/{ajv-DTP2FXRr.js → ajv-DS9gtNZC.js} +1 -1
- package/dist/ajv.d.ts +1 -1
- package/dist/ajv.js +1 -1
- package/dist/{arktype-BdvvaBQX.js → arktype-CRZ8vXZ5.js} +94 -37
- package/dist/arktype.d.ts +3 -3
- package/dist/arktype.js +1 -1
- package/dist/cli/ajv.js +2 -2
- package/dist/cli/arktype.js +2 -2
- package/dist/cli/effect.js +2 -2
- package/dist/cli/typebox.js +2 -2
- package/dist/cli/valibot.js +2 -2
- package/dist/cli/yup.js +2 -2
- package/dist/cli/zod.js +2 -2
- package/dist/{cli-CL2mSark.js → cli-eAY8LqwP.js} +2 -2
- package/dist/{effect-mUknRPv_.js → effect-BkWovUi3.js} +52 -19
- package/dist/effect.d.ts +3 -3
- package/dist/effect.js +1 -1
- package/dist/{helper-Cfvb5UDq.js → helper-CbeedY35.js} +721 -38
- package/dist/{index-C2L8Ty0-.d.ts → index-DYzAccyT.d.ts} +29 -25
- package/dist/{index-DbV3dEmN.d.ts → index-G7UqNQ4w.d.ts} +54 -2
- package/dist/index.d.ts +54 -25
- package/dist/index.js +9 -9
- package/dist/{typebox-BdWJv3ND.js → typebox-wYeJqy7T.js} +33 -14
- package/dist/typebox.d.ts +3 -3
- package/dist/typebox.js +1 -1
- package/dist/{utils-WNBq1HR0.js → utils-Bky98UmP.js} +160 -31
- package/dist/{valibot-CaJIynCH.js → valibot-DQUEDYKt.js} +64 -23
- package/dist/valibot.d.ts +3 -3
- package/dist/valibot.js +1 -1
- package/dist/{yup-CM2TSFig.js → yup-BMpa9Co1.js} +2 -2
- package/dist/yup.d.ts +2 -2
- package/dist/yup.js +1 -1
- package/dist/{zod-BsXLZfwK.js → zod-Dq9LtqPL.js} +130 -91
- package/dist/zod.d.ts +3 -3
- package/dist/zod.js +1 -1
- package/package.json +1 -1
|
@@ -158,6 +158,17 @@ const STRINGBOOL_PATTERN = /^(?:true|1|yes|on|y|enabled|false|0|no|off|n|disable
|
|
|
158
158
|
const STRINGBOOL_TRUTHY_PATTERN = /^(?:true|1|yes|on|y|enabled)$/i;
|
|
159
159
|
/** The text of a 64-bit integer: a sign and digits, which `BigInt` reads losslessly. */
|
|
160
160
|
const INTEGER_TEXT_PATTERN = /^-?\d+$/;
|
|
161
|
+
/**
|
|
162
|
+
* Integer text on the string wire. A sign and digits, with no leading zero, no exponent
|
|
163
|
+
* and no fraction: `Number` and `parseInt` both accept more than this (`""`, `" "`,
|
|
164
|
+
* `"0x10"`, `"1e3"`, `"1.9xyz"`).
|
|
165
|
+
*/
|
|
166
|
+
const INTEGER_WIRE_PATTERN = /^-?(?:0|[1-9]\d*)$/;
|
|
167
|
+
/**
|
|
168
|
+
* Number text on the string wire: the JSON number grammar (RFC 8259). An exponent is a
|
|
169
|
+
* number (`1e3`) and is not an integer. Blank, hex and trailing junk are not numbers.
|
|
170
|
+
*/
|
|
171
|
+
const NUMBER_WIRE_PATTERN = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
|
|
161
172
|
/** The range of each fixed-width numeric format, as the literals the generators emit. */
|
|
162
173
|
const NUMBER_RANGES = {
|
|
163
174
|
int32: {
|
|
@@ -849,56 +860,174 @@ function normalizeTypes(t) {
|
|
|
849
860
|
}
|
|
850
861
|
/**
|
|
851
862
|
* Reconcile a schema's `default` value with the type the schema actually emits
|
|
852
|
-
* so the generated `.default(...)` stays assignable.
|
|
863
|
+
* so the generated `.default(...)` stays assignable. The default is kept only
|
|
864
|
+
* when it is a value of the schema, read the way a document usually writes it:
|
|
853
865
|
*
|
|
854
|
-
* - `null` on a
|
|
855
|
-
*
|
|
856
|
-
* - a
|
|
857
|
-
*
|
|
858
|
-
*
|
|
866
|
+
* - `null` is kept only on a nullable schema (or one whose `enum` lists it).
|
|
867
|
+
* - an `enum` / `const` takes only what it lists.
|
|
868
|
+
* - text that spells a value of the schema's type is read as that value: `'true'`
|
|
869
|
+
* for a boolean, `'7'` for a number or an integer; a number or a boolean for a
|
|
870
|
+
* string is written as text. Any other scalar of the wrong type is dropped
|
|
871
|
+
* (`'null'` for an integer, `'strict'` with the quotes for an enum).
|
|
872
|
+
* - an array keeps its items when every one is a value of `items`.
|
|
873
|
+
* - an object default drops keys the schema does not declare, when the emitted
|
|
874
|
+
* object has no index signature (`additionalProperties` is not `true` or a
|
|
875
|
+
* schema, and there are no `patternProperties`), and needs every `required`
|
|
876
|
+
* key. A loose or record schema keeps every key.
|
|
877
|
+
* - a `$ref`, or an `allOf` the node has no type of its own beside, is read as
|
|
878
|
+
* the definition it names when `definitions` has it; a `oneOf` / `anyOf` keeps
|
|
879
|
+
* the default when a member takes it, whatever `type` sits beside it.
|
|
880
|
+
* - a node with nothing to check against (no `type`, an unknown `$ref`) keeps
|
|
881
|
+
* the default as written.
|
|
859
882
|
*
|
|
860
|
-
*
|
|
861
|
-
*
|
|
862
|
-
* mismatches and schemas without an explicit `type` (`oneOf`/`$ref` only)
|
|
863
|
-
* pass through untouched — JSON Schema 2020-12 §9.9.4.1 treats `default` as
|
|
864
|
-
* an annotation with no validity guarantee, so anything finer would need a
|
|
865
|
-
* full validator.
|
|
883
|
+
* JSON Schema 2020-12 §9.9.4.1 treats `default` as an annotation with no
|
|
884
|
+
* validity guarantee, so an invalid one is dropped rather than reported.
|
|
866
885
|
*
|
|
867
886
|
* @example
|
|
868
887
|
* ```ts
|
|
869
|
-
* coerceDefault({ type: 'boolean' }, 'true')
|
|
870
|
-
* coerceDefault({ type: '
|
|
888
|
+
* coerceDefault({ type: 'boolean' }, 'true') // { keep: true, value: true }
|
|
889
|
+
* coerceDefault({ type: 'number' }, '7') // { keep: true, value: 7 }
|
|
890
|
+
* coerceDefault({ type: 'object' }, null) // { keep: false, value: null }
|
|
871
891
|
* coerceDefault({ type: 'object', nullable: true }, null) // { keep: true, value: null }
|
|
872
|
-
* coerceDefault({ type: 'array' }, 'eval')
|
|
892
|
+
* coerceDefault({ type: 'array' }, 'eval') // { keep: false, value: 'eval' }
|
|
893
|
+
* coerceDefault({ enum: ['a', 'b'] }, "'a'") // { keep: false, value: "'a'" }
|
|
873
894
|
* ```
|
|
874
895
|
*/
|
|
875
|
-
function coerceDefault(schema, value) {
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
896
|
+
function coerceDefault(schema, value, definitions) {
|
|
897
|
+
return conformDefault(schema, value, definitions, /* @__PURE__ */ new Set());
|
|
898
|
+
}
|
|
899
|
+
function conformDefault(schema, value, definitions, reading) {
|
|
900
|
+
const drop = {
|
|
879
901
|
keep: false,
|
|
880
902
|
value
|
|
881
903
|
};
|
|
882
|
-
|
|
904
|
+
const asIs = {
|
|
883
905
|
keep: true,
|
|
884
|
-
value: value === "true"
|
|
885
|
-
};
|
|
886
|
-
const isComposite = Array.isArray(value) || typeof value === "object" && value !== null;
|
|
887
|
-
const allowsComposite = types.length === 0 || types.includes("array") || types.includes("object");
|
|
888
|
-
if (isComposite && !allowsComposite) return {
|
|
889
|
-
keep: false,
|
|
890
906
|
value
|
|
891
907
|
};
|
|
892
|
-
const
|
|
893
|
-
if (
|
|
894
|
-
|
|
908
|
+
const conform = (s, v, r = reading) => conformDefault(s, v, definitions, r);
|
|
909
|
+
if (schema.$ref !== void 0) {
|
|
910
|
+
const target = reading.has(schema.$ref) ? void 0 : definitionOf(schema.$ref, definitions);
|
|
911
|
+
if (target === void 0) return value === null && schema.nullable !== true ? drop : asIs;
|
|
912
|
+
const { $ref, ...beside } = schema;
|
|
913
|
+
return conform({
|
|
914
|
+
...target,
|
|
915
|
+
...beside
|
|
916
|
+
}, value, /* @__PURE__ */ new Set([...reading, $ref]));
|
|
917
|
+
}
|
|
918
|
+
const types = normalizeTypes(schema.type);
|
|
919
|
+
const isNullable = schema.nullable === true || types.includes("null") || schema.enum?.includes(null) === true || schema.const === null;
|
|
920
|
+
if (value === null) {
|
|
921
|
+
if (isNullable) return asIs;
|
|
922
|
+
return [...schema.oneOf ?? [], ...schema.anyOf ?? []].some((member) => conform(member, null).keep) ? asIs : drop;
|
|
923
|
+
}
|
|
924
|
+
const members = schema.oneOf ?? schema.anyOf;
|
|
925
|
+
if (members !== void 0 && members.length > 0) {
|
|
926
|
+
const results = members.map((member) => conform(member, value));
|
|
927
|
+
return results.find((result) => result.keep && result.value === value) ?? results.find((result) => result.keep) ?? drop;
|
|
928
|
+
}
|
|
929
|
+
if (schema.enum !== void 0) return schema.enum.some((member) => member === value) ? asIs : drop;
|
|
930
|
+
if (schema.const !== void 0) return JSON.stringify(schema.const) === JSON.stringify(value) ? asIs : drop;
|
|
931
|
+
if (types.length === 0 && schema.allOf !== void 0) return schema.allOf.filter((member) => {
|
|
932
|
+
const memberTypes = normalizeTypes(member.type);
|
|
933
|
+
return memberTypes.length === 0 || memberTypes.some((t) => t !== "null");
|
|
934
|
+
}).reduce((result, member) => result.keep ? conform(member, result.value) : result, asIs);
|
|
935
|
+
const valueTypes = types.filter((t) => t !== "null");
|
|
936
|
+
if (types.length > 0 && valueTypes.length === 0) return drop;
|
|
937
|
+
if (valueTypes.length === 0) return schema.properties !== void 0 ? readObject(schema, value, conform) ?? drop : asIs;
|
|
938
|
+
const read = (type) => {
|
|
939
|
+
if (type === "boolean") {
|
|
940
|
+
if (typeof value === "boolean") return asIs;
|
|
941
|
+
if (value === "true" || value === "false") return {
|
|
942
|
+
keep: true,
|
|
943
|
+
value: value === "true"
|
|
944
|
+
};
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
if (type === "number" || type === "integer") {
|
|
948
|
+
const number = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value)) ? Number(value) : void 0;
|
|
949
|
+
if (number === void 0) return void 0;
|
|
950
|
+
if (type === "integer" && !Number.isInteger(number)) return void 0;
|
|
951
|
+
return {
|
|
952
|
+
keep: true,
|
|
953
|
+
value: number
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
if (type === "string") {
|
|
957
|
+
if (typeof value === "string") return asIs;
|
|
958
|
+
if (typeof value === "number" || typeof value === "boolean") return {
|
|
959
|
+
keep: true,
|
|
960
|
+
value: String(value)
|
|
961
|
+
};
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
if (type === "array") {
|
|
965
|
+
if (!Array.isArray(value)) return void 0;
|
|
966
|
+
const items = schema.items;
|
|
967
|
+
if (!isDefaultSchemaObject(items)) return asIs;
|
|
968
|
+
const readItems = value.map((item) => conform(items, item));
|
|
969
|
+
return readItems.every((item) => item.keep) ? {
|
|
970
|
+
keep: true,
|
|
971
|
+
value: readItems.map((item) => item.value)
|
|
972
|
+
} : void 0;
|
|
973
|
+
}
|
|
974
|
+
if (type === "object") return readObject(schema, value, conform);
|
|
975
|
+
return asIs;
|
|
976
|
+
};
|
|
977
|
+
const own = valueTypes.find((type) => typeOf(value) === type || type === "number" && typeof value === "number");
|
|
978
|
+
return (own === void 0 ? void 0 : read(own)) ?? valueTypes.map(read).find((r) => r !== void 0) ?? drop;
|
|
979
|
+
}
|
|
980
|
+
/** An object default as a value of the schema, or `undefined` when it is not one. */
|
|
981
|
+
function readObject(schema, value, conform) {
|
|
982
|
+
if (!isDeclaredObject(value)) return void 0;
|
|
983
|
+
if (schema.properties === void 0 || canHoldUndeclaredKeys(schema)) return {
|
|
984
|
+
keep: true,
|
|
895
985
|
value
|
|
896
986
|
};
|
|
987
|
+
const declared = schema.properties;
|
|
988
|
+
if ((schema.required ?? []).some((key) => !Object.hasOwn(value, key))) return void 0;
|
|
989
|
+
const kept = {};
|
|
990
|
+
for (const [key, item] of Object.entries(value)) {
|
|
991
|
+
if (!Object.hasOwn(declared, key)) continue;
|
|
992
|
+
const result = conform(declared[key], item);
|
|
993
|
+
if (!result.keep) return void 0;
|
|
994
|
+
kept[key] = result.value;
|
|
995
|
+
}
|
|
897
996
|
return {
|
|
898
997
|
keep: true,
|
|
899
|
-
value
|
|
998
|
+
value: kept
|
|
900
999
|
};
|
|
901
1000
|
}
|
|
1001
|
+
/** The definition a local `$ref` names, when `definitions` has it. */
|
|
1002
|
+
function definitionOf(ref, definitions) {
|
|
1003
|
+
if (definitions === void 0) return void 0;
|
|
1004
|
+
for (const prefix of DEFINITION_REF_PREFIXES) {
|
|
1005
|
+
if (!ref.startsWith(prefix)) continue;
|
|
1006
|
+
const rest = ref.slice(prefix.length);
|
|
1007
|
+
if (rest === "" || rest.includes("/")) return void 0;
|
|
1008
|
+
const name = decodeURIComponent(rest);
|
|
1009
|
+
return Object.hasOwn(definitions, name) ? definitions[name] : void 0;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
function typeOf(value) {
|
|
1013
|
+
if (typeof value === "boolean") return "boolean";
|
|
1014
|
+
if (typeof value === "number") return Number.isInteger(value) ? "integer" : "number";
|
|
1015
|
+
if (typeof value === "string") return "string";
|
|
1016
|
+
if (Array.isArray(value)) return "array";
|
|
1017
|
+
if (isDeclaredObject(value)) return "object";
|
|
1018
|
+
}
|
|
1019
|
+
function isDefaultSchemaObject(value) {
|
|
1020
|
+
return typeof value === "object" && !Array.isArray(value);
|
|
1021
|
+
}
|
|
1022
|
+
function isDeclaredObject(value) {
|
|
1023
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1024
|
+
}
|
|
1025
|
+
/** Whether a generated object type accepts keys the schema does not name. */
|
|
1026
|
+
function canHoldUndeclaredKeys(schema) {
|
|
1027
|
+
if (schema.additionalProperties === true || typeof schema.additionalProperties === "object") return true;
|
|
1028
|
+
if (schema.patternProperties !== void 0) return true;
|
|
1029
|
+
return schema.unevaluatedProperties === true || typeof schema.unevaluatedProperties === "object";
|
|
1030
|
+
}
|
|
902
1031
|
/**
|
|
903
1032
|
* A message as the expression an emitted check evaluates for each issue: an arrow source
|
|
904
1033
|
* is applied to the issue, a sentence becomes a string literal.
|
|
@@ -1014,4 +1143,4 @@ function makeSafeKey(key) {
|
|
|
1014
1143
|
return isValidIdentifier(key) ? key : JSON.stringify(key);
|
|
1015
1144
|
}
|
|
1016
1145
|
//#endregion
|
|
1017
|
-
export { DEFINITION_REF_PREFIXES as $, isDefinitionKeyword as A,
|
|
1146
|
+
export { DEFINITION_REF_PREFIXES as $, isDefinitionKeyword as A, UNSAFE_GENERATED_MARKER as At, isSchemaObject as B, hasNumericKeyword as C, ROOT_REFS as Ct, isComposite as D, STRING_KEYWORDS as Dt, isArktypeDefinition as E, STRING_FORMATS as Et, isPrimitive as F, ARKTYPE_CODE_EXTENSION_KEYS as G, isStringWireLocation as H, isQuoted as I, CONTENT_ENCODINGS as J, ARROW_FUNCTION_PATTERN as K, isRecord as L, isNullable as M, WIRE_PRIMITIVE_ORDER as Mt, isObjectPrototypeProperty as N, ZOD_CODE_EXTENSION_KEYS as Nt, isDeepLocalPointer as O, STRING_WIRE_LOCATIONS as Ot, isPlainObject as P, DEFINITION_POINTER_PATTERN as Q, isRootRef as R, hasFixedLength as S, QUOTE_OR_BACKSLASH_PATTERN as St, hasType as T, STRINGBOOL_TRUTHY_PATTERN as Tt, ALL_CODE_EXTENSION_KEYS as U, isShapelessMember as V, ANCHOR_REF_PATTERN as W, DEFAULT_ROOT_NAME as X, DATE_PATTERN_SOURCE as Y, DEFINITION_KEYWORDS as Z, canBeNull as _, OFFSET_PATTERN_SOURCE as _t, encodeNonAscii as a, INTEGER_TEXT_PATTERN as at, hasConditional as b, PARAM_LOCATIONS as bt, normalizeTypes as c, JSON_SCHEMA_TYPES as ct, toPascalCase as d, NOT_KEYWORD_UNSUPPORTED_MARKER as dt, EFFECT_CODE_EXTENSION_KEYS as et, valibotError as f, NUMBER_FORMATS as ft, zodErrorPart as g, OBJECT_PROTOTYPE_PROPERTIES as gt, zodError as h, NUMERIC_KEYWORDS as ht, effectMessage as i, INPUT_EXTENSIONS as it, isNullTypeMember as j, VALIBOT_CODE_EXTENSION_KEYS as jt, isDefaultOnlyMember as k, UNICODE_ESCAPE_PATTERN as kt, resolveOpenAPIRef as l, MISSING_DEFINITION_PREFIX as lt, zodBaseError as m, NUMBER_WIRE_PATTERN as mt, effectError as n, IDENTIFIER_PATTERN as nt, issueMessageExpression as o, INTEGER_WIRE_PATTERN as ot, valibotErrorPart as p, NUMBER_RANGES as pt, COMPONENT_SCHEMA_REF_PREFIX as q, effectErrorPart as r, IF_THEN_ELSE_UNSUPPORTED_MARKER as rt, makeSafeKey as s, ISO_4217_CURRENCY_CODES as st, coerceDefault as t, FORMAT_PATTERNS as tt, toIdentifierPascalCase as u, NON_IDENTIFIER_CHARACTER_PATTERN as ut, canBeString as v, OPENAPI_COMPONENT_SUFFIX_MAP as vt, hasStringKeyword as w, STRINGBOOL_PATTERN as wt, hasFixedItemCount as x, PARAM_STYLES as xt, hasCombinator as y, OUTPUT_EXTENSION as yt, isSchemaList as z };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as isSchemaObject, F as isPrimitive, H as isStringWireLocation, M as isNullable, N as isObjectPrototypeProperty,
|
|
2
|
-
import {
|
|
1
|
+
import { At as UNSAFE_GENERATED_MARKER, B as isSchemaObject, F as isPrimitive, H as isStringWireLocation, M as isNullable, N as isObjectPrototypeProperty, S as hasFixedLength, T as hasType, V as isShapelessMember, X as DEFAULT_ROOT_NAME, at as INTEGER_TEXT_PATTERN, b as hasConditional, c as normalizeTypes, f as valibotError, j as isNullTypeMember, k as isDefaultOnlyMember, o as issueMessageExpression, p as valibotErrorPart, pt as NUMBER_RANGES, s as makeSafeKey, x as hasFixedItemCount, y as hasCombinator } from "./utils-Bky98UmP.js";
|
|
2
|
+
import { B as emitOptionsOf, C as isPrimitiveUnion, D as stringboolTruthyPattern, E as stringboolPattern, F as jsLiteral, G as schemaNamer, H as planDocument, J as isOptionalByDefault, M as formatPattern, N as regexSource, O as unionPrimitiveTypes, Q as findCodeExtensionKeysInSchema, S as isNullTextRead, T as ownProperties, 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, n as valibotWrap, nt as foldAllOfMembers, o as typeDeclaration, p as isBigintFormat, q as hasRootSelfReference, r as evaluatedProperties, rt as isKeywordOnlyMember, s as refTarget, tt as constraintPredicate, u as parameterReaders, w as numberWirePattern, y as impliedWireType, z as definitionsOf } from "./helper-CbeedY35.js";
|
|
3
3
|
//#region src/generator/valibot/type.ts
|
|
4
4
|
/** The TypeScript type declared beside a recursive Valibot schema: its output type. */
|
|
5
5
|
function type(schema, rootName = DEFAULT_ROOT_NAME) {
|
|
@@ -41,8 +41,9 @@ function rangeActions(format) {
|
|
|
41
41
|
return [`v.minValue(${range.minimum})`, `v.maxValue(${range.maximum})`];
|
|
42
42
|
}
|
|
43
43
|
/**
|
|
44
|
-
* The Valibot schema of a number node. On the string wire the text
|
|
45
|
-
*
|
|
44
|
+
* The Valibot schema of a number node. On the string wire the text has to match the JSON
|
|
45
|
+
* number grammar before `Number` reads it, then it is checked finite; `float` / `float32`
|
|
46
|
+
* carries its range.
|
|
46
47
|
*/
|
|
47
48
|
function number(schema, options) {
|
|
48
49
|
const errorMessage = schema["x-error-message"];
|
|
@@ -55,7 +56,10 @@ function number(schema, options) {
|
|
|
55
56
|
...numberActions(schema)
|
|
56
57
|
];
|
|
57
58
|
const base = `v.number(${baseErrorArg})`;
|
|
58
|
-
if (options?.wire === true)
|
|
59
|
+
if (options?.wire === true) {
|
|
60
|
+
const regexError = baseErrorArg === "" ? "" : `,${baseErrorArg}`;
|
|
61
|
+
return `v.pipe(v.string(),v.regex(${numberWirePattern()}${regexError}),v.transform((input)=>Number(input)),${base},${actions.join(",")})`;
|
|
62
|
+
}
|
|
59
63
|
if (actions.length > 0) return `v.pipe(${base},${actions.join(",")})`;
|
|
60
64
|
return errorMessage ? base : "v.number()";
|
|
61
65
|
}
|
|
@@ -82,7 +86,8 @@ function int64Input(isWire, baseErrorArg = "") {
|
|
|
82
86
|
/**
|
|
83
87
|
* The Valibot schema of an integer node. `int64` / `uint64` are bigints wherever they
|
|
84
88
|
* come from, `bigint` is one too, `int32` / `uint32` carry their range, and on the
|
|
85
|
-
* string wire the text
|
|
89
|
+
* string wire the text has to match the integer grammar before `Number` reads it, and is
|
|
90
|
+
* then checked a safe integer.
|
|
86
91
|
*/
|
|
87
92
|
function integer(schema, options) {
|
|
88
93
|
const isWire = options?.wire === true;
|
|
@@ -110,8 +115,13 @@ function integer(schema, options) {
|
|
|
110
115
|
...rangeActions(schema.format),
|
|
111
116
|
...numberActions(schema)
|
|
112
117
|
];
|
|
118
|
+
const regexError = baseErrorArg === "" ? "" : `,${baseErrorArg}`;
|
|
113
119
|
return `v.pipe(${[
|
|
114
|
-
...isWire ? [
|
|
120
|
+
...isWire ? [
|
|
121
|
+
"v.string()",
|
|
122
|
+
`v.regex(${integerWirePattern()}${regexError})`,
|
|
123
|
+
"v.transform((input)=>Number(input))"
|
|
124
|
+
] : [],
|
|
115
125
|
`v.number(${baseErrorArg})`,
|
|
116
126
|
...actions
|
|
117
127
|
].join(",")})`;
|
|
@@ -227,12 +237,12 @@ function object(schema, rootName, isValibot, options) {
|
|
|
227
237
|
const conditionalKeysReferenced = hasConditional(schema);
|
|
228
238
|
const objectKind = schema.additionalProperties === true ? "looseObject" : schema.additionalProperties === false || schema.unevaluatedProperties === false ? "strictObject" : conditionalKeysReferenced ? "looseObject" : "object";
|
|
229
239
|
const required = new Set(schema.required);
|
|
230
|
-
const hasOwnDefault = Object.values(schema.properties).some(isOptionalByDefault);
|
|
240
|
+
const hasOwnDefault = Object.values(schema.properties).some((propSchema) => isOptionalByDefault(propSchema, options?.definitions));
|
|
231
241
|
const props = Object.entries(schema.properties).map(([key, propSchema]) => {
|
|
232
|
-
const parsed = valibot(propSchema, rootName, isValibot, options);
|
|
242
|
+
const parsed = valibot(propSchema, rootName, isValibot, propertyEmitOptions(key, propSchema, options) ?? options);
|
|
233
243
|
if (!parsed) return null;
|
|
234
244
|
const safeKey = makeSafeKey(key);
|
|
235
|
-
return required.has(key) || isOptionalByDefault(propSchema) ? `${safeKey}:${parsed}` : `${safeKey}:v.optional(${parsed})`;
|
|
245
|
+
return required.has(key) || isOptionalByDefault(propSchema, options?.definitions) ? `${safeKey}:${parsed}` : `${safeKey}:v.optional(${parsed})`;
|
|
236
246
|
}).filter((p) => p !== null);
|
|
237
247
|
const strictMessageArg = objectKind === "strictObject" ? valibotErrorPart(strictExtrasMessage) : "";
|
|
238
248
|
const rawBase = required.size === 0 && !hasOwnDefault && props.every((p) => p.includes("v.optional(")) ? `v.partial(v.${objectKind}({${props.map((p) => p.replace(/^(.+?):v\.optional\((.+)\)$/u, "$1:$2")).join(",")}}${strictMessageArg}))` : `v.${objectKind}({${props.join(",")}}${strictMessageArg})`;
|
|
@@ -402,6 +412,20 @@ function elementMessageWrap(inner, msg) {
|
|
|
402
412
|
return `v.pipe(v.unknown(),v.rawCheck(({dataset,addIssue})=>{if(!dataset.typed)return;const result=v.safeParse(${inner},dataset.value);if(!result.success){for(const issue of result.issues){if(issue.path&&issue.path.length>0){addIssue({message:${issueMessageExpression(msg)},path:issue.path})}else{addIssue(issue)}}}}))`;
|
|
403
413
|
}
|
|
404
414
|
/**
|
|
415
|
+
* An `allOf` with `unevaluatedProperties` beside it: the members' objects strip what they
|
|
416
|
+
* do not declare, so the keys no member evaluates are checked on the input before it is
|
|
417
|
+
* parsed. `inner` as given when the keyword is absent or every key is evaluated.
|
|
418
|
+
*/
|
|
419
|
+
function unevaluatedPropertiesCheck(inner, schema, rootName, isValibot, options) {
|
|
420
|
+
const unevaluated = schema.unevaluatedProperties;
|
|
421
|
+
if (unevaluated !== false && (typeof unevaluated !== "object" || unevaluated === null)) return inner;
|
|
422
|
+
const evaluated = evaluatedProperties(schema, options?.definitions);
|
|
423
|
+
if (evaluated === void 0) return inner;
|
|
424
|
+
const isEvaluated = isEvaluatedKeyExpression(evaluated, "k");
|
|
425
|
+
const message = schema["x-unevaluatedProperties-message"];
|
|
426
|
+
return `v.pipe(v.unknown(),v.rawCheck(({dataset,addIssue})=>{if(!dataset.typed)return;const o=dataset.value;if(typeof o!=='object'||o===null||Array.isArray(o))return;${unevaluated === false ? `for(const k of Object.keys(o)){if(${isEvaluated})continue;addIssue({message:${message === void 0 ? `'Unevaluated property: '+k` : JSON.stringify(message)}})}` : `const Unevaluated=${valibot(unevaluated, rootName, isValibot, options)};for(const [k,val] of Object.entries(o)){if(${isEvaluated})continue;const result=v.safeParse(Unevaluated,val);if(!result.success){for(const issue of result.issues){addIssue({message:${message === void 0 ? "issue.message" : JSON.stringify(message)}})}}}`}}),${inner})`;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
405
429
|
* Generate Valibot schema code from JSON Schema.
|
|
406
430
|
*
|
|
407
431
|
* @example
|
|
@@ -416,6 +440,10 @@ function valibot(schema, rootName = DEFAULT_ROOT_NAME, isValibot = false, option
|
|
|
416
440
|
}
|
|
417
441
|
return node(schema, rootName, isValibot, options);
|
|
418
442
|
}
|
|
443
|
+
/** A keyword-only `allOf` member: the keywords apply when the value has their type. */
|
|
444
|
+
function keywordConstraint(schema) {
|
|
445
|
+
return `v.pipe(v.any(),v.check((input) => ${constraintPredicate(schema, "input")}${valibotErrorPart(constraintMessage(schema))}))`;
|
|
446
|
+
}
|
|
419
447
|
function node(schema, rootName, isValibot, options) {
|
|
420
448
|
const isStringWireParam = isStringWireLocation(options?.paramIn);
|
|
421
449
|
const isWireCoerced = isStringWireParam && schema["x-coerce"] !== false;
|
|
@@ -429,14 +457,19 @@ function node(schema, rootName, isValibot, options) {
|
|
|
429
457
|
};
|
|
430
458
|
const valibotWrap$1 = (valibotStr, s) => valibotWrap(valibotStr, s, {
|
|
431
459
|
...codeExtOpts,
|
|
432
|
-
...wireOptions(s)
|
|
460
|
+
...wireOptions(s),
|
|
461
|
+
...options?.definitions !== void 0 && { definitions: options.definitions }
|
|
433
462
|
});
|
|
434
463
|
const readonly = (v) => options?.readonly ? `v.pipe(${v},v.readonly())` : v;
|
|
435
464
|
const wireArray = (v) => isStringWireParam ? preprocess([wireArrayOnce("input")], v) : v;
|
|
436
465
|
const literalInput = (values) => {
|
|
437
466
|
if (values.every((v) => typeof v === "number")) {
|
|
438
467
|
if (isInt64(schema)) return int64Input(isWireCoerced);
|
|
439
|
-
if (isWireCoerced) return [
|
|
468
|
+
if (isWireCoerced) return [
|
|
469
|
+
"v.string()",
|
|
470
|
+
`v.regex(${wireNumericKind(schema, values) === "integer" ? integerWirePattern() : numberWirePattern()})`,
|
|
471
|
+
"v.transform((input)=>Number(input))"
|
|
472
|
+
];
|
|
440
473
|
}
|
|
441
474
|
if (isWireCoerced && values.every((v) => typeof v === "boolean")) return stringboolItems("");
|
|
442
475
|
};
|
|
@@ -477,19 +510,19 @@ function node(schema, rootName, isValibot, options) {
|
|
|
477
510
|
if (schema.allOf.length === 0) return valibotWrap$1("v.any()", schema);
|
|
478
511
|
const nullable = isNullable(schema) || schema.allOf.some(isNullTypeMember);
|
|
479
512
|
const defaultValue = schema.allOf.find(isDefaultOnlyMember)?.default;
|
|
480
|
-
const schemas = schema.allOf.filter((s) => !isShapelessMember(s)).map((s) => valibot(s, rootName, isValibot, options));
|
|
513
|
+
const schemas = foldAllOfMembers(schema.allOf.filter((s) => !isShapelessMember(s)), isWireCoerced).map((s) => isKeywordOnlyMember(s) ? keywordConstraint(s) : valibot(s, rootName, isValibot, options));
|
|
481
514
|
if (schemas.length === 0) return valibotWrap$1("v.any()", {
|
|
482
515
|
...schema,
|
|
483
516
|
nullable
|
|
484
517
|
});
|
|
485
518
|
const intersected = schemas.length === 1 ? schemas[0] : `v.intersect([${schemas.join(",")}])`;
|
|
486
519
|
const allOfMessage = schema["x-allOf-message"];
|
|
487
|
-
const
|
|
520
|
+
const checked = unevaluatedPropertiesCheck(allOfMessage ? (() => {
|
|
488
521
|
const msgExpr = issueMessageExpression(allOfMessage);
|
|
489
522
|
return `v.pipe(v.unknown(),v.rawCheck(({dataset,addIssue})=>{if(!dataset.typed)return;const result=v.safeParse(${intersected},dataset.value);if(!result.success){for(const issue of result.issues){addIssue({message:${msgExpr},path:issue.path})}}}))`;
|
|
490
|
-
})() : intersected;
|
|
491
|
-
if (defaultValue !== void 0) return `v.optional(${nullable ? `v.nullable(${
|
|
492
|
-
return valibotWrap$1(
|
|
523
|
+
})() : intersected, schema, rootName, isValibot, options);
|
|
524
|
+
if (defaultValue !== void 0) return `v.optional(${nullable ? `v.nullable(${checked})` : checked},${jsLiteral(defaultValue)})`;
|
|
525
|
+
return valibotWrap$1(checked, {
|
|
493
526
|
...schema,
|
|
494
527
|
nullable
|
|
495
528
|
});
|
|
@@ -500,9 +533,10 @@ function node(schema, rootName, isValibot, options) {
|
|
|
500
533
|
const notMessage = schema["x-not-message"];
|
|
501
534
|
const errorPart = valibotErrorPart(notMessage);
|
|
502
535
|
const predicate = (() => {
|
|
503
|
-
const
|
|
536
|
+
const bigint = isBigintFormat(withoutNot);
|
|
537
|
+
const shared = notPredicate(inner, "input", "input", bigint);
|
|
504
538
|
if (shared !== void 0) return shared;
|
|
505
|
-
if (Array.isArray(inner.enum)) return `(input) => !${
|
|
539
|
+
if (Array.isArray(inner.enum)) return `(input) => !${valueListLiteral(inner.enum, bigint)}.some((item) => item === input)`;
|
|
506
540
|
return `(input) => !v.safeParse(${valibot(inner, rootName, isValibot, options)},input).success`;
|
|
507
541
|
})();
|
|
508
542
|
if (withoutNot.type !== void 0) {
|
|
@@ -621,6 +655,7 @@ function node(schema, rootName, isValibot, options) {
|
|
|
621
655
|
return valibotWrap$1("v.date()", schema);
|
|
622
656
|
}
|
|
623
657
|
if (types.length === 1 && types[0] === "null") return valibotWrap$1("v.null()", schema);
|
|
658
|
+
if (typeof schema.additionalProperties === "object") return readonly(valibotWrap$1(object(schema, rootName, isValibot, options), schema));
|
|
624
659
|
return valibotWrap$1("v.any()", schema);
|
|
625
660
|
}
|
|
626
661
|
//#endregion
|
|
@@ -639,12 +674,18 @@ function annotation(name) {
|
|
|
639
674
|
* A whole JSON Schema document as a Valibot module: imports, `$defs` in dependency
|
|
640
675
|
* order, the root export, and the inferred output type.
|
|
641
676
|
*/
|
|
642
|
-
function schemaToValibot(
|
|
677
|
+
function schemaToValibot(input, options) {
|
|
678
|
+
const schema = withPolymorphicBases(hoistNestedRefs(input));
|
|
643
679
|
const exportType = options?.exportType ?? true;
|
|
644
|
-
const
|
|
645
|
-
const codeExtensionsPresent =
|
|
646
|
-
const toName = schemaNamer(
|
|
680
|
+
const baseOptions = emitOptionsOf(options);
|
|
681
|
+
const codeExtensionsPresent = baseOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0;
|
|
682
|
+
const toName = schemaNamer(baseOptions.openapi);
|
|
647
683
|
const plan = planDocument(schema, rootNameOf(schema, toName));
|
|
684
|
+
const definitions = definitionsOf(baseOptions, plan.definitions);
|
|
685
|
+
const emitOptions = definitions === void 0 ? baseOptions : {
|
|
686
|
+
...baseOptions,
|
|
687
|
+
definitions
|
|
688
|
+
};
|
|
648
689
|
const { rootName } = plan;
|
|
649
690
|
const needsTypeDef = plan.hasDefinitions || hasRootSelfReference(schema);
|
|
650
691
|
const typeDefsCode = needsTypeDef ? [`type _${rootName} = ${type(plan.root, rootName)}`, renderDefinitions(plan, toName, (def, name) => `type _${name} = ${type(def, name)}`)].filter(Boolean).join("\n\n") : "";
|
package/dist/valibot.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { r as JSONSchema } from "./index-
|
|
2
|
-
import { n as GenerateOptions } from "./index-
|
|
1
|
+
import { r as JSONSchema } from "./index-G7UqNQ4w.js";
|
|
2
|
+
import { n as GenerateOptions } from "./index-DYzAccyT.js";
|
|
3
3
|
//#region src/generator/valibot/index.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* A whole JSON Schema document as a Valibot module: imports, `$defs` in dependency
|
|
6
6
|
* order, the root export, and the inferred output type.
|
|
7
7
|
*/
|
|
8
|
-
export declare function schemaToValibot(
|
|
8
|
+
export declare function schemaToValibot(input: JSONSchema, options?: GenerateOptions): string;
|
|
9
9
|
//#endregion
|
package/dist/valibot.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as schemaToValibot } from "./valibot-
|
|
1
|
+
export { t as schemaToValibot } from "./valibot-DQUEDYKt.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { c as normalizeTypes, s as makeSafeKey } from "./utils-
|
|
2
|
-
import {
|
|
1
|
+
import { c as normalizeTypes, s as makeSafeKey } from "./utils-Bky98UmP.js";
|
|
2
|
+
import { G as schemaNamer, W as rootNameOf } from "./helper-CbeedY35.js";
|
|
3
3
|
//#region src/generator/yup/integer.ts
|
|
4
4
|
/**
|
|
5
5
|
* Generate a Yup integer schema as `yup.number().integer()`, with `minimum`
|
package/dist/yup.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as JSONSchema } from "./index-
|
|
2
|
-
import { n as GenerateOptions } from "./index-
|
|
1
|
+
import { r as JSONSchema } from "./index-G7UqNQ4w.js";
|
|
2
|
+
import { n as GenerateOptions } from "./index-DYzAccyT.js";
|
|
3
3
|
//#region src/generator/yup/index.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Convert a JSON Schema document to Yup schema source.
|
package/dist/yup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as schemaToYup } from "./yup-
|
|
1
|
+
export { t as schemaToYup } from "./yup-BMpa9Co1.js";
|