API reference
Thin reference. Every exported identifier, grouped by category, with signature and one minimal example. For “how to use this well” guidance, see the Essentials and Guides sections.
Canonical import:
import { v, validate, type Infer, configureSeal, registerPlugin, type SealPlugin,} from "@warlock.js/seal";Validation entry points
Section titled “Validation entry points”The factory object. Every primitive and structural validator comes off v.
const schema = v.object({ email: v.string().email() });Source: @warlock.js/seal/src/factory/validators.ts.
validate(schema, data, options?)
Section titled “validate(schema, data, options?)”validate<T extends BaseValidator>( schema: T, data: unknown, options?: ValidateOptions,): Promise<TypedValidationResult<ValidatedOutput<T>>>;
type TypedValidationResult<TData> = | { isValid: true; data: TData; errors: ValidationResult["errors"] } | { isValid: false; data: undefined; errors: ValidationResult["errors"] };Runs the schema against data and returns { isValid, data, errors }. Never throws on bad input. On success data is Infer.Output<T>; on failure it is undefined. A schema typed as bare BaseValidator/ObjectValidator keeps data: any; a typed v.record(...) keeps Record<string, …>.
const result = await validate(userSchema, request.body);if (result.isValid) handle(result.data); // Infer.Output<typeof userSchema>Source: @warlock.js/seal/src/factory/validate.ts.
ValidateOptions
Section titled “ValidateOptions”type ValidateOptions = { context?: Record<string, any>; // passed through to SchemaContext.rootContext translateRule?: TranslateRuleCallback; translateAttribute?: TranslateAttributeCallback; firstErrorOnly?: boolean; // Limits (see `SealConfig`); a value here wins over `configureSeal()` for this call maxArrayItems?: number; maxRecordKeys?: number; maxErrors?: number; maxDepth?: number;};Primitives (leaf validators)
Section titled “Primitives (leaf validators)”v.string(errorMessage?)
Section titled “v.string(errorMessage?)”v.string(); // type: stringv.string().email();v.string().url();v.string().uuid(4);v.string().min(3).max(50);url() accepts every scheme URL can parse except the script-capable ones: javascript:, data:, vbscript: and file: are refused. Pass protocols to accept only the listed schemes (with or without the trailing :), which is also how a refused scheme is opted back in:
v.string().url(); // https://…, mailto:…, myapp://… — not javascript:…v.string().url({ protocols: ["http", "https"] }); // web links onlyv.string().url({ protocols: ["https"] }, "Use an https link");pattern(regex) gives the same answer on every call, also for a regex with the g or y flag (each check starts at index 0).
urlDecode() leaves a value with a malformed escape sequence (%E0%A4%A) as it was instead of throwing; the other rules then judge the raw value.
v.email(emailMessage?, errorMessage?)
Section titled “v.email(emailMessage?, errorMessage?)”v.email(); // shortcut for v.string().email()v.number(errorMessage?)
Section titled “v.number(errorMessage?)”v.number().min(0).max(100);Only finite numbers pass: NaN, Infinity and -Infinity are refused. The math mutators (abs(), ceil(), floor(), round(), toFixed()) and coerce() convert numbers and numeric strings only; anything else ("abc", true, [7], {}) reaches the type rule unchanged and fails it.
v.int(errorMessage?)
Section titled “v.int(errorMessage?)”v.int().positive(); // rejects 1.5 and negativesv.float(errorMessage?)
Section titled “v.float(errorMessage?)”v.float().between(0, 1); // rejects 1 and 0v.numeric(errorMessage?)
Section titled “v.numeric(errorMessage?)”v.numeric().min(0); // accepts "42" and 42v.boolean(errorMessage?)
Section titled “v.boolean(errorMessage?)”v.boolean();v.boolean().accepted(); // for "on" / "yes" / "1" form values → real booleanv.boolean().coerce(); // "true"/"1"/1 → true, "false"/"0"/0 → false (query strings)v.scalar(errorMessage?)
Section titled “v.scalar(errorMessage?)”v.scalar(); // type: string | number | booleanv.date(errorMessage?)
Section titled “v.date(errorMessage?)”v.date().past();v.date().defaultNow();v.literal(...values)
Section titled “v.literal(...values)”v.literal("admin", "user"); // type: "admin" | "user"v.enum(values, errorMessage?)
Section titled “v.enum(values, errorMessage?)”v.enum(["draft", "published"]); // array formv.enum(StatusEnum); // TS enum objectv.instanceof(ctor, errorMessage?)
Section titled “v.instanceof(ctor, errorMessage?)”v.instanceof(File);v.instanceof(MyClass);v.computed<T>(callback, resultValidator?)
Section titled “v.computed<T>(callback, resultValidator?)”v.computed<string>(({ first, last }) => `${first} ${last}`);v.managed<T>(callback?, resultValidator?)
Section titled “v.managed<T>(callback?, resultValidator?)”v.managed<Date>(() => new Date());v.managed<string>(({ user }) => user.id);v.any()
Section titled “v.any()”v.any(); // type: anyInside an object, v.any() values (and unknown keys kept by .allowUnknown()) are copied without __proto__ keys, so a request body cannot set the prototype of the validated output. Data nested more than maxDepth levels below the object (256 by default) fails with a maxDepth error.
Structural validators
Section titled “Structural validators”v.object(schema, errorMessage?)
Section titled “v.object(schema, errorMessage?)”v.object({ email: v.string().email(), age: v.int().optional(),});v.array(validator, errorMessage?)
Section titled “v.array(validator, errorMessage?)”v.array(v.string()).minLength(1).maxLength(10);An array without .maxLength() (or .max()), .length() or .between() may hold at most maxArrayItems items (10,000 by default, see configureSeal); a longer one fails with a maxItems error before any item is validated. An explicit .maxLength(n) replaces the default cap for that schema; .maxLength(Infinity) lifts it.
Items are validated 64 at a time. Once maxErrors errors are collected (100 by default) no further items are validated, and the list is cut to that length.
v.record(valueValidator?, errorMessage?)
Section titled “v.record(valueValidator?, errorMessage?)”v.record(v.int()); // type: Record<string, number>v.record(v.int()).maxKeys(50); // at most 50 keys (JSON Schema: maxProperties)A record without .maxKeys(n) may hold at most maxRecordKeys keys (10,000 by default); a larger one fails with a maxKeys error. .maxKeys(Infinity) lifts the cap for that schema. Values are validated in batches under the same maxErrors limit as arrays. A __proto__ key fails with a forbiddenKey error.
v.tuple(validators, errorMessage?)
Section titled “v.tuple(validators, errorMessage?)”v.tuple([v.string(), v.int()]); // type: [string, number]v.union(validators, errorMessage?)
Section titled “v.union(validators, errorMessage?)”v.union([v.string(), v.int()]); // type: string | numberTries every branch whose type matches, in order; the first that passes wins and its output is returned. When none passes, the closest branch’s errors are reported (fewest mismatched literals, then fewest errors, then deepest path) with type "union" at their own paths. errorMessage replaces them with one error at the union’s path.
v.discriminatedUnion(key, branches)
Section titled “v.discriminatedUnion(key, branches)”v.discriminatedUnion("type", [ v.object({ type: v.literal("a"), x: v.string() }), v.object({ type: v.literal("b"), y: v.int() }),]);v.lazy(thunk)
Section titled “v.lazy(thunk)”v.lazy(() => categorySchema); // for recursive / forward refsInference
Section titled “Inference”Infer<T>
Section titled “Infer<T>”type User = Infer<typeof userSchema>;Alias for Infer.Input<T>.
Infer.Input<T>
Section titled “Infer.Input<T>”What the caller is allowed to send (pre-validation). .optional(), .default(), .catch() all mark a key optional here.
Infer.Output<T>
Section titled “Infer.Output<T>”What result.data contains (post-validation). .default() and .catch() guarantee a value, so those keys are required here.
type In = Infer.Input<typeof schema>;type Out = Infer.Output<typeof schema>;Configuration
Section titled “Configuration”configureSeal(options)
Section titled “configureSeal(options)”configureSeal({ firstErrorOnly: false, translateRule: ({ rule, attributes }) => t(`validation.${rule.name}`, attributes),});getSealConfig()
Section titled “getSealConfig()”const config = getSealConfig(); // SealConfigresetSealConfig()
Section titled “resetSealConfig()”resetSealConfig(); // clear translation hooks + reset firstErrorOnly and the limits to their defaultsSealConfig
Section titled “SealConfig”type SealConfig = { translateRule?: (ruleTranslation: RuleTranslation) => string; translateAttribute?: (attributeTranslation: AttributeTranslation) => string; firstErrorOnly?: boolean; // default: true maxArrayItems?: number; // default: 10000 — arrays without .maxLength(); Infinity lifts it maxRecordKeys?: number; // default: 10000 — records without .maxKeys(); Infinity lifts it maxErrors?: number; // default: 100 — errors one array or record collects maxDepth?: number; // default: 256 — nesting inside an object's output};The limits bound what one request can cost. Raise them for a schema with .maxLength(n) / .maxKeys(n), for one call with the validate() options, or for the whole app:
configureSeal({ maxArrayItems: 50_000, maxErrors: 20 });The limit errors use the rule names maxItems, maxKeys and maxDepth, so they can be translated like any other rule.
Source: @warlock.js/seal/src/config.ts.
Plugin system
Section titled “Plugin system”registerPlugin(plugin)
Section titled “registerPlugin(plugin)”await registerPlugin(slugPlugin);Async. Idempotent — duplicate names warn and skip.
unregisterPlugin(name)
Section titled “unregisterPlugin(name)”await unregisterPlugin("slug");Runs the plugin’s uninstall?.() and removes from the registry.
hasPlugin(name)
Section titled “hasPlugin(name)”if (hasPlugin("slug")) { /* ... */}getInstalledPlugins()
Section titled “getInstalledPlugins()”const plugins = getInstalledPlugins(); // SealPlugin[]SealPlugin
Section titled “SealPlugin”type SealPlugin = { name: string; version?: string; description?: string; install: (context: PluginContext) => void | Promise<void>; uninstall?: () => void | Promise<void>;};Source: @warlock.js/seal/src/plugins/plugin-system.ts.
Validator classes (for plugin authoring + type narrowing)
Section titled “Validator classes (for plugin authoring + type narrowing)”These are the underlying classes the factory wraps. You rarely touch them in app code — they’re exported for plugin authoring (module augmentation, prototype patching) and for typing slots that accept a specific validator shape.
BaseValidator— root class withvalidate,toJsonSchema, chain methods.StringValidator,NumberValidator,IntValidator,FloatValidator,NumericValidator,BooleanValidator,ScalarValidator,DateValidator.LiteralValidator<T>,InstanceOfValidator<T>,AnyValidator.ObjectValidator<TSchema>,ArrayValidator,RecordValidator,TupleValidator.UnionValidator,DiscriminatedUnionValidator<K, Branches>.LazyValidator<T>.ComputedValidator<TResult>,ManagedValidator<TResult>.
Each lives in its own file under @warlock.js/seal/src/validators/.
Standard Schema
Section titled “Standard Schema”schema["~standard"]
Section titled “schema["~standard"]”const result = await schema["~standard"].validate(input);// → { value } on success, { issues } on failure
const json = schema["~standard"].jsonSchema.input({ target: "openai-strict" });The Standard Schema V1 accessor. See Bridge Standard Schema guide.
StandardSchemaV1<Input, Output>
Section titled “StandardSchemaV1<Input, Output>”The Standard Schema V1 interface seal implements. Re-exported from @warlock.js/seal/src/standard-schema/types.ts.
StandardJSONSchemaV1
Section titled “StandardJSONSchemaV1”Seal’s extension of the Standard Schema spec adding JSON Schema accessors.
JSON Schema
Section titled “JSON Schema”schema.toJsonSchema(target?)
Section titled “schema.toJsonSchema(target?)”schema.toJsonSchema("draft-2020-12");schema.toJsonSchema("draft-07");schema.toJsonSchema("openapi-3.0");schema.toJsonSchema("openai-strict");Default target is "draft-2020-12".
JsonSchemaTarget
Section titled “JsonSchemaTarget”type JsonSchemaTarget = "draft-2020-12" | "draft-07" | "openapi-3.0" | "openai-strict";Source: @warlock.js/seal/src/standard-schema/json-schema.ts.
The package exports its type surface from @warlock.js/seal/src/types/:
Schema— aRecord<string, BaseValidator>(the input tov.object).SchemaContext— runtime context passed through validation (siblings, path, configurations).ValidationResult—{ isValid, data, errors }.RuleTranslation,AttributeTranslation— params passed to the translation hooks.Mutator,TransformerCallback,SimpleTransformerCallback— data-pipeline shapes.SchemaRule,ContextualSchemaRule,SchemaRuleOptions— for custom rule authoring.
Source: @warlock.js/seal/src/types/index.ts.
Related
Section titled “Related”- Essentials — the daily-use reference.
- Guides — task-shaped how-tos.
- Recipes — copy-paste patterns.