@warlock.js/seal 5.23.2 → 5.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/LICENSE +21 -21
- package/cjs/index.cjs +10 -5
- package/cjs/index.cjs.map +1 -1
- package/cjs/{object-DPPttDAF.cjs → object-BuKApaax.cjs} +3 -3
- package/cjs/object-BuKApaax.cjs.map +1 -0
- package/cjs/object.cjs +2 -2
- package/cjs/{required-methods-DJTm7yNP.cjs → required-methods-BOVNRtci.cjs} +12 -2
- package/cjs/required-methods-BOVNRtci.cjs.map +1 -0
- package/cjs/{string-C_pAtZPC.cjs → string-DpDpgefH.cjs} +2 -2
- package/cjs/string-DpDpgefH.cjs.map +1 -0
- package/cjs/string.cjs +2 -2
- package/esm/config.mjs.map +1 -1
- package/esm/factory/validate.mjs.map +1 -1
- package/esm/factory/validators.mjs +1 -1
- package/esm/factory/validators.mjs.map +1 -1
- package/esm/helpers/date-helpers.mjs.map +1 -1
- package/esm/helpers/get-field-value.mjs.map +1 -1
- package/esm/helpers/path-helpers.mjs.map +1 -1
- package/esm/mutators/array-mutators.mjs.map +1 -1
- package/esm/mutators/date-mutators.mjs.map +1 -1
- package/esm/mutators/number-mutators.mjs.map +1 -1
- package/esm/mutators/object-mutators.mjs.map +1 -1
- package/esm/mutators/scalar-mutators.mjs.map +1 -1
- package/esm/mutators/string-mutators.mjs.map +1 -1
- package/esm/plugins/plugin-system.mjs.map +1 -1
- package/esm/rules/array/array-rules.mjs.map +1 -1
- package/esm/rules/color/color-rules.mjs.map +1 -1
- package/esm/rules/common/enum.mjs.map +1 -1
- package/esm/rules/common/equals-field-rules.mjs.map +1 -1
- package/esm/rules/common/type-rules.mjs.map +1 -1
- package/esm/rules/conditional/forbidden-if-rules.mjs.map +1 -1
- package/esm/rules/conditional/present-if-rules.mjs.map +1 -1
- package/esm/rules/conditional/present-unless-rules.mjs.map +1 -1
- package/esm/rules/conditional/present-with-rules.mjs.map +1 -1
- package/esm/rules/conditional/present-without-rules.mjs.map +1 -1
- package/esm/rules/conditional/required-if-rules.mjs.map +1 -1
- package/esm/rules/conditional/required-unless-rules.mjs.map +1 -1
- package/esm/rules/conditional/required-with-rules.mjs.map +1 -1
- package/esm/rules/conditional/required-without-rules.mjs.map +1 -1
- package/esm/rules/core/equal.mjs.map +1 -1
- package/esm/rules/core/forbidden.mjs.map +1 -1
- package/esm/rules/core/required.mjs.map +1 -1
- package/esm/rules/core/union.mjs.map +1 -1
- package/esm/rules/core/when.mjs.map +1 -1
- package/esm/rules/date/date-comparison-rules.mjs.map +1 -1
- package/esm/rules/date/date-day-rules.mjs.map +1 -1
- package/esm/rules/date/date-field-comparison-rules.mjs.map +1 -1
- package/esm/rules/date/date-period-rules.mjs.map +1 -1
- package/esm/rules/date/date-relative-rules.mjs.map +1 -1
- package/esm/rules/date/date-special-rules.mjs.map +1 -1
- package/esm/rules/date/date.mjs.map +1 -1
- package/esm/rules/file/dimensions.mjs.map +1 -1
- package/esm/rules/file/file-size.mjs.map +1 -1
- package/esm/rules/length/length-rules.mjs.map +1 -1
- package/esm/rules/number/number-rules.mjs.map +1 -1
- package/esm/rules/scalar/accepted-rule.mjs.map +1 -1
- package/esm/rules/scalar/declined-rule.mjs.map +1 -1
- package/esm/rules/string/alpha.mjs.map +1 -1
- package/esm/rules/string/credit-card.mjs.map +1 -1
- package/esm/rules/string/email.mjs.map +1 -1
- package/esm/rules/string/matches.mjs.map +1 -1
- package/esm/rules/string/pattern.mjs.map +1 -1
- package/esm/rules/string/string-comparison.mjs.map +1 -1
- package/esm/rules/string/strong-password-rule.mjs.map +1 -1
- package/esm/rules/string/url.mjs.map +1 -1
- package/esm/rules/string/without-whitespace.mjs.map +1 -1
- package/esm/types/date-types.mjs.map +1 -1
- package/esm/validators/any-validator.mjs.map +1 -1
- package/esm/validators/array-validator.d.mts.map +1 -1
- package/esm/validators/array-validator.mjs +1 -0
- package/esm/validators/array-validator.mjs.map +1 -1
- package/esm/validators/base-validator.d.mts +2 -0
- package/esm/validators/base-validator.d.mts.map +1 -1
- package/esm/validators/base-validator.mjs +11 -1
- package/esm/validators/base-validator.mjs.map +1 -1
- package/esm/validators/boolean-validator.d.mts.map +1 -1
- package/esm/validators/boolean-validator.mjs +1 -0
- package/esm/validators/boolean-validator.mjs.map +1 -1
- package/esm/validators/date-validator.d.mts.map +1 -1
- package/esm/validators/date-validator.mjs +1 -0
- package/esm/validators/date-validator.mjs.map +1 -1
- package/esm/validators/float-validator.mjs.map +1 -1
- package/esm/validators/int-validator.mjs.map +1 -1
- package/esm/validators/literal-validator.d.mts.map +1 -1
- package/esm/validators/literal-validator.mjs +1 -3
- package/esm/validators/literal-validator.mjs.map +1 -1
- package/esm/validators/methods/equality-conditional-methods.mjs.map +1 -1
- package/esm/validators/methods/forbidden-methods.mjs.map +1 -1
- package/esm/validators/methods/present-methods.mjs.map +1 -1
- package/esm/validators/methods/required-methods.mjs.map +1 -1
- package/esm/validators/number-validator.d.mts.map +1 -1
- package/esm/validators/number-validator.mjs +1 -0
- package/esm/validators/number-validator.mjs.map +1 -1
- package/esm/validators/numeric-validator.mjs.map +1 -1
- package/esm/validators/object-validator.d.mts.map +1 -1
- package/esm/validators/object-validator.mjs +1 -1
- package/esm/validators/object-validator.mjs.map +1 -1
- package/esm/validators/record-validator.mjs.map +1 -1
- package/esm/validators/scalar-validator.d.mts.map +1 -1
- package/esm/validators/scalar-validator.mjs +1 -0
- package/esm/validators/scalar-validator.mjs.map +1 -1
- package/esm/validators/string-validator.mjs.map +1 -1
- package/esm/validators/tuple-validator.mjs.map +1 -1
- package/esm/validators/union-validator.mjs.map +1 -1
- package/llms-full.txt +1165 -1165
- package/package.json +1 -1
- package/skills/bridge-standard-schema/SKILL.md +138 -138
- package/skills/define-structural-shape/SKILL.md +138 -138
- package/skills/extend-seal-with-plugins/SKILL.md +178 -178
- package/skills/generate-json-schema/SKILL.md +143 -143
- package/skills/handle-seal-errors/SKILL.md +148 -148
- package/skills/pick-seal-primitive/SKILL.md +149 -149
- package/cjs/object-DPPttDAF.cjs.map +0 -1
- package/cjs/required-methods-DJTm7yNP.cjs.map +0 -1
- package/cjs/string-C_pAtZPC.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"strong-password-rule.mjs","names":[],"sources":["../../../../../../../../seal/src/rules/string/strong-password-rule.ts"],"sourcesContent":["import { invalidRule, VALID_RULE } from \"../../helpers\";\
|
|
1
|
+
{"version":3,"file":"strong-password-rule.mjs","names":[],"sources":["../../../../../../../../seal/src/rules/string/strong-password-rule.ts"],"sourcesContent":["import { invalidRule, VALID_RULE } from \"../../helpers\";\nimport type { SchemaRule } from \"../../types\";\n\n/**\n * Strong Password rule - validates password strength\n * Requirements:\n * - At least 8 characters\n * - At least 1 uppercase letter\n * - At least 1 lowercase letter\n * - At least 1 number\n * - At least 1 special character\n */\nexport const strongPasswordRule: SchemaRule<{ minLength?: number }> = {\n name: \"strongPassword\",\n defaultErrorMessage:\n \"The :input must be at least 8 characters and contain at least one uppercase letter, one lowercase letter, one number, and one special character\",\n async validate(value: any, context) {\n const password = String(value);\n const minLength = this.context.options.minLength ?? 8;\n\n // Check minimum length\n if (password.length < minLength) {\n return invalidRule(this, context);\n }\n\n // Check for at least one uppercase letter\n if (!/[A-Z]/.test(password)) {\n return invalidRule(this, context);\n }\n\n // Check for at least one lowercase letter\n if (!/[a-z]/.test(password)) {\n return invalidRule(this, context);\n }\n\n // Check for at least one number\n if (!/[0-9]/.test(password)) {\n return invalidRule(this, context);\n }\n\n // Check for at least one special character\n if (!/[!@#$%^&*()_+\\-=[\\]{};':\"\\\\|,.<>/?]/.test(password)) {\n return invalidRule(this, context);\n }\n\n return VALID_RULE;\n },\n};\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,qBAAyD;CACpE,MAAM;CACN,qBACE;CACF,MAAM,SAAS,OAAY,SAAS;EAClC,MAAM,WAAW,OAAO,KAAK;EAC7B,MAAM,YAAY,KAAK,QAAQ,QAAQ,aAAa;EAGpD,IAAI,SAAS,SAAS,WACpB,OAAO,YAAY,MAAM,OAAO;EAIlC,IAAI,CAAC,QAAQ,KAAK,QAAQ,GACxB,OAAO,YAAY,MAAM,OAAO;EAIlC,IAAI,CAAC,QAAQ,KAAK,QAAQ,GACxB,OAAO,YAAY,MAAM,OAAO;EAIlC,IAAI,CAAC,QAAQ,KAAK,QAAQ,GACxB,OAAO,YAAY,MAAM,OAAO;EAIlC,IAAI,CAAC,sCAAsC,KAAK,QAAQ,GACtD,OAAO,YAAY,MAAM,OAAO;EAGlC,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"url.mjs","names":[],"sources":["../../../../../../../../seal/src/rules/string/url.ts"],"sourcesContent":["import { invalidRule, VALID_RULE } from \"../../helpers\";\
|
|
1
|
+
{"version":3,"file":"url.mjs","names":[],"sources":["../../../../../../../../seal/src/rules/string/url.ts"],"sourcesContent":["import { invalidRule, VALID_RULE } from \"../../helpers\";\nimport type { SchemaRule } from \"../../types\";\n\n/**\n * URL rule - validates URL format\n */\nexport const urlRule: SchemaRule = {\n name: \"url\",\n defaultErrorMessage: \"The :input must be a valid URL\",\n async validate(value: any, context) {\n try {\n new URL(value);\n return VALID_RULE;\n } catch {\n return invalidRule(this, context);\n }\n },\n};\n"],"mappings":";;;;;;;AAMA,MAAa,UAAsB;CACjC,MAAM;CACN,qBAAqB;CACrB,MAAM,SAAS,OAAY,SAAS;EAClC,IAAI;GACF,IAAI,IAAI,KAAK;GACb,OAAO;EACT,QAAQ;GACN,OAAO,YAAY,MAAM,OAAO;EAClC;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"without-whitespace.mjs","names":[],"sources":["../../../../../../../../seal/src/rules/string/without-whitespace.ts"],"sourcesContent":["import { invalidRule, VALID_RULE } from \"../../helpers\";\
|
|
1
|
+
{"version":3,"file":"without-whitespace.mjs","names":[],"sources":["../../../../../../../../seal/src/rules/string/without-whitespace.ts"],"sourcesContent":["import { invalidRule, VALID_RULE } from \"../../helpers\";\nimport type { SchemaRule } from \"../../types\";\n\n/**\n * Without whitespace rule - value must not contain whitespace\n */\nexport const withoutWhitespaceRule: SchemaRule = {\n name: \"withoutWhitespace\",\n defaultErrorMessage: \"The :input must not contain whitespace\",\n async validate(value: any, context) {\n if (!/\\s/.test(value)) {\n return VALID_RULE;\n }\n return invalidRule(this, context);\n },\n};\n"],"mappings":";;;;;;;AAMA,MAAa,wBAAoC;CAC/C,MAAM;CACN,qBAAqB;CACrB,MAAM,SAAS,OAAY,SAAS;EAClC,IAAI,CAAC,KAAK,KAAK,KAAK,GAClB,OAAO;EAET,OAAO,YAAY,MAAM,OAAO;CAClC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"date-types.mjs","names":[],"sources":["../../../../../../../seal/src/types/date-types.ts"],"sourcesContent":["/**\
|
|
1
|
+
{"version":3,"file":"date-types.mjs","names":[],"sources":["../../../../../../../seal/src/types/date-types.ts"],"sourcesContent":["/**\n * Week day names for validation\n */\nexport type WeekDay =\n | \"sunday\"\n | \"monday\"\n | \"tuesday\"\n | \"wednesday\"\n | \"thursday\"\n | \"friday\"\n | \"saturday\";\n\n/**\n * Week day numbers mapping\n */\nexport const WEEK_DAYS: Record<WeekDay, number> = {\n sunday: 0,\n monday: 1,\n tuesday: 2,\n wednesday: 3,\n thursday: 4,\n friday: 5,\n saturday: 6,\n};\n"],"mappings":";;;;AAeA,MAAa,YAAqC;CAChD,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;AACZ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"any-validator.mjs","names":[],"sources":["../../../../../../../seal/src/validators/any-validator.ts"],"sourcesContent":["import type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\
|
|
1
|
+
{"version":3,"file":"any-validator.mjs","names":[],"sources":["../../../../../../../seal/src/validators/any-validator.ts"],"sourcesContent":["import type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\nimport { applyNullable } from \"../standard-schema/json-schema\";\nimport { BaseValidator } from \"./base-validator\";\n\n/**\n * Any validator - accepts any value\n */\nexport class AnyValidator extends BaseValidator {\n /**\n * Any validator means any value, so we disable the default required requirement.\n */\n public override requiredRule = null;\n\n /**\n * Set is optional to be true\n */\n public override isOptional = true;\n\n /**\n * @inheritdoc\n *\n * Any validator accepts anything. In JSON Schema, an empty object `{}`\n * is the permissive schema that accepts any valid JSON value.\n *\n * @example\n * ```ts\n * v.any().toJsonSchema(\"draft-2020-12\")\n * // → {}\n * ```\n */\n public override toJsonSchema(target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n const schema: JsonSchemaResult = {};\n if (this.isNullable) applyNullable(schema, target);\n return schema;\n }\n}\n"],"mappings":";;;;;;;AAOA,IAAa,eAAb,cAAkC,cAAc;;;sBAIf;oBAKF;;;;;;;;;;;;;;CAc7B,AAAgB,aAAa,SAA2B,iBAAmC;EACzF,MAAM,SAA2B,CAAC;EAClC,IAAI,KAAK,YAAY,cAAc,QAAQ,MAAM;EACjD,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"array-validator.d.mts","names":[],"sources":["../../../../../../../seal/src/validators/array-validator.ts"],"mappings":";;;;;;;;;cAmBa,cAAA,SAAuB,aAAA;EAEzB,SAAA,EAAW,aAAA;cAAX,SAAA,EAAW,aAAA,EAClB,YAAA;;;;
|
|
1
|
+
{"version":3,"file":"array-validator.d.mts","names":[],"sources":["../../../../../../../seal/src/validators/array-validator.ts"],"mappings":";;;;;;;;;cAmBa,cAAA,SAAuB,aAAA;EAEzB,SAAA,EAAW,aAAA;cAAX,SAAA,EAAW,aAAA,EAClB,YAAA;;;;EAUK,WAAA,CAAY,KAAA;EA8GuB;;;EAvG1B,KAAA;EAoK0D;EA3JnE,IAAA;EA7BwC;EAkCxC,OAAA;EAlC2B;EAuC3B,UAAA;EArCa;EA0Cb,IAAA,CAAK,SAAA,mBAAmC,GAAA;EA1C3B;EA+Cb,GAAA,CAAI,GAAA,UAAa,YAAA;EA9CtB;EAmDK,SAAA,CAAU,MAAA,UAAgB,YAAA;EAzCd;EA8CZ,GAAA,CAAI,GAAA,UAAa,YAAA;EA9BjB;EAmCA,SAAA,CAAU,MAAA,UAAgB,YAAA;EAzB1B;EA8BA,MAAA,CAAO,MAAA,UAAgB,YAAA;EAzBlB;;;;;;;;;;;;;;EA2CL,OAAA,CAAQ,GAAA,UAAa,GAAA,UAAa,YAAA;EAlB3B;;;EA4BP,aAAA,CAAc,GAAA,UAAa,GAAA,UAAa,YAAA;EAVnB;EAerB,MAAA,CAAO,YAAA;EALP;EAUA,MAAA,CAAO,SAAA,mBAAmC,YAAA;EAVf;EAe3B,MAAA,CAAO,IAAA,OAAW,OAAA,EAAS,aAAA;EAV3B;;;;;;EAqBM,QAAA,CAAS,IAAA,OAAW,OAAA,EAAS,aAAA,GAAgB,OAAA,CAAQ,gBAAA;EAXhC;;;;;;;;;;;EAwElB,YAAA,CAAa,MAAA,GAAQ,gBAAA,GAAqC,gBAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"array-validator.mjs","names":[],"sources":["../../../../../../../seal/src/validators/array-validator.ts"],"sourcesContent":["import { setKeyPath } from \"../helpers\";\r\nimport { flipArrayMutator, sortArrayMutator, uniqueArrayMutator } from \"../mutators\";\r\nimport {\r\n arrayRule,\r\n betweenLengthRule,\r\n lengthRule,\r\n maxLengthRule,\r\n minLengthRule,\r\n sortedArrayRule,\r\n uniqueArrayRule,\r\n} from \"../rules\";\r\nimport type { SchemaContext, ValidationResult } from \"../types\";\r\nimport { BaseValidator } from \"./base-validator\";\r\nimport { applyNullable, getRuleOptions } from \"../standard-schema/json-schema\";\r\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\r\n\r\n/**\r\n * Array validator class\r\n */\r\nexport class ArrayValidator extends BaseValidator {\r\n public constructor(\r\n public validator: BaseValidator,\r\n errorMessage?: string,\r\n ) {\r\n super();\r\n this.addMutableRule(arrayRule, errorMessage);\r\n }\r\n\r\n /**\r\n * Check if value is an array type\r\n */\r\n public matchesType(value: any): boolean {\r\n return Array.isArray(value);\r\n }\r\n\r\n /**\r\n * Clone the validator\r\n */\r\n public override clone(): this {\r\n const cloned = super.clone();\r\n\r\n cloned.validator = this.validator.clone();\r\n\r\n return cloned;\r\n }\r\n\r\n /** Reverse array order */\r\n public flip() {\r\n return this.addMutator(flipArrayMutator);\r\n }\r\n\r\n /** Reverse array order (alias) */\r\n public reverse() {\r\n return this.addMutator(flipArrayMutator);\r\n }\r\n\r\n /** Make it has only unique values */\r\n public onlyUnique() {\r\n return this.addMutator(uniqueArrayMutator);\r\n }\r\n\r\n /** Sort array */\r\n public sort(direction: \"asc\" | \"desc\" = \"asc\", key?: string) {\r\n return this.addMutator(sortArrayMutator, { direction, key });\r\n }\r\n\r\n /** Array length must be greater than the given length */\n public min(min: number, errorMessage?: string) {\n return this.addRule(minLengthRule, errorMessage, { minLength: min });\n }\n\n /** @alias min */\n public minLength(length: number, errorMessage?: string) {\n return this.min(length, errorMessage);\n }\n\n /** Array length must be less than the given length */\n public max(max: number, errorMessage?: string) {\n return this.addRule(maxLengthRule, errorMessage, { maxLength: max });\n }\n\n /** @alias max */\n public maxLength(length: number, errorMessage?: string) {\n return this.max(length, errorMessage);\n }\n\r\n /** Array length must be of the given length */\r\n public length(length: number, errorMessage?: string) {\r\n return this.addRule(lengthRule, errorMessage, { length });\r\n }\r\n\r\n /**\r\n * Array length must be between min and max (inclusive)\r\n *\r\n * @param min - Minimum length (inclusive)\r\n * @param max - Maximum length (inclusive)\r\n *\r\n * @example\r\n * ```ts\r\n * v.array(v.string()).between(1, 10) // Array must have 1 to 10 items\r\n * v.array(v.number()).lengthBetween(5, 20) // Same using alias\r\n * ```\r\n *\r\n * @category Validation Rule\r\n */\r\n public between(min: number, max: number, errorMessage?: string) {\r\n return this.addRule(betweenLengthRule, errorMessage, {\r\n minLength: min,\r\n maxLength: max,\r\n });\r\n }\r\n\r\n /**\r\n * Alias for between() - array length between min and max\r\n */\r\n public lengthBetween(min: number, max: number, errorMessage?: string) {\r\n return this.between(min, max, errorMessage);\r\n }\r\n\r\n /** Array must have unique values */\r\n public unique(errorMessage?: string) {\r\n return this.addRule(uniqueArrayRule, errorMessage);\r\n }\r\n\r\n /** Array must be sorted */\r\n public sorted(direction: \"asc\" | \"desc\" = \"asc\", errorMessage?: string) {\r\n return this.addRule(sortedArrayRule, errorMessage, { direction });\r\n }\r\n\r\n /** Mutate the data */\r\n public mutate(data: any, context: SchemaContext) {\r\n if (!Array.isArray(data)) return data;\r\n return super.mutate([...data], context);\r\n }\r\n\r\n /** Validate array\r\n *\r\n * Absent input (and absent without `.default()`) propagates as `data: undefined`\r\n * so the parent ObjectValidator can omit the key. Without this, optional array\r\n * fields would silently materialise as `[]` in the validated output.\r\n */\r\n public async validate(data: any, context: SchemaContext): Promise<ValidationResult> {\r\n // Apply default when absent, then mutate. Mirrors BaseValidator's\r\n // `valueForRules = data ?? this.getDefaultValue()` so `.default([...])`\r\n // works on arrays too.\r\n const valueForRules = data ?? this.getDefaultValue();\r\n const mutatedData = await this.mutate(valueForRules, context);\r\n\r\n const result = await super.validate(data, context);\r\n\r\n if (result.isValid === false) return result;\r\n\r\n // Nothing to iterate for absent (no default) or null (nullable) inputs —\r\n // propagate so the parent ObjectValidator can omit the key.\r\n if (mutatedData === undefined || mutatedData === null) return result;\r\n\r\n // Defensive: type rule (arrayRule) should have failed for non-arrays.\r\n if (!Array.isArray(mutatedData)) return result;\r\n\r\n const errors: ValidationResult[\"errors\"] = [];\r\n\r\n // Validate all items in parallel (consistent with ObjectValidator)\r\n const validationPromises = mutatedData.map(async (value: any, index: number) => {\r\n const childContext: SchemaContext = {\r\n ...context,\r\n parent: mutatedData,\r\n value,\r\n key: index.toString(),\r\n path: setKeyPath(context.path, index.toString()),\r\n };\r\n\r\n const childResult = await this.validator.validate(value, childContext);\r\n\r\n // Update mutated data with validated result\r\n mutatedData[index] = childResult.data;\r\n\r\n // Collect errors from this element\r\n if (childResult.isValid === false) {\r\n errors.push(...childResult.errors);\r\n }\r\n });\r\n\r\n await Promise.all(validationPromises);\r\n\r\n return {\r\n isValid: errors.length === 0,\r\n errors,\r\n data: await this.startTransformationPipeline(mutatedData, context),\r\n };\r\n }\r\n\r\n /**\r\n * @inheritdoc\r\n *\r\n * Recursively generates JSON Schema for the array items.\r\n *\r\n * @example\r\n * ```ts\r\n * v.array(v.string().min(1)).minLength(1).toJsonSchema(\"draft-2020-12\")\r\n * // → { type: \"array\", items: { type: \"string\", minLength: 1 }, minItems: 1 }\r\n * ```\r\n */\r\n public override toJsonSchema(target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\r\n const schema: JsonSchemaResult = {\r\n type: \"array\",\r\n items: this.validator.toJsonSchema(target),\r\n };\r\n\r\n const minOpts = getRuleOptions(this.rules, \"minLength\");\r\n if (minOpts?.minLength !== undefined) schema.minItems = minOpts.minLength;\r\n\r\n const maxOpts = getRuleOptions(this.rules, \"maxLength\");\r\n if (maxOpts?.maxLength !== undefined) schema.maxItems = maxOpts.maxLength;\r\n\r\n const betweenOpts = getRuleOptions(this.rules, \"betweenLength\");\r\n if (betweenOpts) {\r\n if (betweenOpts.minLength !== undefined) schema.minItems = betweenOpts.minLength;\r\n if (betweenOpts.maxLength !== undefined) schema.maxItems = betweenOpts.maxLength;\r\n }\r\n\r\n const lengthOpts = getRuleOptions(this.rules, \"length\");\r\n if (lengthOpts?.length !== undefined) {\r\n schema.minItems = lengthOpts.length;\r\n schema.maxItems = lengthOpts.length;\r\n }\r\n\r\n if (this.isNullable) applyNullable(schema, target);\r\n\r\n return schema;\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;AAmBA,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K,UAAU,aAAa,MAAM;EAC3C;EAEA,MAAM,UAAU,eAAe,KAAK,OAAO,WAAW;EACtD,IAAI,SAAS,cAAc,QAAW,OAAO,WAAW,QAAQ;EAEhE,MAAM,UAAU,eAAe,KAAK,OAAO,WAAW;EACtD,IAAI,SAAS,cAAc,QAAW,OAAO,WAAW,QAAQ;EAEhE,MAAM,cAAc,eAAe,KAAK,OAAO,eAAe;EAC9D,IAAI,aAAa;GACf,IAAI,YAAY,cAAc,QAAW,OAAO,WAAW,YAAY;GACvE,IAAI,YAAY,cAAc,QAAW,OAAO,WAAW,YAAY;EACzE;EAEA,MAAM,aAAa,eAAe,KAAK,OAAO,QAAQ;EACtD,IAAI,YAAY,WAAW,QAAW;GACpC,OAAO,WAAW,WAAW;GAC7B,OAAO,WAAW,WAAW;EAC/B;EAEA,IAAI,KAAK,YAAY,cAAc,QAAQ,MAAM;EAEjD,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"array-validator.mjs","names":[],"sources":["../../../../../../../seal/src/validators/array-validator.ts"],"sourcesContent":["import { setKeyPath } from \"../helpers\";\nimport { flipArrayMutator, sortArrayMutator, uniqueArrayMutator } from \"../mutators\";\nimport {\n arrayRule,\n betweenLengthRule,\n lengthRule,\n maxLengthRule,\n minLengthRule,\n sortedArrayRule,\n uniqueArrayRule,\n} from \"../rules\";\nimport type { SchemaContext, ValidationResult } from \"../types\";\nimport { BaseValidator } from \"./base-validator\";\nimport { applyNullable, getRuleOptions } from \"../standard-schema/json-schema\";\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\n\n/**\n * Array validator class\n */\nexport class ArrayValidator extends BaseValidator {\n public constructor(\n public validator: BaseValidator,\n errorMessage?: string,\n ) {\n super();\n this.blankIsMissing = true;\n this.addMutableRule(arrayRule, errorMessage);\n }\n\n /**\n * Check if value is an array type\n */\n public matchesType(value: any): boolean {\n return Array.isArray(value);\n }\n\n /**\n * Clone the validator\n */\n public override clone(): this {\n const cloned = super.clone();\n\n cloned.validator = this.validator.clone();\n\n return cloned;\n }\n\n /** Reverse array order */\n public flip() {\n return this.addMutator(flipArrayMutator);\n }\n\n /** Reverse array order (alias) */\n public reverse() {\n return this.addMutator(flipArrayMutator);\n }\n\n /** Make it has only unique values */\n public onlyUnique() {\n return this.addMutator(uniqueArrayMutator);\n }\n\n /** Sort array */\n public sort(direction: \"asc\" | \"desc\" = \"asc\", key?: string) {\n return this.addMutator(sortArrayMutator, { direction, key });\n }\n\n /** Array length must be greater than the given length */\n public min(min: number, errorMessage?: string) {\n return this.addRule(minLengthRule, errorMessage, { minLength: min });\n }\n\n /** @alias min */\n public minLength(length: number, errorMessage?: string) {\n return this.min(length, errorMessage);\n }\n\n /** Array length must be less than the given length */\n public max(max: number, errorMessage?: string) {\n return this.addRule(maxLengthRule, errorMessage, { maxLength: max });\n }\n\n /** @alias max */\n public maxLength(length: number, errorMessage?: string) {\n return this.max(length, errorMessage);\n }\n\n /** Array length must be of the given length */\n public length(length: number, errorMessage?: string) {\n return this.addRule(lengthRule, errorMessage, { length });\n }\n\n /**\n * Array length must be between min and max (inclusive)\n *\n * @param min - Minimum length (inclusive)\n * @param max - Maximum length (inclusive)\n *\n * @example\n * ```ts\n * v.array(v.string()).between(1, 10) // Array must have 1 to 10 items\n * v.array(v.number()).lengthBetween(5, 20) // Same using alias\n * ```\n *\n * @category Validation Rule\n */\n public between(min: number, max: number, errorMessage?: string) {\n return this.addRule(betweenLengthRule, errorMessage, {\n minLength: min,\n maxLength: max,\n });\n }\n\n /**\n * Alias for between() - array length between min and max\n */\n public lengthBetween(min: number, max: number, errorMessage?: string) {\n return this.between(min, max, errorMessage);\n }\n\n /** Array must have unique values */\n public unique(errorMessage?: string) {\n return this.addRule(uniqueArrayRule, errorMessage);\n }\n\n /** Array must be sorted */\n public sorted(direction: \"asc\" | \"desc\" = \"asc\", errorMessage?: string) {\n return this.addRule(sortedArrayRule, errorMessage, { direction });\n }\n\n /** Mutate the data */\n public mutate(data: any, context: SchemaContext) {\n if (!Array.isArray(data)) return data;\n return super.mutate([...data], context);\n }\n\n /** Validate array\n *\n * Absent input (and absent without `.default()`) propagates as `data: undefined`\n * so the parent ObjectValidator can omit the key. Without this, optional array\n * fields would silently materialise as `[]` in the validated output.\n */\n public async validate(data: any, context: SchemaContext): Promise<ValidationResult> {\n // Apply default when absent, then mutate. Mirrors BaseValidator's\n // `valueForRules = data ?? this.getDefaultValue()` so `.default([...])`\n // works on arrays too.\n const valueForRules = data ?? this.getDefaultValue();\n const mutatedData = await this.mutate(valueForRules, context);\n\n const result = await super.validate(data, context);\n\n if (result.isValid === false) return result;\n\n // Nothing to iterate for absent (no default) or null (nullable) inputs —\n // propagate so the parent ObjectValidator can omit the key.\n if (mutatedData === undefined || mutatedData === null) return result;\n\n // Defensive: type rule (arrayRule) should have failed for non-arrays.\n if (!Array.isArray(mutatedData)) return result;\n\n const errors: ValidationResult[\"errors\"] = [];\n\n // Validate all items in parallel (consistent with ObjectValidator)\n const validationPromises = mutatedData.map(async (value: any, index: number) => {\n const childContext: SchemaContext = {\n ...context,\n parent: mutatedData,\n value,\n key: index.toString(),\n path: setKeyPath(context.path, index.toString()),\n };\n\n const childResult = await this.validator.validate(value, childContext);\n\n // Update mutated data with validated result\n mutatedData[index] = childResult.data;\n\n // Collect errors from this element\n if (childResult.isValid === false) {\n errors.push(...childResult.errors);\n }\n });\n\n await Promise.all(validationPromises);\n\n return {\n isValid: errors.length === 0,\n errors,\n data: await this.startTransformationPipeline(mutatedData, context),\n };\n }\n\n /**\n * @inheritdoc\n *\n * Recursively generates JSON Schema for the array items.\n *\n * @example\n * ```ts\n * v.array(v.string().min(1)).minLength(1).toJsonSchema(\"draft-2020-12\")\n * // → { type: \"array\", items: { type: \"string\", minLength: 1 }, minItems: 1 }\n * ```\n */\n public override toJsonSchema(target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n const schema: JsonSchemaResult = {\n type: \"array\",\n items: this.validator.toJsonSchema(target),\n };\n\n const minOpts = getRuleOptions(this.rules, \"minLength\");\n if (minOpts?.minLength !== undefined) schema.minItems = minOpts.minLength;\n\n const maxOpts = getRuleOptions(this.rules, \"maxLength\");\n if (maxOpts?.maxLength !== undefined) schema.maxItems = maxOpts.maxLength;\n\n const betweenOpts = getRuleOptions(this.rules, \"betweenLength\");\n if (betweenOpts) {\n if (betweenOpts.minLength !== undefined) schema.minItems = betweenOpts.minLength;\n if (betweenOpts.maxLength !== undefined) schema.maxItems = betweenOpts.maxLength;\n }\n\n const lengthOpts = getRuleOptions(this.rules, \"length\");\n if (lengthOpts?.length !== undefined) {\n schema.minItems = lengthOpts.length;\n schema.maxItems = lengthOpts.length;\n }\n\n if (this.isNullable) applyNullable(schema, target);\n\n return schema;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmBA,IAAa,iBAAb,cAAoC,cAAc;CAChD,AAAO,YACL,AAAO,WACP,cACA;EACA,MAAM;EAHC;EAIP,KAAK,iBAAiB;EACtB,KAAK,eAAe,WAAW,YAAY;CAC7C;;;;CAKA,AAAO,YAAY,OAAqB;EACtC,OAAO,MAAM,QAAQ,KAAK;CAC5B;;;;CAKA,AAAgB,QAAc;EAC5B,MAAM,SAAS,MAAM,MAAM;EAE3B,OAAO,YAAY,KAAK,UAAU,MAAM;EAExC,OAAO;CACT;;CAGA,AAAO,OAAO;EACZ,OAAO,KAAK,WAAW,gBAAgB;CACzC;;CAGA,AAAO,UAAU;EACf,OAAO,KAAK,WAAW,gBAAgB;CACzC;;CAGA,AAAO,aAAa;EAClB,OAAO,KAAK,WAAW,kBAAkB;CAC3C;;CAGA,AAAO,KAAK,YAA4B,OAAO,KAAc;EAC3D,OAAO,KAAK,WAAW,kBAAkB;GAAE;GAAW;EAAI,CAAC;CAC7D;;CAGA,AAAO,IAAI,KAAa,cAAuB;EAC7C,OAAO,KAAK,QAAQ,eAAe,cAAc,EAAE,WAAW,IAAI,CAAC;CACrE;;CAGA,AAAO,UAAU,QAAgB,cAAuB;EACt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ected isMutable: boolean;
|
|
20
|
+
/** Treat empty or whitespace-only form strings as an absent value. */
|
|
21
|
+
protected blankIsMissing: boolean;
|
|
20
22
|
/**
|
|
21
23
|
* Catch state — when `hasCatch` is true and validation fails, `catchValue`
|
|
22
24
|
* (or its callback result) substitutes for the failed value, and the public
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-validator.d.mts","names":[],"sources":["../../../../../../../seal/src/validators/base-validator.ts"],"mappings":";;;;;;;;;;;cAyBa,aAAA,6BAA0C,MAAA;EAC9C,KAAA,EAAO,oBAAA;EACP,QAAA,EAAU,qBAAA;EAAA,UACP,YAAA;EAAA,UACA,WAAA;EAAA,UACA,UAAA;EAAA,UACA,UAAA;EAAA,UACA,SAAA;EANI;;;;;;;EAAA,
|
|
1
|
+
{"version":3,"file":"base-validator.d.mts","names":[],"sources":["../../../../../../../seal/src/validators/base-validator.ts"],"mappings":";;;;;;;;;;;cAyBa,aAAA,6BAA0C,MAAA;EAC9C,KAAA,EAAO,oBAAA;EACP,QAAA,EAAU,qBAAA;EAAA,UACP,YAAA;EAAA,UACA,WAAA;EAAA,UACA,UAAA;EAAA,UACA,UAAA;EAAA,UACA,SAAA;EANI;EAAA,UAQJ,cAAA;EAUQ;;;;;;;EAAA,UADR,UAAA,UACA,MAAA,EAAQ,gBAAA,YAA4B,aAAA,gBAA6B,OAAA;EAAA,UACjE,QAAA;EA6MmD;;;;;;;EApMtD,UAAA;EAsXC;;;;;;;EA7WD,YAAA,EAAc,oBAAA;EAsZ+B;;;EAAA,UAjZ1C,gBAAA,EAAkB,yBAAA;EAqZJ;;;;;EAAA,UA9Yd,cAAA,EAAgB,wBAAA;EA4Zf;;;EAAA,UAvZD,oBAAA,EAAsB,MAAA;EAsca;;;EAAA,IAjclC,OAAA;EA+cE;;;EAAA,IAvcF,SAAA;EA0hBS;;;;;EAAA,cAhhBN,QAAA;EAojB4C;;;;EA5iBnD,eAAA;EAkuBsB;;;;;;EAxtBtB,QAAA;IA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,GAAoB,iBAAA,EACjD,IAAA,EAAM,UAAA,CAAW,CAAA,GACjB,YAAA,WACA,OAAA,GAAS,CAAA,GACR,oBAAA,CAAqB,CAAA;;;;;;;;;;;;;;;;;;;;;;;EA8CjB,OAAA,WAAkB,iBAAA,GAAoB,iBAAA,EAC3C,IAAA,EAAM,UAAA,CAAW,CAAA,GACjB,OAAA,GAAU,CAAA;IAAM,YAAA;EAAA;;;;EASX,MAAA,CACL,QAAA,GACE,KAAA,OACA,OAAA,EAAS,aAAA,KACN,OAAA;;;;EAkBA,UAAA,CAAW,OAAA,EAAS,OAAA,EAAS,OAAA;;;;EAS7B,iBAAA,CAAkB,OAAA,EAAS,OAAA,EAAS,OAAA;;;;;;;;EAiBpC,OAAA,CAAQ,KAAA;IAAsB,UAAA;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoC9B,KAAA,CACL,QAAA,UACU,MAAA,EAAQ,gBAAA,YAA4B,aAAA,gBAA6B,OAAA;IACjE,QAAA;EAAA;;;;EAYC,MAAA,CAAO,IAAA,OAAW,OAAA,EAAS,aAAA,GAAa,OAAA;;;;EAc9C,KAAA,CAAM,KAAA;;;;EASA,QAAA,CAAS,IAAA,OAAW,OAAA,EAAS,aAAA,GAAgB,OAAA,CAAQ,gBAAA;;;;YAyFxD,qBAAA,CAAsB,IAAA,EAAM,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBAoDjB,oBAAA,CAAqB,KAAA,CAAM,MAAA,EAAQ,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;EAyCjD,YAAA,CAAa,OAAA,GAAS,gBAAA,GAAqC,gBAAA;AAAA"}
|
|
@@ -16,6 +16,7 @@ var BaseValidator = class {
|
|
|
16
16
|
this.shouldOmit = false;
|
|
17
17
|
this.isNullable = false;
|
|
18
18
|
this.isMutable = false;
|
|
19
|
+
this.blankIsMissing = false;
|
|
19
20
|
this.hasCatch = false;
|
|
20
21
|
this.isOptional = false;
|
|
21
22
|
this.requiredRule = this.createRule(requiredRule);
|
|
@@ -276,8 +277,10 @@ var BaseValidator = class {
|
|
|
276
277
|
cloned.shouldOmit = this.shouldOmit;
|
|
277
278
|
cloned.description = this.description;
|
|
278
279
|
cloned.attributesText = { ...this.attributesText };
|
|
280
|
+
cloned.translatedAttributes = { ...this.translatedAttributes };
|
|
279
281
|
cloned.isNullable = this.isNullable;
|
|
280
282
|
cloned.isOptional = this.isOptional;
|
|
283
|
+
cloned.blankIsMissing = this.blankIsMissing;
|
|
281
284
|
cloned.requiredRule = this.requiredRule;
|
|
282
285
|
cloned.catchValue = this.catchValue;
|
|
283
286
|
cloned.hasCatch = this.hasCatch;
|
|
@@ -523,7 +526,13 @@ var BaseValidator = class {
|
|
|
523
526
|
errors: [],
|
|
524
527
|
data: null
|
|
525
528
|
};
|
|
526
|
-
const
|
|
529
|
+
const isBlank = this.blankIsMissing && typeof data === "string" && data.trim() === "";
|
|
530
|
+
if (isBlank && this.isNullable) return {
|
|
531
|
+
isValid: true,
|
|
532
|
+
errors: [],
|
|
533
|
+
data: null
|
|
534
|
+
};
|
|
535
|
+
const valueForRules = (isBlank ? void 0 : data) ?? this.getDefaultValue();
|
|
527
536
|
const mutatedData = this.isOptional && valueForRules === void 0 ? void 0 : await this.mutate(valueForRules, context);
|
|
528
537
|
const errors = [];
|
|
529
538
|
let isValid = true;
|
|
@@ -562,6 +571,7 @@ var BaseValidator = class {
|
|
|
562
571
|
*/
|
|
563
572
|
setRuleAttributesList(rule) {
|
|
564
573
|
rule.context.attributesList = typeof this.attributesText[rule.name] === "object" ? this.attributesText[rule.name] : this.attributesText;
|
|
574
|
+
rule.context.translatedAttributes = this.translatedAttributes;
|
|
565
575
|
}
|
|
566
576
|
/**
|
|
567
577
|
* Standard Schema V1 compliance.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-validator.mjs","names":["defaultRequiredRule"],"sources":["../../../../../../../seal/src/validators/base-validator.ts"],"sourcesContent":["import { clone } from \"@mongez/reinforcements\";\nimport { validate } from \"../factory/validate\";\nimport { VALID_RULE, invalidRule } from \"../helpers/validation-helpers\";\nimport { isEmptyValue } from \"../helpers/is-empty-value\";\nimport { requiredRule as defaultRequiredRule } from \"../rules/core/required\";\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\nimport { mapToStandardResult } from \"../standard-schema/map-result\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"../standard-schema/types\";\nimport type {\n ContextualSchemaRule,\n ContextualizedMutator,\n ContextualizedTransformer,\n Mutator,\n SchemaContext,\n SchemaRule,\n SchemaRuleOptions,\n SimpleTransformerCallback,\n TransformerCallback,\n ValidationAttributesList,\n ValidationResult,\n} from \"../types\";\n\n/**\n * Base validator class - foundation for all validators\n */\nexport class BaseValidator<TInput = unknown, TOutput = TInput> {\n public rules: ContextualSchemaRule[] = [];\n public mutators: ContextualizedMutator[] = [];\n protected defaultValue: any | (() => any);\n protected description?: string;\n protected shouldOmit = false;\n protected isNullable = false;\n protected isMutable = false;\n\n /**\n * Catch state — when `hasCatch` is true and validation fails, `catchValue`\n * (or its callback result) substitutes for the failed value, and the public\n * result reports `isValid: true` with no errors.\n *\n * See `.catch()` for semantics and the v1 scope (leaf-only).\n */\n protected catchValue:\n any | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>);\n protected hasCatch = false;\n\n /**\n * Whether the field is optional.\n * - false (default): field is required unless a requiredRule governs the condition.\n * - true: field can be absent or empty — set by calling .optional().\n *\n * Also used as a TypeScript literal brand via the optional() return type.\n */\n public isOptional = false;\n\n /**\n * The single required-condition rule for this field.\n * - null: field uses strict default (always required when not optional).\n * - set: the rule governs when the field is required (e.g., requiredIf).\n *\n * Stored separately from rules[] and prepended at validate() time.\n */\n public requiredRule: ContextualSchemaRule | null = this.createRule(defaultRequiredRule);\n\n /**\n * Pipeline to transform the mutated/original data before returning it\n */\n protected dataTransformers: ContextualizedTransformer[] = [];\n\n /**\n * Attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n */\n protected attributesText: ValidationAttributesList = {};\n\n /**\n * Attributed that will be always using the attribute translator\n */\n protected translatedAttributes: Record<string, string> = {};\n\n /**\n * Mark the validator as mutable\n */\n public get mutable() {\n this.isMutable = true;\n return this;\n }\n\n /**\n * Mark the validator as immutable\n */\n public get immutable() {\n this.isMutable = false;\n return this;\n }\n\n /**\n * Get the instance to apply changes to.\n * By default (immutable), returns a clone so the original is unchanged.\n * When `.mutable` is set, returns `this` to mutate in place.\n */\n protected get instance(): this {\n return this.isMutable ? this : this.clone();\n }\n\n /**\n * Get the default value\n * Supports lazy evaluation via callbacks\n */\n public getDefaultValue(): any {\n return typeof this.defaultValue === \"function\" ? this.defaultValue() : this.defaultValue;\n }\n\n /**\n * Allow null as a valid value.\n *\n * Brands the return type with `{ isNullable: true }` so `Infer<>` widens\n * the inferred output to include `| null`.\n */\n public nullable(): this & { isNullable: true } {\n const instance = this.instance;\n instance.isNullable = true;\n return instance as this & { isNullable: true };\n }\n\n /**\n * Explicitly disallow null values after calling nullable.\n *\n * Brands the return type with `{ isNullable: false }` to cancel any prior\n * `.nullable()` at the type level.\n */\n public notNullable(): this & { isNullable: false } {\n const instance = this.instance;\n instance.isNullable = false;\n return instance as this & { isNullable: false };\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addTransformer(transform: TransformerCallback, options: any = {}) {\n const instance = this.instance;\n instance.addMutableTransformer(transform, options);\n\n return instance;\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addMutableTransformer(transform: TransformerCallback, options: any = {}) {\n this.dataTransformers.push({\n transform,\n options,\n });\n }\n\n /**\n * Transform the output value - simple one-time transformation\n *\n * @param callback - Simple callback receiving data and context\n *\n * @example\n * ```ts\n * // Simple transformation\n * v.string().outputAs(data => data.toUpperCase())\n *\n * // With context\n * v.string().outputAs((data, context) => {\n * console.log(`Transforming ${context.path}`);\n * return data.toLowerCase();\n * })\n * ```\n */\n public outputAs(callback: SimpleTransformerCallback) {\n return this.addTransformer((data, { context }) => callback(data, context));\n }\n\n /**\n * Transform output to JSON string\n *\n * Works with any validator type (string, number, date, object, array, etc.)\n *\n * @param indent - Optional indentation for pretty printing (default: 0 for compact)\n *\n * @example\n * ```ts\n * // Compact JSON\n * v.object({ name: v.string() }).toJSON()\n * // Output: '{\"name\":\"John\"}'\n *\n * // Pretty-printed JSON\n * v.array(v.object({...})).toJSON(2)\n * // Output:\n * // [\n * // {\n * // \"name\": \"John\"\n * // }\n * // ]\n *\n * // Works with any type\n * v.string().toJSON() // '\"hello\"'\n * v.number().toJSON() // '42'\n * v.date().toJSON() // '\"2024-10-26T00:00:00.000Z\"'\n * ```\n *\n * @category Transformer\n */\n public toJSON(indent?: number) {\n return this.addTransformer((data, { options }) => JSON.stringify(data, null, options.indent), {\n indent: indent ?? 0,\n });\n }\n\n /**\n * Start data transformation pipeline\n * Context is passed at runtime, not stored\n */\n public async startTransformationPipeline(data: any, context: SchemaContext) {\n for (const transformer of this.dataTransformers) {\n data = await transformer.transform(data, {\n options: transformer.options,\n context,\n });\n }\n\n return data;\n }\n\n /**\n * Set attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n *\n * @example\n * v.string().attributes({\n * name: \"Name\",\n * email: \"Email\",\n * });\n * // Example 2: Add custom attributes for matches\n * v.string().matches(\"confirmPassword\").attributes({\n * matches: {\n * confirmPassword: \"Confirm Password\",\n * },\n * });\n */\n public attributes(attributes: Record<string, string | Record<string, string>>) {\n const instance = this.instance;\n for (const [key, value] of Object.entries(attributes)) {\n instance.attributesText[key] = value;\n }\n\n return instance;\n }\n\n /**\n * Define a lazy getter property for each attribute in the given object and use the config attribute translator\n */\n public transAttributes(attributes: Record<string, string>) {\n const instance = this.instance;\n for (const [key, value] of Object.entries(attributes)) {\n instance.translatedAttributes[key] = value;\n }\n\n return instance;\n }\n\n /**\n * Add description to the validator\n */\n public describe(description: string) {\n const instance = this.instance;\n instance.description = description;\n return instance;\n }\n\n /**\n * Check if this validator can handle the given value's type\n * Override this in specific validators to enable type-based routing in union validators\n *\n * Default: returns true (validator will attempt to validate any type)\n *\n * @param value - The value to check\n * @returns True if this validator can handle this type\n *\n * @example\n * ```ts\n * // StringValidator\n * public matchesType(value: any): boolean {\n * return typeof value === 'string';\n * }\n *\n * // Custom FileValidator\n * public matchesType(value: any): boolean {\n * return value instanceof UploadedFile;\n * }\n * ```\n */\n public matchesType(_value: any): boolean {\n return true; // Default: permissive, attempt to validate any type\n }\n\n /**\n * Create a copy of this validator with the same configuration\n * Copies all rules, mutators, transformers, default values, and settings\n *\n * @returns A new validator instance with copied configuration\n *\n * @example\n * ```ts\n * // Create reusable validator templates\n * const baseString = v.string().required().trim().min(3);\n * const emailField = baseString.clone().email();\n * const usernameField = baseString.clone().alphanumeric().max(20);\n *\n * // Works with all validators\n * const positiveInt = v.int().positive().required();\n * const ageField = positiveInt.clone().min(18).max(120);\n * ```\n */\n public clone(): this {\n // Create a new instance using Object.create to preserve the prototype chain\n const Constructor = this.constructor as new (...args: any[]) => this;\n const cloned = Object.create(Constructor.prototype);\n\n // Copy all BaseValidator properties\n cloned.rules = [...this.rules];\n cloned.mutators = [...this.mutators];\n cloned.dataTransformers = [...this.dataTransformers];\n cloned.defaultValue = this.defaultValue;\n cloned.shouldOmit = this.shouldOmit;\n cloned.description = this.description;\n cloned.attributesText = { ...this.attributesText };\n cloned.isNullable = this.isNullable;\n cloned.isOptional = this.isOptional;\n cloned.requiredRule = this.requiredRule; // same reference is fine — rule is treated as immutable\n cloned.catchValue = this.catchValue;\n cloned.hasCatch = this.hasCatch;\n\n return cloned;\n }\n\n /**\n * @deprecated This method is no longer needed and does nothing.\n * Empty values are now automatically skipped for validation rules by default.\n * Only presence validators (required, present, etc.) will check empty values.\n * You can safely remove this call from your code.\n */\n public ignoreEmptyValue(_ignoreEmptyValue = true) {\n // No-op for backward compatibility\n return this;\n }\n\n /**\n * Omit this field from the validated data output\n *\n * Field will still be validated but not included in the final result.\n * Useful for confirmation fields, captcha, terms acceptance, etc.\n *\n * @example\n * ```ts\n * v.object({\n * password: v.string().required(),\n * confirmPassword: v.string().required().sameAs(\"password\").omit(),\n * acceptTerms: v.boolean().required().omit(),\n * });\n * // Output: { password: \"...\" }\n * // confirmPassword and acceptTerms validated but omitted\n * ```\n */\n public omit() {\n const instance = this.instance;\n instance.shouldOmit = true;\n return instance;\n }\n\n /**\n * @alias omit\n */\n public exclude() {\n return this.omit();\n }\n\n /**\n * Check if this field should be omitted from the output\n */\n public isOmitted(): boolean {\n return this.shouldOmit;\n }\n\n /**\n * Add rule to the validator\n */\n public addRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.addMutableRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Set the required-condition rule for this field.\n *\n * Unlike addRule(), this does NOT push to rules[]. The rule is stored in the\n * dedicated `requiredRule` slot and is prepended to the validation pipeline\n * at runtime. Only one required rule can be active per field — this replaces\n * any previously set required rule.\n *\n * Also marks the field as not optional (isOptional = false).\n *\n * @example\n * ```ts\n * // Used internally by required(), requiredIf(), requiredWith(), etc.\n * BaseValidator.prototype.required = function(msg) {\n * return this.setRequiredRule(requiredRule, msg);\n * };\n * ```\n */\n public setRequiredRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.isOptional = false;\n instance.requiredRule = instance.createRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Add mutable rule\n */\n public addMutableRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = this.createRule(rule, errorMessage, options);\n\n this.rules.push(newRule);\n\n return newRule;\n }\n\n /**\n * Create new rule\n */\n protected createRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = {\n ...(clone(rule) as ContextualSchemaRule<T>),\n context: {\n errorMessage,\n options,\n attributesList: this.attributesText,\n translatedAttributes: this.translatedAttributes,\n translationParams: {},\n translatableParams: {},\n },\n };\n\n if (errorMessage) {\n newRule.errorMessage = errorMessage;\n }\n\n if (rule.sortOrder === undefined) {\n newRule.sortOrder = this.rules.length + 1;\n }\n\n return newRule;\n }\n\n /**\n * Use a custom or pre-built validation rule\n *\n * @param rule - The validation rule to apply\n * @param options - Rule options including errorMessage and any rule-specific options\n *\n * @example\n * ```ts\n * import { hexColorRule } from \"@warlock.js/seal\";\n *\n * v.string().useRule(hexColorRule, { errorMessage: \"Invalid color\" });\n * ```\n *\n * @example\n * ```ts\n * // With rule options\n * v.string().useRule(myCustomRule, {\n * customOption: true,\n * errorMessage: \"Custom validation failed\"\n * });\n * ```\n */\n public useRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n options?: T & { errorMessage?: string },\n ) {\n const { errorMessage, ...ruleOptions } = options || ({} as any);\n return this.addRule(rule, errorMessage, ruleOptions);\n }\n\n /**\n * Define custom rule\n */\n public refine(\n callback: (\n value: any,\n context: SchemaContext,\n ) => Promise<string | undefined> | string | undefined,\n ) {\n return this.addRule({\n name: \"custom\",\n async validate(value, context) {\n const result = await callback(value, context);\n if (result) {\n this.context.errorMessage = result;\n return invalidRule(this, context);\n }\n return VALID_RULE;\n },\n });\n }\n\n /**\n * Add mutator to the validator\n */\n public addMutator(mutator: Mutator, options: any = {}) {\n const instance = this.instance;\n instance.addMutableMutator(mutator, options);\n return instance;\n }\n\n /**\n * Add mutable mutator\n */\n public addMutableMutator(mutator: Mutator, options: any = {}) {\n this.mutators.push({\n mutate: mutator,\n context: {\n options,\n ctx: {} as any,\n },\n });\n }\n\n /**\n * Set default value for the field. The default is used when the input is\n * absent (`undefined`); it then flows through the rule pipeline.\n *\n * Brands the return type with `{ hasDefault: true }` so `Infer<>` treats\n * the field as guaranteed-present even when chained with `.optional()`.\n */\n public default(value: any): this & { hasDefault: true } {\n const instance = this.instance;\n instance.defaultValue = value;\n return instance as this & { hasDefault: true };\n }\n\n /**\n * Fallback to a value when validation fails.\n *\n * Complementary to `.default()`: `.default(x)` fires when input is **absent**,\n * `.catch(y)` fires when input is **present but invalid**. Combine them when\n * you want both behaviours: `.optional().default(x).catch(y)`.\n *\n * The fallback can be a value or a callback `(errors, originalInput) => fallback`.\n * The callback variant is the only side-channel for the swallowed errors —\n * use it to log/alert before the fallback substitutes.\n *\n * Brands the return type with `{ hasCatch: true }` so `Infer<>` treats the\n * field as guaranteed-present (the catch ensures a value will always exist).\n *\n * **Scope (v1).** Catch is honoured for **leaf validators** (string, number,\n * boolean, date, …) and for fields inside containers. It is a **no-op on\n * container validators themselves** (`v.object`, `v.array`, `v.record`,\n * `v.tuple`, `v.discriminatedUnion`) — those use their own iteration logic\n * that bypasses the catch hook in `BaseValidator.validate()`.\n *\n * @example\n * ```ts\n * v.int().min(0).catch(3) // bad number → 3\n * v.string().in([\"us\", \"eu\"]).catch(\"us\") // unknown enum → \"us\"\n * v.string().catch((errors, input) => {\n * console.warn(`bad user value: ${JSON.stringify(input)}`, errors);\n * return \"anonymous\";\n * })\n * ```\n */\n public catch(\n fallback:\n any | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>),\n ): this & { hasCatch: true } {\n const instance = this.instance;\n\n instance.catchValue = fallback;\n instance.hasCatch = true;\n\n return instance as this & { hasCatch: true };\n }\n\n /**\n * Mutate the data\n */\n public async mutate(data: any, context: SchemaContext) {\n let mutatedData = data;\n\n for (const mutator of this.mutators) {\n mutator.context.ctx = context;\n mutatedData = await mutator.mutate(mutatedData, mutator.context);\n }\n\n return mutatedData;\n }\n\n /**\n * Set the label for the validator that will be matching the :input attribute\n */\n public label(label: string) {\n const instance = this.instance;\n instance.attributesText.input = label;\n return instance;\n }\n\n /**\n * Validate the data\n */\n public async validate(data: any, context: SchemaContext): Promise<ValidationResult> {\n if (data === null && this.isNullable) {\n return { isValid: true, errors: [], data: null };\n }\n\n const valueForRules = data ?? this.getDefaultValue();\n // Optional fields with no resolved value are absent, not values to\n // transform. Skipping here protects every mutator while still allowing\n // defaults and present values through the normal mutation pipeline.\n const mutatedData =\n this.isOptional && valueForRules === undefined\n ? undefined\n : await this.mutate(valueForRules, context);\n\n const errors: ValidationResult[\"errors\"] = [];\n let isValid = true;\n const isFirstErrorOnly = context.configurations?.firstErrorOnly ?? true;\n\n const isEmpty = isEmptyValue(valueForRules);\n\n // D8 fix (design/core-defects-found.md): for an optional field, only a\n // truly ABSENT value (`valueForRules === undefined` — the key was\n // missing, or was `null`/`undefined` and got coalesced above) may skip\n // the value rules. A PRESENT-but-empty value (e.g. `\"\"` from `?page=`)\n // must still run them, so `v.int().optional()` given `\"\"` fails instead\n // of silently handing back a string that `Infer.Output`'s\n // `number | undefined` forbids. Non-optional fields are unaffected —\n // their `requiredRule` (not nulled out by `.optional()`) already rejects\n // `\"\"` before these rules matter.\n const skipEmptyRules = this.isOptional ? valueForRules === undefined : isEmpty;\n\n // Prepend the required-condition rule if set, so it always runs first.\n // requiredRule has requiresValue = false so it runs even on empty values.\n const rulesToRun = this.requiredRule ? [this.requiredRule, ...this.rules] : this.rules;\n\n for (const rule of rulesToRun) {\n if ((rule.requiresValue ?? true) && skipEmptyRules) continue;\n\n this.setRuleAttributesList(rule);\n\n const result = await rule.validate(mutatedData, context);\n\n if (result.isValid === false) {\n isValid = false;\n errors.push({\n type: rule.name,\n error: result.error,\n input: result.path ?? context.path,\n });\n\n if (isFirstErrorOnly) {\n break;\n }\n }\n }\n\n const result: ValidationResult = {\n isValid,\n errors,\n data:\n mutatedData !== undefined\n ? await this.startTransformationPipeline(mutatedData, context)\n : undefined,\n };\n\n // Catch fallback — only on the leaf path. Container validators override\n // validate() and don't run this hook on their own outcome, so catching\n // a whole object/array/record is a no-op in v1.\n if (result.isValid === false && this.hasCatch) {\n const fallback =\n typeof this.catchValue === \"function\"\n ? await this.catchValue(result.errors, data)\n : this.catchValue;\n\n return { isValid: true, errors: [], data: fallback };\n }\n\n return result;\n }\n\n /**\n * Set rule attributes list\n */\n protected setRuleAttributesList(rule: ContextualSchemaRule) {\n rule.context.attributesList =\n typeof this.attributesText[rule.name] === \"object\"\n ? (this.attributesText[rule.name] as ValidationAttributesList)\n : this.attributesText;\n }\n\n /**\n * Standard Schema V1 compliance.\n *\n * Allows this validator to be used with any Standard Schema-aware library\n * (OpenAI structured outputs, LangGraph, TanStack Form, Conform, Valibot adapters, etc.)\n * without extra adapters.\n *\n * Delegates to the `validate()` factory so all `configureSeal()` options\n * (translations, firstErrorOnly) are picked up automatically at call time.\n *\n * Includes Standard JSON Schema support via `jsonSchema.input()` / `jsonSchema.output()`.\n *\n * ## How Standard Schema libraries consume this\n *\n * You pass the **schema object itself** to the library — they internally read\n * `schema[\"~standard\"]`. Do NOT pass `schema[\"~standard\"]` directly.\n *\n * @example\n * ```ts\n * const schema = v.object({ name: v.string().required() });\n *\n * // TanStack Form — pass schema, library reads [\"~standard\"] internally\n * const form = useForm({ validators: { onChange: schema } });\n *\n * // Conform (Remix) — same pattern\n * const [form] = useForm({ onValidate({ formData }) {\n * return parseWithStandardSchema(formData, { schema });\n * }});\n *\n * // Direct validation (lower level — most apps don't need this)\n * const result = await schema[\"~standard\"].validate({ name: \"Hasan\" });\n * // → { value: { name: \"Hasan\" } } on success\n * // → { issues: [{ message: \"...\", path: [{ key: \"name\" }] }] } on failure\n *\n * // JSON Schema for OpenAI / LangChain tool calling\n * const parameters = schema[\"~standard\"].jsonSchema.input({ target: \"openai-strict\" });\n * // → { type: \"object\", properties: {...}, required: [...], additionalProperties: false }\n * ```\n *\n * @note Cross-field rules (sameAs, requiredIf, requiredWith) rely on sibling values\n * available in the full validation context. When called on a standalone scalar validator,\n * sibling data is absent and those rules will not evaluate correctly.\n * Always call on the parent ObjectValidator for full-payload validation.\n */\n get [\"~standard\"](): StandardJSONSchemaV1.Props<TInput, TOutput> {\n return {\n version: 1,\n vendor: \"seal\",\n types: undefined as unknown as StandardSchemaV1.Types<TInput, TOutput>,\n validate: async (value: unknown) => {\n const result = await validate(this, value);\n return mapToStandardResult(result) as StandardSchemaV1.Result<TOutput>;\n },\n jsonSchema: {\n input: (options) => this.toJsonSchema(options.target),\n output: (options) => this.toJsonSchema(options.target),\n },\n };\n }\n\n /**\n * Generate a JSON Schema representation of this validator.\n *\n * Supports targets: `\"draft-2020-12\"` (default), `\"draft-07\"`, `\"openapi-3.0\"`.\n *\n * Subclasses override this to describe their specific constraints.\n * The base implementation returns `{}` (permissive — accepts anything),\n * which is correct for validators with no representable JSON Schema constraints.\n *\n * @note Rules that cannot be expressed in JSON Schema are silently omitted:\n * - Cross-field rules: sameAs, requiredIf, requiredWith, requiredWithout\n * - Custom callbacks: refine()\n * - Framework-specific runtime rules (core/cascade plugins)\n * These rules still run normally at validation time — only absent from JSON Schema.\n *\n * @example\n * ```ts\n * v.string().min(3).max(50).toJsonSchema(\"draft-2020-12\")\n * // → { type: \"string\", minLength: 3, maxLength: 50 }\n *\n * v.object({ name: v.string().required(), age: v.int().optional() })\n * .toJsonSchema(\"draft-07\")\n * // → { type: \"object\", properties: { name: { type: \"string\" }, age: { type: \"integer\" } }, required: [\"name\"] }\n * ```\n */\n public toJsonSchema(_target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;AAyBA,IAAa,gBAAb,MAA+D;;eACtB,CAAC;kBACG,CAAC;oBAGrB;oBACA;mBACD;kBAWD;oBASD;sBAS+B,KAAK,WAAWA,YAAmB;0BAK5B,CAAC;wBAON,CAAC;8BAKG,CAAC;;;;;CAK1D,IAAW,UAAU;EACnB,KAAK,YAAY;EACjB,OAAO;CACT;;;;CAKA,IAAW,YAAY;EACrB,KAAK,YAAY;EACjB,OAAO;CACT;;;;;;CAOA,IAAc,WAAiB;EAC7B,OAAO,KAAK,YAAY,OAAO,KAAK,MAAM;CAC5C;;;;;CAMA,AAAO,kBAAuB;EAC5B,OAAO,OAAO,KAAK,iBAAiB,aAAa,KAAK,aAAa,IAAI,KAAK;CAC9E;;;;;;;CAQA,AAAO,WAAwC;EAC7C,MAAM,WAAW,KAAK;EACtB,SAAS,aAAa;EACtB,OAAO;CACT;;;;;;;CAQA,AAAO,cAA4C;EACjD,MAAM,WAAW,KAAK;EACtB,SAAS,aAAa;EACtB,OAAO;CACT;;;;;;;;;;;;;;;;;;;CAoBA,AAAO,eAAe,WAAgC,UAAe,CAAC,GAAG;EACvE,MAAM,WAAW,KAAK;EACtB,SAAS,sBAAsB,WAAW,OAAO;EAEjD,OAAO;CACT;;;;;;;;;;;;;;;;;;;CAoBA,AAAO,sBAAsB,WAAgC,UAAe,CAAC,GAAG;EAC9E,KAAK,iBAAiB,KAAK;GACzB;GACA;EACF,CAAC;CACH;;;;;;;;;;;;;;;;;;CAmBA,AAAO,SAAS,UAAqC;EACnD,OAAO,KAAK,gBAAgB,MAAM,EAAE,cAAc,SAAS,MAAM,OAAO,CAAC;CAC3E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCA,AA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Y;IACV,QAAQ,YAAY,KAAK,aAAa,QAAQ,MAAM;IACpD,SAAS,YAAY,KAAK,aAAa,QAAQ,MAAM;GACvD;EACF;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,AAAO,aAAa,UAA4B,iBAAmC;EACjF,OAAO,CAAC;CACV;AACF"}
|
|
1
|
+
{"version":3,"file":"base-validator.mjs","names":["defaultRequiredRule"],"sources":["../../../../../../../seal/src/validators/base-validator.ts"],"sourcesContent":["import { clone } from \"@mongez/reinforcements\";\nimport { validate } from \"../factory/validate\";\nimport { VALID_RULE, invalidRule } from \"../helpers/validation-helpers\";\nimport { isEmptyValue } from \"../helpers/is-empty-value\";\nimport { requiredRule as defaultRequiredRule } from \"../rules/core/required\";\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\nimport { mapToStandardResult } from \"../standard-schema/map-result\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"../standard-schema/types\";\nimport type {\n ContextualSchemaRule,\n ContextualizedMutator,\n ContextualizedTransformer,\n Mutator,\n SchemaContext,\n SchemaRule,\n SchemaRuleOptions,\n SimpleTransformerCallback,\n TransformerCallback,\n ValidationAttributesList,\n ValidationResult,\n} from \"../types\";\n\n/**\n * Base validator class - foundation for all validators\n */\nexport class BaseValidator<TInput = unknown, TOutput = TInput> {\n public rules: ContextualSchemaRule[] = [];\n public mutators: ContextualizedMutator[] = [];\n protected defaultValue: any | (() => any);\n protected description?: string;\n protected shouldOmit = false;\n protected isNullable = false;\n protected isMutable = false;\n /** Treat empty or whitespace-only form strings as an absent value. */\n protected blankIsMissing = false;\n\n /**\n * Catch state — when `hasCatch` is true and validation fails, `catchValue`\n * (or its callback result) substitutes for the failed value, and the public\n * result reports `isValid: true` with no errors.\n *\n * See `.catch()` for semantics and the v1 scope (leaf-only).\n */\n protected catchValue:\n any | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>);\n protected hasCatch = false;\n\n /**\n * Whether the field is optional.\n * - false (default): field is required unless a requiredRule governs the condition.\n * - true: field can be absent or empty — set by calling .optional().\n *\n * Also used as a TypeScript literal brand via the optional() return type.\n */\n public isOptional = false;\n\n /**\n * The single required-condition rule for this field.\n * - null: field uses strict default (always required when not optional).\n * - set: the rule governs when the field is required (e.g., requiredIf).\n *\n * Stored separately from rules[] and prepended at validate() time.\n */\n public requiredRule: ContextualSchemaRule | null = this.createRule(defaultRequiredRule);\n\n /**\n * Pipeline to transform the mutated/original data before returning it\n */\n protected dataTransformers: ContextualizedTransformer[] = [];\n\n /**\n * Attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n */\n protected attributesText: ValidationAttributesList = {};\n\n /**\n * Attributed that will be always using the attribute translator\n */\n protected translatedAttributes: Record<string, string> = {};\n\n /**\n * Mark the validator as mutable\n */\n public get mutable() {\n this.isMutable = true;\n return this;\n }\n\n /**\n * Mark the validator as immutable\n */\n public get immutable() {\n this.isMutable = false;\n return this;\n }\n\n /**\n * Get the instance to apply changes to.\n * By default (immutable), returns a clone so the original is unchanged.\n * When `.mutable` is set, returns `this` to mutate in place.\n */\n protected get instance(): this {\n return this.isMutable ? this : this.clone();\n }\n\n /**\n * Get the default value\n * Supports lazy evaluation via callbacks\n */\n public getDefaultValue(): any {\n return typeof this.defaultValue === \"function\" ? this.defaultValue() : this.defaultValue;\n }\n\n /**\n * Allow null as a valid value.\n *\n * Brands the return type with `{ isNullable: true }` so `Infer<>` widens\n * the inferred output to include `| null`.\n */\n public nullable(): this & { isNullable: true } {\n const instance = this.instance;\n instance.isNullable = true;\n return instance as this & { isNullable: true };\n }\n\n /**\n * Explicitly disallow null values after calling nullable.\n *\n * Brands the return type with `{ isNullable: false }` to cancel any prior\n * `.nullable()` at the type level.\n */\n public notNullable(): this & { isNullable: false } {\n const instance = this.instance;\n instance.isNullable = false;\n return instance as this & { isNullable: false };\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addTransformer(transform: TransformerCallback, options: any = {}) {\n const instance = this.instance;\n instance.addMutableTransformer(transform, options);\n\n return instance;\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addMutableTransformer(transform: TransformerCallback, options: any = {}) {\n this.dataTransformers.push({\n transform,\n options,\n });\n }\n\n /**\n * Transform the output value - simple one-time transformation\n *\n * @param callback - Simple callback receiving data and context\n *\n * @example\n * ```ts\n * // Simple transformation\n * v.string().outputAs(data => data.toUpperCase())\n *\n * // With context\n * v.string().outputAs((data, context) => {\n * console.log(`Transforming ${context.path}`);\n * return data.toLowerCase();\n * })\n * ```\n */\n public outputAs(callback: SimpleTransformerCallback) {\n return this.addTransformer((data, { context }) => callback(data, context));\n }\n\n /**\n * Transform output to JSON string\n *\n * Works with any validator type (string, number, date, object, array, etc.)\n *\n * @param indent - Optional indentation for pretty printing (default: 0 for compact)\n *\n * @example\n * ```ts\n * // Compact JSON\n * v.object({ name: v.string() }).toJSON()\n * // Output: '{\"name\":\"John\"}'\n *\n * // Pretty-printed JSON\n * v.array(v.object({...})).toJSON(2)\n * // Output:\n * // [\n * // {\n * // \"name\": \"John\"\n * // }\n * // ]\n *\n * // Works with any type\n * v.string().toJSON() // '\"hello\"'\n * v.number().toJSON() // '42'\n * v.date().toJSON() // '\"2024-10-26T00:00:00.000Z\"'\n * ```\n *\n * @category Transformer\n */\n public toJSON(indent?: number) {\n return this.addTransformer((data, { options }) => JSON.stringify(data, null, options.indent), {\n indent: indent ?? 0,\n });\n }\n\n /**\n * Start data transformation pipeline\n * Context is passed at runtime, not stored\n */\n public async startTransformationPipeline(data: any, context: SchemaContext) {\n for (const transformer of this.dataTransformers) {\n data = await transformer.transform(data, {\n options: transformer.options,\n context,\n });\n }\n\n return data;\n }\n\n /**\n * Set attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n *\n * @example\n * v.string().attributes({\n * name: \"Name\",\n * email: \"Email\",\n * });\n * // Example 2: Add custom attributes for matches\n * v.string().matches(\"confirmPassword\").attributes({\n * matches: {\n * confirmPassword: \"Confirm Password\",\n * },\n * });\n */\n public attributes(attributes: Record<string, string | Record<string, string>>) {\n const instance = this.instance;\n for (const [key, value] of Object.entries(attributes)) {\n instance.attributesText[key] = value;\n }\n\n return instance;\n }\n\n /**\n * Define a lazy getter property for each attribute in the given object and use the config attribute translator\n */\n public transAttributes(attributes: Record<string, string>) {\n const instance = this.instance;\n for (const [key, value] of Object.entries(attributes)) {\n instance.translatedAttributes[key] = value;\n }\n\n return instance;\n }\n\n /**\n * Add description to the validator\n */\n public describe(description: string) {\n const instance = this.instance;\n instance.description = description;\n return instance;\n }\n\n /**\n * Check if this validator can handle the given value's type\n * Override this in specific validators to enable type-based routing in union validators\n *\n * Default: returns true (validator will attempt to validate any type)\n *\n * @param value - The value to check\n * @returns True if this validator can handle this type\n *\n * @example\n * ```ts\n * // StringValidator\n * public matchesType(value: any): boolean {\n * return typeof value === 'string';\n * }\n *\n * // Custom FileValidator\n * public matchesType(value: any): boolean {\n * return value instanceof UploadedFile;\n * }\n * ```\n */\n public matchesType(_value: any): boolean {\n return true; // Default: permissive, attempt to validate any type\n }\n\n /**\n * Create a copy of this validator with the same configuration\n * Copies all rules, mutators, transformers, default values, and settings\n *\n * @returns A new validator instance with copied configuration\n *\n * @example\n * ```ts\n * // Create reusable validator templates\n * const baseString = v.string().required().trim().min(3);\n * const emailField = baseString.clone().email();\n * const usernameField = baseString.clone().alphanumeric().max(20);\n *\n * // Works with all validators\n * const positiveInt = v.int().positive().required();\n * const ageField = positiveInt.clone().min(18).max(120);\n * ```\n */\n public clone(): this {\n // Create a new instance using Object.create to preserve the prototype chain\n const Constructor = this.constructor as new (...args: any[]) => this;\n const cloned = Object.create(Constructor.prototype);\n\n // Copy all BaseValidator properties\n cloned.rules = [...this.rules];\n cloned.mutators = [...this.mutators];\n cloned.dataTransformers = [...this.dataTransformers];\n cloned.defaultValue = this.defaultValue;\n cloned.shouldOmit = this.shouldOmit;\n cloned.description = this.description;\n cloned.attributesText = { ...this.attributesText };\n cloned.translatedAttributes = { ...this.translatedAttributes };\n cloned.isNullable = this.isNullable;\n cloned.isOptional = this.isOptional;\n cloned.blankIsMissing = this.blankIsMissing;\n cloned.requiredRule = this.requiredRule; // same reference is fine — rule is treated as immutable\n cloned.catchValue = this.catchValue;\n cloned.hasCatch = this.hasCatch;\n\n return cloned;\n }\n\n /**\n * @deprecated This method is no longer needed and does nothing.\n * Empty values are now automatically skipped for validation rules by default.\n * Only presence validators (required, present, etc.) will check empty values.\n * You can safely remove this call from your code.\n */\n public ignoreEmptyValue(_ignoreEmptyValue = true) {\n // No-op for backward compatibility\n return this;\n }\n\n /**\n * Omit this field from the validated data output\n *\n * Field will still be validated but not included in the final result.\n * Useful for confirmation fields, captcha, terms acceptance, etc.\n *\n * @example\n * ```ts\n * v.object({\n * password: v.string().required(),\n * confirmPassword: v.string().required().sameAs(\"password\").omit(),\n * acceptTerms: v.boolean().required().omit(),\n * });\n * // Output: { password: \"...\" }\n * // confirmPassword and acceptTerms validated but omitted\n * ```\n */\n public omit() {\n const instance = this.instance;\n instance.shouldOmit = true;\n return instance;\n }\n\n /**\n * @alias omit\n */\n public exclude() {\n return this.omit();\n }\n\n /**\n * Check if this field should be omitted from the output\n */\n public isOmitted(): boolean {\n return this.shouldOmit;\n }\n\n /**\n * Add rule to the validator\n */\n public addRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.addMutableRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Set the required-condition rule for this field.\n *\n * Unlike addRule(), this does NOT push to rules[]. The rule is stored in the\n * dedicated `requiredRule` slot and is prepended to the validation pipeline\n * at runtime. Only one required rule can be active per field — this replaces\n * any previously set required rule.\n *\n * Also marks the field as not optional (isOptional = false).\n *\n * @example\n * ```ts\n * // Used internally by required(), requiredIf(), requiredWith(), etc.\n * BaseValidator.prototype.required = function(msg) {\n * return this.setRequiredRule(requiredRule, msg);\n * };\n * ```\n */\n public setRequiredRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.isOptional = false;\n instance.requiredRule = instance.createRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Add mutable rule\n */\n public addMutableRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = this.createRule(rule, errorMessage, options);\n\n this.rules.push(newRule);\n\n return newRule;\n }\n\n /**\n * Create new rule\n */\n protected createRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = {\n ...(clone(rule) as ContextualSchemaRule<T>),\n context: {\n errorMessage,\n options,\n attributesList: this.attributesText,\n translatedAttributes: this.translatedAttributes,\n translationParams: {},\n translatableParams: {},\n },\n };\n\n if (errorMessage) {\n newRule.errorMessage = errorMessage;\n }\n\n if (rule.sortOrder === undefined) {\n newRule.sortOrder = this.rules.length + 1;\n }\n\n return newRule;\n }\n\n /**\n * Use a custom or pre-built validation rule\n *\n * @param rule - The validation rule to apply\n * @param options - Rule options including errorMessage and any rule-specific options\n *\n * @example\n * ```ts\n * import { hexColorRule } from \"@warlock.js/seal\";\n *\n * v.string().useRule(hexColorRule, { errorMessage: \"Invalid color\" });\n * ```\n *\n * @example\n * ```ts\n * // With rule options\n * v.string().useRule(myCustomRule, {\n * customOption: true,\n * errorMessage: \"Custom validation failed\"\n * });\n * ```\n */\n public useRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n options?: T & { errorMessage?: string },\n ) {\n const { errorMessage, ...ruleOptions } = options || ({} as any);\n return this.addRule(rule, errorMessage, ruleOptions);\n }\n\n /**\n * Define custom rule\n */\n public refine(\n callback: (\n value: any,\n context: SchemaContext,\n ) => Promise<string | undefined> | string | undefined,\n ) {\n return this.addRule({\n name: \"custom\",\n async validate(value, context) {\n const result = await callback(value, context);\n if (result) {\n this.context.errorMessage = result;\n return invalidRule(this, context);\n }\n return VALID_RULE;\n },\n });\n }\n\n /**\n * Add mutator to the validator\n */\n public addMutator(mutator: Mutator, options: any = {}) {\n const instance = this.instance;\n instance.addMutableMutator(mutator, options);\n return instance;\n }\n\n /**\n * Add mutable mutator\n */\n public addMutableMutator(mutator: Mutator, options: any = {}) {\n this.mutators.push({\n mutate: mutator,\n context: {\n options,\n ctx: {} as any,\n },\n });\n }\n\n /**\n * Set default value for the field. The default is used when the input is\n * absent (`undefined`); it then flows through the rule pipeline.\n *\n * Brands the return type with `{ hasDefault: true }` so `Infer<>` treats\n * the field as guaranteed-present even when chained with `.optional()`.\n */\n public default(value: any): this & { hasDefault: true } {\n const instance = this.instance;\n instance.defaultValue = value;\n return instance as this & { hasDefault: true };\n }\n\n /**\n * Fallback to a value when validation fails.\n *\n * Complementary to `.default()`: `.default(x)` fires when input is **absent**,\n * `.catch(y)` fires when input is **present but invalid**. Combine them when\n * you want both behaviours: `.optional().default(x).catch(y)`.\n *\n * The fallback can be a value or a callback `(errors, originalInput) => fallback`.\n * The callback variant is the only side-channel for the swallowed errors —\n * use it to log/alert before the fallback substitutes.\n *\n * Brands the return type with `{ hasCatch: true }` so `Infer<>` treats the\n * field as guaranteed-present (the catch ensures a value will always exist).\n *\n * **Scope (v1).** Catch is honoured for **leaf validators** (string, number,\n * boolean, date, …) and for fields inside containers. It is a **no-op on\n * container validators themselves** (`v.object`, `v.array`, `v.record`,\n * `v.tuple`, `v.discriminatedUnion`) — those use their own iteration logic\n * that bypasses the catch hook in `BaseValidator.validate()`.\n *\n * @example\n * ```ts\n * v.int().min(0).catch(3) // bad number → 3\n * v.string().in([\"us\", \"eu\"]).catch(\"us\") // unknown enum → \"us\"\n * v.string().catch((errors, input) => {\n * console.warn(`bad user value: ${JSON.stringify(input)}`, errors);\n * return \"anonymous\";\n * })\n * ```\n */\n public catch(\n fallback:\n any | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>),\n ): this & { hasCatch: true } {\n const instance = this.instance;\n\n instance.catchValue = fallback;\n instance.hasCatch = true;\n\n return instance as this & { hasCatch: true };\n }\n\n /**\n * Mutate the data\n */\n public async mutate(data: any, context: SchemaContext) {\n let mutatedData = data;\n\n for (const mutator of this.mutators) {\n mutator.context.ctx = context;\n mutatedData = await mutator.mutate(mutatedData, mutator.context);\n }\n\n return mutatedData;\n }\n\n /**\n * Set the label for the validator that will be matching the :input attribute\n */\n public label(label: string) {\n const instance = this.instance;\n instance.attributesText.input = label;\n return instance;\n }\n\n /**\n * Validate the data\n */\n public async validate(data: any, context: SchemaContext): Promise<ValidationResult> {\n if (data === null && this.isNullable) {\n return { isValid: true, errors: [], data: null };\n }\n\n const isBlank = this.blankIsMissing && typeof data === \"string\" && data.trim() === \"\";\n\n if (isBlank && this.isNullable) {\n return { isValid: true, errors: [], data: null };\n }\n\n const valueForRules = (isBlank ? undefined : data) ?? this.getDefaultValue();\n // Optional fields with no resolved value are absent, not values to\n // transform. Skipping here protects every mutator while still allowing\n // defaults and present values through the normal mutation pipeline.\n const mutatedData =\n this.isOptional && valueForRules === undefined\n ? undefined\n : await this.mutate(valueForRules, context);\n\n const errors: ValidationResult[\"errors\"] = [];\n let isValid = true;\n const isFirstErrorOnly = context.configurations?.firstErrorOnly ?? true;\n\n const isEmpty = isEmptyValue(valueForRules);\n\n // D8 fix (design/core-defects-found.md): for an optional field, only a\n // truly ABSENT value (`valueForRules === undefined` — the key was\n // missing, or was `null`/`undefined` and got coalesced above) may skip\n // the value rules. A PRESENT-but-empty value (e.g. `\"\"` from `?page=`)\n // must still run them, so `v.int().optional()` given `\"\"` fails instead\n // of silently handing back a string that `Infer.Output`'s\n // `number | undefined` forbids. Non-optional fields are unaffected —\n // their `requiredRule` (not nulled out by `.optional()`) already rejects\n // `\"\"` before these rules matter.\n const skipEmptyRules = this.isOptional ? valueForRules === undefined : isEmpty;\n\n // Prepend the required-condition rule if set, so it always runs first.\n // requiredRule has requiresValue = false so it runs even on empty values.\n const rulesToRun = this.requiredRule ? [this.requiredRule, ...this.rules] : this.rules;\n\n for (const rule of rulesToRun) {\n if ((rule.requiresValue ?? true) && skipEmptyRules) continue;\n\n this.setRuleAttributesList(rule);\n\n const result = await rule.validate(mutatedData, context);\n\n if (result.isValid === false) {\n isValid = false;\n errors.push({\n type: rule.name,\n error: result.error,\n input: result.path ?? context.path,\n });\n\n if (isFirstErrorOnly) {\n break;\n }\n }\n }\n\n const result: ValidationResult = {\n isValid,\n errors,\n data:\n mutatedData !== undefined\n ? await this.startTransformationPipeline(mutatedData, context)\n : undefined,\n };\n\n // Catch fallback — only on the leaf path. Container validators override\n // validate() and don't run this hook on their own outcome, so catching\n // a whole object/array/record is a no-op in v1.\n if (result.isValid === false && this.hasCatch) {\n const fallback =\n typeof this.catchValue === \"function\"\n ? await this.catchValue(result.errors, data)\n : this.catchValue;\n\n return { isValid: true, errors: [], data: fallback };\n }\n\n return result;\n }\n\n /**\n * Set rule attributes list\n */\n protected setRuleAttributesList(rule: ContextualSchemaRule) {\n rule.context.attributesList =\n typeof this.attributesText[rule.name] === \"object\"\n ? (this.attributesText[rule.name] as ValidationAttributesList)\n : this.attributesText;\n rule.context.translatedAttributes = this.translatedAttributes;\n }\n\n /**\n * Standard Schema V1 compliance.\n *\n * Allows this validator to be used with any Standard Schema-aware library\n * (OpenAI structured outputs, LangGraph, TanStack Form, Conform, Valibot adapters, etc.)\n * without extra adapters.\n *\n * Delegates to the `validate()` factory so all `configureSeal()` options\n * (translations, firstErrorOnly) are picked up automatically at call time.\n *\n * Includes Standard JSON Schema support via `jsonSchema.input()` / `jsonSchema.output()`.\n *\n * ## How Standard Schema libraries consume this\n *\n * You pass the **schema object itself** to the library — they internally read\n * `schema[\"~standard\"]`. Do NOT pass `schema[\"~standard\"]` directly.\n *\n * @example\n * ```ts\n * const schema = v.object({ name: v.string().required() });\n *\n * // TanStack Form — pass schema, library reads [\"~standard\"] internally\n * const form = useForm({ validators: { onChange: schema } });\n *\n * // Conform (Remix) — same pattern\n * const [form] = useForm({ onValidate({ formData }) {\n * return parseWithStandardSchema(formData, { schema });\n * }});\n *\n * // Direct validation (lower level — most apps don't need this)\n * const result = await schema[\"~standard\"].validate({ name: \"Hasan\" });\n * // → { value: { name: \"Hasan\" } } on success\n * // → { issues: [{ message: \"...\", path: [{ key: \"name\" }] }] } on failure\n *\n * // JSON Schema for OpenAI / LangChain tool calling\n * const parameters = schema[\"~standard\"].jsonSchema.input({ target: \"openai-strict\" });\n * // → { type: \"object\", properties: {...}, required: [...], additionalProperties: false }\n * ```\n *\n * @note Cross-field rules (sameAs, requiredIf, requiredWith) rely on sibling values\n * available in the full validation context. When called on a standalone scalar validator,\n * sibling data is absent and those rules will not evaluate correctly.\n * Always call on the parent ObjectValidator for full-payload validation.\n */\n get [\"~standard\"](): StandardJSONSchemaV1.Props<TInput, TOutput> {\n return {\n version: 1,\n vendor: \"seal\",\n types: undefined as unknown as StandardSchemaV1.Types<TInput, TOutput>,\n validate: async (value: unknown) => {\n const result = await validate(this, value);\n return mapToStandardResult(result) as StandardSchemaV1.Result<TOutput>;\n },\n jsonSchema: {\n input: (options) => this.toJsonSchema(options.target),\n output: (options) => this.toJsonSchema(options.target),\n },\n };\n }\n\n /**\n * Generate a JSON Schema representation of this validator.\n *\n * Supports targets: `\"draft-2020-12\"` (default), `\"draft-07\"`, `\"openapi-3.0\"`.\n *\n * Subclasses override this to describe their specific constraints.\n * The base implementation returns `{}` (permissive — accepts anything),\n * which is correct for validators with no representable JSON Schema constraints.\n *\n * @note Rules that cannot be expressed in JSON Schema are silently omitted:\n * - Cross-field rules: sameAs, requiredIf, requiredWith, requiredWithout\n * - Custom callbacks: refine()\n * - Framework-specific runtime rules (core/cascade plugins)\n * These rules still run normally at validation time — only absent from JSON Schema.\n *\n * @example\n * ```ts\n * v.string().min(3).max(50).toJsonSchema(\"draft-2020-12\")\n * // → { type: \"string\", minLength: 3, maxLength: 50 }\n *\n * v.object({ name: v.string().required(), age: v.int().optional() })\n * .toJsonSchema(\"draft-07\")\n * // → { type: \"object\", properties: { name: { type: \"string\" }, age: { type: \"integer\" } }, required: [\"name\"] }\n * ```\n */\n public toJsonSchema(_target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;AAyBA,IAAa,gBAAb,MAA+D;;eACtB,CAAC;kBACG,CAAC;oBAGrB;oBACA;mBACD;wBAEK;kBAWN;oBASD;sBAS+B,KAAK,WAAWA,YAAmB;0BAK5B,CAAC;wBAON,CAAC;8BAKG,CAAC;;;;;CAK1D,IAAW,UAAU;EACnB,KAAK,YAAY;EACjB,OAAO;CACT;;;;CAKA,IAAW,YAAY;EACrB,KAAK,YAAY;EACjB,OAAO;CACT;;;;;;CAOA,IAAc,WAAiB;EAC7B,OAAO,KAAK,YAAY,OAAO,KAAK,MAAM;CAC5C;;;;;CAMA,AAAO,kBAAuB;EAC5B,OAAO,OAAO,KAAK,iBAAiB,aAAa,KAAK,aAAa,IAAI,KAAK;CAC9E;;;;;;;CAQA,AAAO,WAAwC;EAC7C,MAAM,WAAW,KAAK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;GAEvD,IAAI,OAAO,YAAY,OAAO;IAC5B,UAAU;IACV,OAAO,KAAK;KACV,MAAM,KAAK;KACX,OAAO,OAAO;KACd,OAAO,OAAO,QAAQ,QAAQ;IAChC,CAAC;IAED,IAAI,kBACF;GAEJ;EACF;EAEA,MAAM,SAA2B;GAC/B;GACA;GACA,MACE,gBAAgB,SACZ,MAAM,KAAK,4BAA4B,aAAa,OAAO,IAC3D;EACR;EAKA,IAAI,OAAO,YAAY,SAAS,KAAK,UAMnC,OAAO;GAAE,SAAS;GAAM,QAAQ,CAAC;GAAG,MAJlC,OAAO,KAAK,eAAe,aACvB,MAAM,KAAK,WAAW,OAAO,QAAQ,IAAI,IACzC,KAAK;EAEwC;EAGrD,OAAO;CACT;;;;CAKA,AAAU,sBAAsB,MAA4B;EAC1D,KAAK,QAAQ,iBACX,OAAO,KAAK,eAAe,KAAK,UAAU,WACrC,KAAK,eAAe,KAAK,QAC1B,KAAK;EACX,KAAK,QAAQ,uBAAuB,KAAK;CAC3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CA,KAAK,eAA4D;EAC/D,OAAO;GACL,SAAS;GACT,QAAQ;GACR,OAAO;GACP,UAAU,OAAO,UAAmB;IAElC,OAAO,oBAAoB,MADN,SAAS,MAAM,KAAK,CACR;GACnC;GACA,YAAY;IACV,QAAQ,YAAY,KAAK,aAAa,QAAQ,MAAM;IACpD,SAAS,YAAY,KAAK,aAAa,QAAQ,MAAM;GACvD;EACF;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,AAAO,aAAa,UAA4B,iBAAmC;EACjF,OAAO,CAAC;CACV;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boolean-validator.d.mts","names":[],"sources":["../../../../../../../seal/src/validators/boolean-validator.ts"],"mappings":";;;;;;AA4BA;;;;;cAAa,gBAAA,SAAyB,kBAAA;cACjB,YAAA;EADmC;;;
|
|
1
|
+
{"version":3,"file":"boolean-validator.d.mts","names":[],"sources":["../../../../../../../seal/src/validators/boolean-validator.ts"],"mappings":";;;;;;AA4BA;;;;;cAAa,gBAAA,SAAyB,kBAAA;cACjB,YAAA;EADmC;;;EAU/C,WAAA,CAAY,KAAA;EAAZ;;;;;;;;;;;;;;;;;;EAAA,QAsBC,kBAAA;EA4CD;EAzBA,QAAA,CAAS,YAAA;EAyBsB;EApB/B,UAAA,CAAW,KAAA,UAAe,KAAA,OAAY,YAAA;EA2B7B;EAtBT,cAAA,CAAe,KAAA,UAAe,KAAA,OAAY,YAAA;EA2B/B;EAtBX,kBAAA,CAAmB,KAAA,UAAe,YAAA;EAsBI;EAjBtC,iBAAA,CAAkB,KAAA,UAAe,YAAA;EAsBlB;EAjBf,eAAA,CAAgB,KAAA,UAAe,YAAA;EAiBW;EAV1C,QAAA,CAAS,YAAA;EAeU;EAVnB,UAAA,CAAW,KAAA,UAAe,KAAA,OAAY,YAAA;EAetC;EAVA,cAAA,CAAe,KAAA,UAAe,KAAA,OAAY,YAAA;EAUT;EALjC,kBAAA,CAAmB,KAAA,UAAe,YAAA;EAUlB;EALhB,iBAAA,CAAkB,KAAA,UAAe,YAAA;EA+BjC;EA1BA,eAAA,CAAgB,KAAA,UAAe,YAAA;EAoC/B;;;;;;;;;AA2BmF;;;;;;;;;;;EArCnF,MAAA;IACoD,SAAA;EAAA;;;;;EASpD,UAAA,CAAW,YAAA;;;;;EAQX,WAAA,CAAY,YAAA;;;;;;;;;;;;;;;;EAmBH,YAAA,CAAa,MAAA,GAAQ,gBAAA,GAAqC,gBAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boolean-validator.mjs","names":[],"sources":["../../../../../../../seal/src/validators/boolean-validator.ts"],"sourcesContent":["import { booleanCoerceMutator, formBooleanMutator } from \"../mutators/boolean-mutators\";\nimport {\n acceptedIfPresentRule,\n acceptedIfRequiredRule,\n acceptedIfRule,\n acceptedRule,\n acceptedUnlessRule,\n acceptedWithoutRule,\n declinedIfPresentRule,\n declinedIfRequiredRule,\n declinedIfRule,\n declinedRule,\n declinedUnlessRule,\n declinedWithoutRule,\n} from \"../rules/scalar\";\nimport { booleanRule } from \"../rules\";\nimport { PrimitiveValidator } from \"./primitive-validator\";\nimport { applyNullable } from \"../standard-schema/json-schema\";\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\nimport type { SchemaRule, SchemaRuleOptions } from \"../types\";\n\n/**\n * Boolean validator class\n *\n * Extends PrimitiveValidator — inherits enum/in/oneOf/allowsOnly/forbids/notIn.\n * Defines accepted/declined directly as real methods (not ScalarValidator field copies)\n * so they survive cloning correctly.\n */\nexport class BooleanValidator extends PrimitiveValidator {\n public constructor(errorMessage?: string) {\n super();\n this.addMutableRule(booleanRule, errorMessage);\n }\n\n /**\n * Check if value is a boolean type\n */\n public matchesType(value: any): boolean {\n return typeof value === \"boolean\";\n }\n\n /**\n * Add a rule from the accepted/declined family, opting the validator into\n * form-boolean parsing.\n *\n * Calling ANY `accepted*`/`declined*` method on `v.boolean()` adds (once,\n * idempotently — checked by mutator identity so chaining several of these\n * methods never stacks duplicates) `formBooleanMutator`, which runs before\n * the type rule and converts the accepted set (`1`, `\"1\"`, `true`,\n * `\"true\"`, `\"yes\"`, `\"y\"`, `\"on\"`, `\"Yes\"`, `\"Y\"`, `\"On\"`) to `true` and\n * the declined set (`0`, `\"0\"`, `false`, `\"false\"`, `\"no\"`, `\"n\"`, `\"off\"`,\n * `\"No\"`, `\"N\"`, `\"Off\"`) to `false`; any other value passes through\n * unchanged and is rejected by the strict type rule as before.\n *\n * The mutator and the rule are added to the SAME resolved instance in one\n * pass — resolving `this.instance` twice (once per `addRule`/`addMutator`\n * call) would clone twice on an immutable validator and silently drop one\n * of the two additions.\n */\n private addFormBooleanRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n\n if (!instance.mutators.some((mutator) => mutator.mutate === formBooleanMutator)) {\n instance.addMutableMutator(formBooleanMutator);\n }\n\n instance.addMutableRule(rule, errorMessage, options);\n\n return instance;\n }\n\n // ==================== Accepted ====================\n\n /** Value must be accepted (true, \"yes\", 1, \"on\", etc. — form strings are parsed into a real boolean first) */\n public accepted(errorMessage?: string) {\n return this.addFormBooleanRule(acceptedRule, errorMessage);\n }\n\n /** Value must be accepted if another field equals a value */\n public acceptedIf(field: string, value: any, errorMessage?: string) {\n return this.addFormBooleanRule(acceptedIfRule, errorMessage, { field, value });\n }\n\n /** Value must be accepted unless another field equals a value */\n public acceptedUnless(field: string, value: any, errorMessage?: string) {\n return this.addFormBooleanRule(acceptedUnlessRule, errorMessage, { field, value });\n }\n\n /** Value must be accepted if another field is required */\n public acceptedIfRequired(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(acceptedIfRequiredRule, errorMessage, { field });\n }\n\n /** Value must be accepted if another field is present */\n public acceptedIfPresent(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(acceptedIfPresentRule, errorMessage, { field });\n }\n\n /** Value must be accepted if another field is missing */\n public acceptedWithout(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(acceptedWithoutRule, errorMessage, { field });\n }\n\n // ==================== Declined ====================\n\n /** Value must be declined (false, \"no\", 0, \"off\", etc. — form strings are parsed into a real boolean first) */\n public declined(errorMessage?: string) {\n return this.addFormBooleanRule(declinedRule, errorMessage);\n }\n\n /** Value must be declined if another field equals a value */\n public declinedIf(field: string, value: any, errorMessage?: string) {\n return this.addFormBooleanRule(declinedIfRule, errorMessage, { field, value });\n }\n\n /** Value must be declined unless another field equals a value */\n public declinedUnless(field: string, value: any, errorMessage?: string) {\n return this.addFormBooleanRule(declinedUnlessRule, errorMessage, { field, value });\n }\n\n /** Value must be declined if another field is required */\n public declinedIfRequired(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(declinedIfRequiredRule, errorMessage, { field });\n }\n\n /** Value must be declined if another field is present */\n public declinedIfPresent(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(declinedIfPresentRule, errorMessage, { field });\n }\n\n /** Value must be declined if another field is missing */\n public declinedWithout(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(declinedWithoutRule, errorMessage, { field });\n }\n\n // ==================== Coercion ====================\n\n /**\n * Opt in to coercion: an exact query-string-shaped boolean is converted to a\n * real boolean **before** the type rules run; any other value passes through\n * unchanged so bad input still fails the type rule.\n *\n * Converts exactly `\"true\"` / `\"1\"` / `1` → `true` and `\"false\"` / `\"0\"` / `0`\n * → `false`. Case-sensitive, no trimming — `\"TRUE\"`, `\"yes\"`, `\"on\"`, `\"\"`, and\n * `2` all pass through unchanged and fail the type rule. `v.boolean()` does\n * **not** coerce by default; this only takes effect when explicitly chained.\n * For form-style truthy strings like `\"yes\"` / `\"on\"`, use `.accepted()` /\n * `.declined()` instead — those methods opt into their own form-boolean\n * parsing (a wider value set, case-insensitive on a few forms) and then\n * apply the accepted/declined pass-fail rule on top of the parsed boolean.\n *\n * The output type is unchanged (`Infer<>` keys off the validator class), so\n * `v.boolean().coerce()` still infers `boolean`.\n *\n * @example\n * v.boolean().coerce() // \"true\" → true; \"1\" → true; \"0\" → false; \"yes\" → invalid\n */\n public coerce() {\n return this.addMutator(booleanCoerceMutator) as this & { isCoerced: true };\n }\n\n // ==================== Strict boolean checks ====================\n\n /**\n * Value must be strictly true (not \"yes\", \"on\", 1, etc.)\n * @alias accepted - strict version\n */\n public mustBeTrue(errorMessage?: string) {\n return this.equal(true, errorMessage);\n }\n\n /**\n * Value must be strictly false (not \"no\", \"off\", 0, etc.)\n * @alias declined - strict version\n */\n public mustBeFalse(errorMessage?: string) {\n return this.equal(false, errorMessage);\n }\n\n /**\n * @inheritdoc\n *\n * @note accepted/declined rules and all cross-field boolean rules\n * are not representable in JSON Schema and are silently omitted.\n *\n * @example\n * ```ts\n * v.boolean().toJsonSchema(\"draft-2020-12\")\n * // → { type: \"boolean\" }\n *\n * v.boolean().nullable().toJsonSchema(\"openapi-3.0\")\n * // → { type: \"boolean\", nullable: true }\n * ```\n */\n public override toJsonSchema(target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n const schema: JsonSchemaResult = { type: \"boolean\" };\n if (this.isNullable) applyNullable(schema, target);\n return schema;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,IAAa,mBAAb,cAAsC,mBAAmB;CACvD,AAAO,YAAY,cAAuB;EACxC,MAAM;EACN,KAAK,eAAe,aAAa,YAAY;CAC/C;;;;CAKA,AAAO,YAAY,OAAqB;EACtC,OAAO,OAAO,UAAU;CAC1B;;;;;;;;;;;;;;;;;;;CAoBA,AAAQ,mBACN,MACA,cACA,UAAa,CAAC,GACR;EACN,MAAM,WAAW,KAAK;EAEtB,IAAI,CAAC,SAAS,SAAS,MAAM,YAAY,QAAQ,WAAW,kBAAkB,GAC5E,SAAS,kBAAkB,kBAAkB;EAG/C,SAAS,eAAe,MAAM,cAAc,OAAO;EAEnD,OAAO;CACT;;CAKA,AAAO,SAAS,cAAuB;EACrC,OAAO,KAAK,mBAAmB,cAAc,YAAY;CAC3D;;CAGA,AAAO,WAAW,OAAe,OAAY,cAAuB;EAClE,OAAO,KAAK,mBAAmB,gBAAgB,cAAc;GAAE;GAAO;EAAM,CAAC;CAC/E;;CAGA,AAAO,eAAe,OAAe,OAAY,cAAuB;EACtE,OAAO,KAAK,mBAAmB,oBAAoB,cAAc;GAAE;GAAO;EAAM,CAAC;CACnF;;CAGA,AAAO,mBAAmB,OAAe,cAAuB;EAC9D,OAAO,KAAK,mBAAmB,wBAAwB,cAAc,EAAE,MAAM,CAAC;CAChF;;CAGA,AAAO,kBAAkB,OAAe,cAAuB;EAC7D,OAAO,KAAK,mBAAmB,uBAAuB,cAAc,EAAE,MAAM,CAAC;CAC/E;;CAGA,AAAO,gBAAgB,OAAe,cAAuB;EAC3D,OAAO,KAAK,mBAAmB,qBAAqB,cAAc,EAAE,MAAM,CAAC;CAC7E;;CAKA,AAAO,SAAS,cAAuB;EACrC,OAAO,KAAK,mBAAmB,cAAc,YAAY;CAC3D;;CAGA,AAAO,WAAW,OAAe,OAAY,cAAuB;EAClE,OAAO,KAAK,mBAAmB,gBAAgB,cAAc;GAAE;GAAO;EAAM,CAAC;CAC/E;;CAGA,AAAO,eAAe,OAAe,OAAY,cAAuB;EACtE,OAAO,KAAK,mBAAmB,oBAAoB,cAAc;GAAE;GAAO;EAAM,CAAC;CACnF;;CAGA,AAAO,mBAAmB,OAAe,cAAuB;EAC9D,OAAO,KAAK,mBAAmB,wBAAwB,cAAc,EAAE,MAAM,CAAC;CAChF;;CAGA,AAAO,kBAAkB,OAAe,cAAuB;EAC7D,OAAO,KAAK,mBAAmB,uBAAuB,cAAc,EAAE,MAAM,CAAC;CAC/E;;CAGA,AAAO,gBAAgB,OAAe,cAAuB;EAC3D,OAAO,KAAK,mBAAmB,qBAAqB,cAAc,EAAE,MAAM,CAAC;CAC7E;;;;;;;;;;;;;;;;;;;;;CAwBA,AAAO,SAAS;EACd,OAAO,KAAK,WAAW,oBAAoB;CAC7C;;;;;CAQA,AAAO,WAAW,cAAuB;EACvC,OAAO,KAAK,MAAM,MAAM,YAAY;CACtC;;;;;CAMA,AAAO,YAAY,cAAuB;EACxC,OAAO,KAAK,MAAM,OAAO,YAAY;CACvC;;;;;;;;;;;;;;;;CAiBA,AAAgB,aAAa,SAA2B,iBAAmC;EACzF,MAAM,SAA2B,EAAE,MAAM,UAAU;EACnD,IAAI,KAAK,YAAY,cAAc,QAAQ,MAAM;EACjD,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"boolean-validator.mjs","names":[],"sources":["../../../../../../../seal/src/validators/boolean-validator.ts"],"sourcesContent":["import { booleanCoerceMutator, formBooleanMutator } from \"../mutators/boolean-mutators\";\nimport {\n acceptedIfPresentRule,\n acceptedIfRequiredRule,\n acceptedIfRule,\n acceptedRule,\n acceptedUnlessRule,\n acceptedWithoutRule,\n declinedIfPresentRule,\n declinedIfRequiredRule,\n declinedIfRule,\n declinedRule,\n declinedUnlessRule,\n declinedWithoutRule,\n} from \"../rules/scalar\";\nimport { booleanRule } from \"../rules\";\nimport { PrimitiveValidator } from \"./primitive-validator\";\nimport { applyNullable } from \"../standard-schema/json-schema\";\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\nimport type { SchemaRule, SchemaRuleOptions } from \"../types\";\n\n/**\n * Boolean validator class\n *\n * Extends PrimitiveValidator — inherits enum/in/oneOf/allowsOnly/forbids/notIn.\n * Defines accepted/declined directly as real methods (not ScalarValidator field copies)\n * so they survive cloning correctly.\n */\nexport class BooleanValidator extends PrimitiveValidator {\n public constructor(errorMessage?: string) {\n super();\n this.blankIsMissing = true;\n this.addMutableRule(booleanRule, errorMessage);\n }\n\n /**\n * Check if value is a boolean type\n */\n public matchesType(value: any): boolean {\n return typeof value === \"boolean\";\n }\n\n /**\n * Add a rule from the accepted/declined family, opting the validator into\n * form-boolean parsing.\n *\n * Calling ANY `accepted*`/`declined*` method on `v.boolean()` adds (once,\n * idempotently — checked by mutator identity so chaining several of these\n * methods never stacks duplicates) `formBooleanMutator`, which runs before\n * the type rule and converts the accepted set (`1`, `\"1\"`, `true`,\n * `\"true\"`, `\"yes\"`, `\"y\"`, `\"on\"`, `\"Yes\"`, `\"Y\"`, `\"On\"`) to `true` and\n * the declined set (`0`, `\"0\"`, `false`, `\"false\"`, `\"no\"`, `\"n\"`, `\"off\"`,\n * `\"No\"`, `\"N\"`, `\"Off\"`) to `false`; any other value passes through\n * unchanged and is rejected by the strict type rule as before.\n *\n * The mutator and the rule are added to the SAME resolved instance in one\n * pass — resolving `this.instance` twice (once per `addRule`/`addMutator`\n * call) would clone twice on an immutable validator and silently drop one\n * of the two additions.\n */\n private addFormBooleanRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n\n if (!instance.mutators.some((mutator) => mutator.mutate === formBooleanMutator)) {\n instance.addMutableMutator(formBooleanMutator);\n }\n\n instance.addMutableRule(rule, errorMessage, options);\n\n return instance;\n }\n\n // ==================== Accepted ====================\n\n /** Value must be accepted (true, \"yes\", 1, \"on\", etc. — form strings are parsed into a real boolean first) */\n public accepted(errorMessage?: string) {\n return this.addFormBooleanRule(acceptedRule, errorMessage);\n }\n\n /** Value must be accepted if another field equals a value */\n public acceptedIf(field: string, value: any, errorMessage?: string) {\n return this.addFormBooleanRule(acceptedIfRule, errorMessage, { field, value });\n }\n\n /** Value must be accepted unless another field equals a value */\n public acceptedUnless(field: string, value: any, errorMessage?: string) {\n return this.addFormBooleanRule(acceptedUnlessRule, errorMessage, { field, value });\n }\n\n /** Value must be accepted if another field is required */\n public acceptedIfRequired(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(acceptedIfRequiredRule, errorMessage, { field });\n }\n\n /** Value must be accepted if another field is present */\n public acceptedIfPresent(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(acceptedIfPresentRule, errorMessage, { field });\n }\n\n /** Value must be accepted if another field is missing */\n public acceptedWithout(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(acceptedWithoutRule, errorMessage, { field });\n }\n\n // ==================== Declined ====================\n\n /** Value must be declined (false, \"no\", 0, \"off\", etc. — form strings are parsed into a real boolean first) */\n public declined(errorMessage?: string) {\n return this.addFormBooleanRule(declinedRule, errorMessage);\n }\n\n /** Value must be declined if another field equals a value */\n public declinedIf(field: string, value: any, errorMessage?: string) {\n return this.addFormBooleanRule(declinedIfRule, errorMessage, { field, value });\n }\n\n /** Value must be declined unless another field equals a value */\n public declinedUnless(field: string, value: any, errorMessage?: string) {\n return this.addFormBooleanRule(declinedUnlessRule, errorMessage, { field, value });\n }\n\n /** Value must be declined if another field is required */\n public declinedIfRequired(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(declinedIfRequiredRule, errorMessage, { field });\n }\n\n /** Value must be declined if another field is present */\n public declinedIfPresent(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(declinedIfPresentRule, errorMessage, { field });\n }\n\n /** Value must be declined if another field is missing */\n public declinedWithout(field: string, errorMessage?: string) {\n return this.addFormBooleanRule(declinedWithoutRule, errorMessage, { field });\n }\n\n // ==================== Coercion ====================\n\n /**\n * Opt in to coercion: an exact query-string-shaped boolean is converted to a\n * real boolean **before** the type rules run; any other value passes through\n * unchanged so bad input still fails the type rule.\n *\n * Converts exactly `\"true\"` / `\"1\"` / `1` → `true` and `\"false\"` / `\"0\"` / `0`\n * → `false`. Case-sensitive, no trimming — `\"TRUE\"`, `\"yes\"`, `\"on\"`, `\"\"`, and\n * `2` all pass through unchanged and fail the type rule. `v.boolean()` does\n * **not** coerce by default; this only takes effect when explicitly chained.\n * For form-style truthy strings like `\"yes\"` / `\"on\"`, use `.accepted()` /\n * `.declined()` instead — those methods opt into their own form-boolean\n * parsing (a wider value set, case-insensitive on a few forms) and then\n * apply the accepted/declined pass-fail rule on top of the parsed boolean.\n *\n * The output type is unchanged (`Infer<>` keys off the validator class), so\n * `v.boolean().coerce()` still infers `boolean`.\n *\n * @example\n * v.boolean().coerce() // \"true\" → true; \"1\" → true; \"0\" → false; \"yes\" → invalid\n */\n public coerce() {\n return this.addMutator(booleanCoerceMutator) as this & { isCoerced: true };\n }\n\n // ==================== Strict boolean checks ====================\n\n /**\n * Value must be strictly true (not \"yes\", \"on\", 1, etc.)\n * @alias accepted - strict version\n */\n public mustBeTrue(errorMessage?: string) {\n return this.equal(true, errorMessage);\n }\n\n /**\n * Value must be strictly false (not \"no\", \"off\", 0, etc.)\n * @alias declined - strict version\n */\n public mustBeFalse(errorMessage?: string) {\n return this.equal(false, errorMessage);\n }\n\n /**\n * @inheritdoc\n *\n * @note accepted/declined rules and all cross-field boolean rules\n * are not representable in JSON Schema and are silently omitted.\n *\n * @example\n * ```ts\n * v.boolean().toJsonSchema(\"draft-2020-12\")\n * // → { type: \"boolean\" }\n *\n * v.boolean().nullable().toJsonSchema(\"openapi-3.0\")\n * // → { type: \"boolean\", nullable: true }\n * ```\n */\n public override toJsonSchema(target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n const schema: JsonSchemaResult = { type: \"boolean\" };\n if (this.isNullable) applyNullable(schema, target);\n return schema;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,IAAa,mBAAb,cAAsC,mBAAmB;CACvD,AAAO,YAAY,cAAuB;EACxC,MAAM;EACN,KAAK,iBAAiB;EACtB,KAAK,eAAe,aAAa,YAAY;CAC/C;;;;CAKA,AAAO,YAAY,OAAqB;EACtC,OAAO,OAAO,UAAU;CAC1B;;;;;;;;;;;;;;;;;;;CAoBA,AAAQ,mBACN,MACA,cACA,UAAa,CAAC,GACR;EACN,MAAM,WAAW,KAAK;EAEtB,IAAI,CAAC,SAAS,SAAS,MAAM,YAAY,QAAQ,WAAW,kBAAkB,GAC5E,SAAS,kBAAkB,kBAAkB;EAG/C,SAAS,eAAe,MAAM,cAAc,OAAO;EAEnD,OAAO;CACT;;CAKA,AAAO,SAAS,cAAuB;EACrC,OAAO,KAAK,mBAAmB,cAAc,YAAY;CAC3D;;CAGA,AAAO,WAAW,OAAe,OAAY,cAAuB;EAClE,OAAO,KAAK,mBAAmB,gBAAgB,cAAc;GAAE;GAAO;EAAM,CAAC;CAC/E;;CAGA,AAAO,eAAe,OAAe,OAAY,cAAuB;EACtE,OAAO,KAAK,mBAAmB,oBAAoB,cAAc;GAAE;GAAO;EAAM,CAAC;CACnF;;CAGA,AAAO,mBAAmB,OAAe,cAAuB;EAC9D,OAAO,KAAK,mBAAmB,wBAAwB,cAAc,EAAE,MAAM,CAAC;CAChF;;CAGA,AAAO,kBAAkB,OAAe,cAAuB;EAC7D,OAAO,KAAK,mBAAmB,uBAAuB,cAAc,EAAE,MAAM,CAAC;CAC/E;;CAGA,AAAO,gBAAgB,OAAe,cAAuB;EAC3D,OAAO,KAAK,mBAAmB,qBAAqB,cAAc,EAAE,MAAM,CAAC;CAC7E;;CAKA,AAAO,SAAS,cAAuB;EACrC,OAAO,KAAK,mBAAmB,cAAc,YAAY;CAC3D;;CAGA,AAAO,WAAW,OAAe,OAAY,cAAuB;EAClE,OAAO,KAAK,mBAAmB,gBAAgB,cAAc;GAAE;GAAO;EAAM,CAAC;CAC/E;;CAGA,AAAO,eAAe,OAAe,OAAY,cAAuB;EACtE,OAAO,KAAK,mBAAmB,oBAAoB,cAAc;GAAE;GAAO;EAAM,CAAC;CACnF;;CAGA,AAAO,mBAAmB,OAAe,cAAuB;EAC9D,OAAO,KAAK,mBAAmB,wBAAwB,cAAc,EAAE,MAAM,CAAC;CAChF;;CAGA,AAAO,kBAAkB,OAAe,cAAuB;EAC7D,OAAO,KAAK,mBAAmB,uBAAuB,cAAc,EAAE,MAAM,CAAC;CAC/E;;CAGA,AAAO,gBAAgB,OAAe,cAAuB;EAC3D,OAAO,KAAK,mBAAmB,qBAAqB,cAAc,EAAE,MAAM,CAAC;CAC7E;;;;;;;;;;;;;;;;;;;;;CAwBA,AAAO,SAAS;EACd,OAAO,KAAK,WAAW,oBAAoB;CAC7C;;;;;CAQA,AAAO,WAAW,cAAuB;EACvC,OAAO,KAAK,MAAM,MAAM,YAAY;CACtC;;;;;CAMA,AAAO,YAAY,cAAuB;EACxC,OAAO,KAAK,MAAM,OAAO,YAAY;CACvC;;;;;;;;;;;;;;;;CAiBA,AAAgB,aAAa,SAA2B,iBAAmC;EACzF,MAAM,SAA2B,EAAE,MAAM,UAAU;EACnD,IAAI,KAAK,YAAY,cAAc,QAAQ,MAAM;EACjD,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"date-validator.d.mts","names":[],"sources":["../../../../../../../seal/src/validators/date-validator.ts"],"mappings":";;;;;;;;cAwEa,aAAA,SAAsB,aAAA;cACd,YAAA;;;;
|
|
1
|
+
{"version":3,"file":"date-validator.d.mts","names":[],"sources":["../../../../../../../seal/src/validators/date-validator.ts"],"mappings":";;;;;;;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