validup 0.2.2 → 0.4.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/LICENSE +201 -21
- package/README.md +868 -115
- package/dist/index.d.mts +1473 -0
- package/dist/index.mjs +1561 -450
- package/dist/index.mjs.map +1 -1
- package/package.json +16 -18
- package/dist/constants.d.ts +0 -17
- package/dist/container/check.d.ts +0 -2
- package/dist/container/index.d.ts +0 -3
- package/dist/container/module.d.ts +0 -23
- package/dist/container/types.d.ts +0 -120
- package/dist/error/base.d.ts +0 -5
- package/dist/error/check.d.ts +0 -5
- package/dist/error/index.d.ts +0 -2
- package/dist/helpers/error.d.ts +0 -2
- package/dist/helpers/index.d.ts +0 -3
- package/dist/helpers/optional-value.d.ts +0 -8
- package/dist/helpers/path-stringify.d.ts +0 -6
- package/dist/index.cjs +0 -494
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.ts +0 -7
- package/dist/issue/check.d.ts +0 -4
- package/dist/issue/constants.d.ts +0 -4
- package/dist/issue/define.d.ts +0 -5
- package/dist/issue/index.d.ts +0 -4
- package/dist/issue/types.d.ts +0 -47
- package/dist/types.d.ts +0 -24
- package/dist/utils/has-own-property.d.ts +0 -1
- package/dist/utils/index.d.ts +0 -2
- package/dist/utils/object.d.ts +0 -1
package/README.md
CHANGED
|
@@ -1,180 +1,933 @@
|
|
|
1
|
-
#
|
|
1
|
+
# validup 🛡️
|
|
2
2
|
|
|
3
|
-
[![
|
|
4
|
-
[![
|
|
5
|
-
[![
|
|
6
|
-
[![
|
|
3
|
+
[![npm version][npm-version-src]][npm-version-href]
|
|
4
|
+
[![Master Workflow][workflow-src]][workflow-href]
|
|
5
|
+
[![CodeQL][codeql-src]][codeql-href]
|
|
6
|
+
[![Known Vulnerabilities][snyk-src]][snyk-href]
|
|
7
|
+
[![Conventional Commits][conventional-src]][conventional-href]
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
A composable, path-based validation library for TypeScript.
|
|
9
10
|
|
|
10
|
-
|
|
11
|
-
>
|
|
12
|
-
> Validup is currently under active development and is not yet ready for production.
|
|
11
|
+
Mount any validator function (or nested container) onto any path of your input, run them in groups, collect structured issues, and bridge to existing libraries via integration packages. No decorators, no schema DSL, no metadata reflection.
|
|
13
12
|
|
|
14
13
|
**Table of Contents**
|
|
15
14
|
|
|
16
|
-
- [Features](#features)
|
|
17
15
|
- [Installation](#installation)
|
|
18
|
-
- [
|
|
19
|
-
- [Concepts](#concepts)
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
- [
|
|
16
|
+
- [Quick Start](#quick-start)
|
|
17
|
+
- [Key Concepts](#key-concepts)
|
|
18
|
+
- [Validators](#validators)
|
|
19
|
+
- [Containers](#containers)
|
|
20
|
+
- [Issues & Errors](#issues--errors)
|
|
21
|
+
- [Builder API (compile-time typing)](#builder-api-compile-time-typing)
|
|
22
|
+
- [Mounting](#mounting)
|
|
23
|
+
- [Path Patterns](#path-patterns)
|
|
24
|
+
- [Nested Containers](#nested-containers)
|
|
25
|
+
- [Mounting Without a Path](#mounting-without-a-path)
|
|
26
|
+
- [Subclassing](#subclassing)
|
|
27
|
+
- [Groups](#groups)
|
|
28
|
+
- [Optional Values](#optional-values)
|
|
29
|
+
- [oneOf Branches](#oneof-branches)
|
|
30
|
+
- [Path Filtering](#path-filtering)
|
|
31
|
+
- [Defaults](#defaults)
|
|
32
|
+
- [Context](#context)
|
|
33
|
+
- [Cancellation](#cancellation)
|
|
34
|
+
- [Run Modes](#run-modes)
|
|
35
|
+
- [Parallel Execution](#parallel-execution)
|
|
36
|
+
- [Safe Run](#safe-run)
|
|
37
|
+
- [Sync Fast Path](#sync-fast-path)
|
|
38
|
+
- [Localized Messages](#localized-messages)
|
|
39
|
+
- [Error Handling](#error-handling)
|
|
40
|
+
- [ValidupError](#validuperror)
|
|
41
|
+
- [Issue Shape](#issue-shape)
|
|
42
|
+
- [Issue Codes](#issue-codes)
|
|
43
|
+
- [API Reference](#api-reference)
|
|
44
|
+
- [Container](#container)
|
|
45
|
+
- [defineSchema](#defineschema)
|
|
46
|
+
- [Issue Helpers](#issue-helpers)
|
|
47
|
+
- [Type Guards](#type-guards)
|
|
48
|
+
- [Integrations](#integrations)
|
|
49
|
+
- [Stability](#stability)
|
|
25
50
|
- [License](#license)
|
|
26
51
|
|
|
27
|
-
## Features
|
|
28
|
-
|
|
29
|
-
- ✨ Simple API
|
|
30
|
-
- 🌐 Works in any (Node.Js, browser & workers) environment
|
|
31
|
-
- ❌ Dedicated errors for different scenarios
|
|
32
|
-
- 🚀 Nesting of Validators and Containers
|
|
33
|
-
- 🎭 Easy integrate third-party validators/sanitizers (zod, validator.js, ...)
|
|
34
|
-
|
|
35
52
|
## Installation
|
|
36
53
|
|
|
37
54
|
```bash
|
|
38
55
|
npm install validup --save
|
|
39
56
|
```
|
|
40
57
|
|
|
41
|
-
##
|
|
42
|
-
|
|
43
|
-
A validator is an (async) function to validate (and modify) any piece of information.
|
|
44
|
-
Each validator receives a [context](#validatorcontext) containing the actual value, key (aka path), ...
|
|
58
|
+
## Quick Start
|
|
45
59
|
|
|
46
60
|
```typescript
|
|
47
|
-
import {
|
|
48
|
-
Validator,
|
|
49
|
-
ValidatorContext,
|
|
50
|
-
ValidupValidatorError
|
|
51
|
-
} from 'validup';
|
|
61
|
+
import { Container, ValidupError, type Validator } from 'validup';
|
|
52
62
|
|
|
53
|
-
const isString: Validator = (ctx
|
|
63
|
+
const isString: Validator = (ctx) => {
|
|
54
64
|
if (typeof ctx.value !== 'string') {
|
|
55
|
-
throw new
|
|
56
|
-
message: `The validator for ${ctx.path} expected a string as input.`,
|
|
57
|
-
expected: 'string',
|
|
58
|
-
path: ctx.path
|
|
59
|
-
})
|
|
65
|
+
throw new Error('Value is not a string');
|
|
60
66
|
}
|
|
61
|
-
|
|
62
67
|
return ctx.value;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const container = new Container<{ name: string; email: string }>();
|
|
71
|
+
|
|
72
|
+
container.mount('name', isString);
|
|
73
|
+
container.mount('email', isString);
|
|
74
|
+
|
|
75
|
+
const valid = await container.run({
|
|
76
|
+
name: 'Peter',
|
|
77
|
+
email: 'peter@example.com',
|
|
78
|
+
});
|
|
79
|
+
// valid is { name: 'Peter', email: 'peter@example.com' }
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
When a validator throws, the container collects the failure into a structured `ValidupError`:
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
try {
|
|
86
|
+
await container.run({ name: 42, email: 'peter@example.com' });
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (error instanceof ValidupError) {
|
|
89
|
+
console.log(error.issues);
|
|
90
|
+
// [{ type: 'item', code: 'value_invalid', path: ['name'], message: '...' }]
|
|
91
|
+
}
|
|
63
92
|
}
|
|
64
93
|
```
|
|
65
94
|
|
|
66
|
-
|
|
67
|
-
|
|
95
|
+
## Key Concepts
|
|
96
|
+
|
|
97
|
+
### Validators
|
|
98
|
+
|
|
99
|
+
A validator is a (sync or async) function that receives a `ValidatorContext` and either returns the validated/transformed value or throws.
|
|
68
100
|
|
|
69
101
|
```typescript
|
|
70
|
-
|
|
102
|
+
type Validator<C = unknown, Out = unknown> = (ctx: ValidatorContext<C>) => Out | Promise<Out>;
|
|
103
|
+
|
|
104
|
+
type ValidatorContext<C = unknown> = {
|
|
105
|
+
key: string; // expanded mount path within the current container
|
|
106
|
+
path: PropertyKey[]; // global mount path including parent containers
|
|
107
|
+
value: unknown; // the value to validate
|
|
108
|
+
data: Record<string, any>; // input of the current container
|
|
109
|
+
group?: string; // active execution group, if any
|
|
110
|
+
context: C; // caller-supplied context (see [Context](#context))
|
|
111
|
+
signal?: AbortSignal; // cancellation signal (see [Cancellation](#cancellation))
|
|
112
|
+
};
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
A validator's **return value** becomes the output for that path — so validators double as transformers/sanitizers. The optional second generic `Out` lets callers (and the [Builder API](#builder-api-compile-time-typing)) infer per-field types from the validator's return type — `Out` defaults to `unknown`, so existing call sites compile unchanged.
|
|
116
|
+
|
|
117
|
+
#### Descriptor form
|
|
71
118
|
|
|
72
|
-
|
|
73
|
-
container.mount('foo', isString);
|
|
119
|
+
`mount()` also accepts a `ValidatorDescriptor<C, Out>` — a small wrapper that attaches per-mount metadata the framework consults. Today the metadata is just `sideEffect`, the switch that opts a validator out of the [result cache](#result-caching).
|
|
74
120
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
121
|
+
```typescript
|
|
122
|
+
import { defineValidator } from 'validup';
|
|
123
|
+
|
|
124
|
+
// Cache-eligible (default): same (value, context, group) → reuse result.
|
|
125
|
+
const isPositive = defineValidator({
|
|
126
|
+
run: (ctx) => {
|
|
127
|
+
if (typeof ctx.value !== 'number' || ctx.value <= 0) {
|
|
128
|
+
throw new Error('must be positive');
|
|
129
|
+
}
|
|
130
|
+
return ctx.value;
|
|
131
|
+
},
|
|
78
132
|
});
|
|
79
133
|
|
|
80
|
-
|
|
81
|
-
|
|
134
|
+
// Cross-field / network / stateful — re-run every time:
|
|
135
|
+
const isEmailUnique = defineValidator({
|
|
136
|
+
sideEffect: true,
|
|
137
|
+
run: async (ctx) => {
|
|
138
|
+
if (await api.isEmailTaken(ctx.value as string)) {
|
|
139
|
+
throw new Error('Email already taken');
|
|
140
|
+
}
|
|
141
|
+
return ctx.value;
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
container.mount('email', isEmailUnique);
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Bare functions stay fully supported — `mount('foo', fn)` normalizes them to `{ run: fn }` internally with no behavior change. Use `defineValidator` when you need the metadata.
|
|
149
|
+
|
|
150
|
+
### Containers
|
|
151
|
+
|
|
152
|
+
A `Container<T, C>` holds an ordered list of mounts and runs them against an input object. The optional generic `T` constrains mount keys and shapes the resolved output; the optional `C` types the caller-supplied [context](#context).
|
|
153
|
+
|
|
154
|
+
```typescript
|
|
155
|
+
const container = new Container<{ name: string; age: number }>();
|
|
156
|
+
|
|
157
|
+
container.mount('name', isString); // ✅ 'name' is a key of T
|
|
158
|
+
container.mount('email', isString); // ⚠️ 'email' is not — allowed via fallback type
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### Issues & Errors
|
|
162
|
+
|
|
163
|
+
When validation fails, the container throws a `ValidupError` containing a list of `Issue`s. Issues are a discriminated union — each one is either a leaf `IssueItem` or an `IssueGroup` containing children.
|
|
164
|
+
|
|
165
|
+
```typescript
|
|
166
|
+
type Issue = IssueItem | IssueGroup;
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
This recursive structure preserves the path of failure, so consumers can render rich field-level error messages.
|
|
170
|
+
|
|
171
|
+
## Builder API (compile-time typing)
|
|
172
|
+
|
|
173
|
+
`new Container<T>()` happily accepts mounts that don't cover every required key of `T`, and `run()` returns `T` regardless. The TypeScript shape is a promise the runtime can't keep:
|
|
174
|
+
|
|
175
|
+
```typescript
|
|
176
|
+
const c = new Container<{ foo: string; bar: number }>();
|
|
177
|
+
c.mount('foo', isString); // ⚠️ bar is never validated
|
|
178
|
+
const out = await c.run({}); // out: { foo, bar } — bar is undefined at runtime
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
`defineSchema()` is an opt-in, type-accumulating wrapper around `Container` that derives `T` *from the registered mounts* — so `run()`'s static return type reflects exactly what was registered:
|
|
182
|
+
|
|
183
|
+
```typescript
|
|
184
|
+
import { defineSchema } from 'validup';
|
|
185
|
+
import { createValidator } from '@validup/zod';
|
|
186
|
+
import { z } from 'zod';
|
|
187
|
+
|
|
188
|
+
const schema = defineSchema()
|
|
189
|
+
.mount('foo', createValidator(z.string())) // { foo: string }
|
|
190
|
+
.mount('age', { optional: true }, createValidator(z.number().int())) // { foo: string; age?: number }
|
|
191
|
+
.mount('address', defineSchema().mount('city', isString)) // { …; address: { city: string } }
|
|
192
|
+
.build();
|
|
193
|
+
|
|
194
|
+
const out = await schema.run(input);
|
|
195
|
+
// out: { foo: string; age?: number; address: { city: string } } — inferred, not declared
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
The integration packages' `createValidator(...)` functions (`@validup/zod`, `@validup/standard-schema`) infer the per-field `Out` type from the underlying schema, so the builder pulls real types through. Hand-written validators participate too — annotate the return type via `Validator<C, Out>` (or just write the function inline so TypeScript can infer it).
|
|
199
|
+
|
|
200
|
+
The builder mirrors `Container.mount`'s keyed forms — `.mount(key, target)` and `.mount(key, options, target)` — and dispatches on the target type:
|
|
201
|
+
|
|
202
|
+
| Target type | Effect on `T` |
|
|
203
|
+
|------------------------------------|-------------------------------------------------------------------------|
|
|
204
|
+
| `Validator<C, Out>` | adds `{ [K]: Awaited<Out> }` (or `{ [K]?: Awaited<Out> }` when `options.optional`) |
|
|
205
|
+
| `IBuilder<U, C>` | adds `{ [K]: U }` and auto-`.build()`s the child |
|
|
206
|
+
| `IContainer<U, C>` (e.g. `Container<U, C>`) | adds `{ [K]: U }` |
|
|
207
|
+
|
|
208
|
+
Builders are immutable — every method returns a new instance, so chains can fork without leaking state — and `.build()` materializes a `Container<T, C>`:
|
|
209
|
+
|
|
210
|
+
```typescript
|
|
211
|
+
interface IBuilder<T extends Record<string, any>, C = unknown> {
|
|
212
|
+
mount<K extends string, V extends Validator<C, any> | IBuilder<any, C> | IContainer<any, C>>(
|
|
213
|
+
key: K,
|
|
214
|
+
target: V,
|
|
215
|
+
): IBuilder<T & Mounted<K, V, undefined>, C>;
|
|
216
|
+
|
|
217
|
+
mount<K extends string, const O extends MountOptions, V extends Validator<C, any> | IBuilder<any, C> | IContainer<any, C>>(
|
|
218
|
+
key: K,
|
|
219
|
+
options: O,
|
|
220
|
+
target: V,
|
|
221
|
+
): IBuilder<T & Mounted<K, V, O>, C>;
|
|
222
|
+
|
|
223
|
+
oneOf(): IBuilder<T, C>;
|
|
224
|
+
pathsToInclude(...paths: (keyof T & string)[]): IBuilder<T, C>;
|
|
225
|
+
pathsToExclude(...paths: (keyof T & string)[]): IBuilder<T, C>;
|
|
226
|
+
build(): Container<T, C>;
|
|
227
|
+
}
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
> **Note** — the `?`-widening on `optional: true` only fires when TypeScript sees the value as the literal `true` (or a predicate function). The `const` modifier on the second overload preserves literals from inline option objects, so the common case (`mount('email', { optional: true }, ...)`) just works. A pre-typed `MountOptions` variable whose `optional` is `boolean` will keep the field required.
|
|
231
|
+
|
|
232
|
+
Pass the context type as a generic to flow it through the chain:
|
|
233
|
+
|
|
234
|
+
```typescript
|
|
235
|
+
type AppContext = { userId: string };
|
|
236
|
+
|
|
237
|
+
const schema = defineSchema<AppContext>()
|
|
238
|
+
.mount('slug', async (ctx) => {
|
|
239
|
+
// ctx.context is typed as AppContext
|
|
240
|
+
await assertSlugAvailable(ctx.value, ctx.context.userId);
|
|
241
|
+
return ctx.value;
|
|
242
|
+
})
|
|
243
|
+
.build();
|
|
244
|
+
|
|
245
|
+
await schema.run(input, { context: { userId: 'u-42' } });
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
When to reach for which API:
|
|
249
|
+
|
|
250
|
+
| Goal | API |
|
|
251
|
+
|--------------------------------------------------------------------|------------------------------------|
|
|
252
|
+
| Static schema, want compile-time exhaustiveness | `defineSchema()` builder |
|
|
253
|
+
| Dynamic mounts (loops, conditional registration, `initialize()` hook) | `new Container<T>()` |
|
|
254
|
+
| Ship a domain-scoped, reusable validator class | `class extends Container<T>` |
|
|
255
|
+
|
|
256
|
+
The imperative `Container` API is **not** deprecated — it remains the runtime substrate (`.build()` calls `Container.mount(...)`) and the right tool whenever the schema isn't fully known up front.
|
|
257
|
+
|
|
258
|
+
> **Note on `oneOf()`** — only one branch's keys actually appear in the runtime output, but the accumulated type stays as the intersection of every branch (honest about *possible* keys). Wrap the result with your own discriminated union when that fits better.
|
|
259
|
+
|
|
260
|
+
## Mounting
|
|
261
|
+
|
|
262
|
+
`container.mount(...)` is variadic. Pass any combination of:
|
|
263
|
+
|
|
264
|
+
| Argument | Meaning |
|
|
265
|
+
|------------------|----------------------------------|
|
|
266
|
+
| `string` | path |
|
|
267
|
+
| `function` | `Validator` |
|
|
268
|
+
| `Container` | nested container |
|
|
269
|
+
| plain object | `MountOptions` |
|
|
270
|
+
|
|
271
|
+
```typescript
|
|
272
|
+
container.mount('foo', validator); // path + validator
|
|
273
|
+
container.mount('foo', { group: 'create' }, validator); // path + options + validator
|
|
274
|
+
container.mount('foo', childContainer); // path + nested container
|
|
275
|
+
container.mount({ optional: true }, childContainer); // options + nested container (no path)
|
|
276
|
+
container.mount(childContainer); // nested container at root
|
|
82
277
|
```
|
|
83
278
|
|
|
84
|
-
|
|
85
|
-
> The container run method throws an error if an error occurred during the execution of a validator.
|
|
279
|
+
### Path Patterns
|
|
86
280
|
|
|
87
|
-
|
|
281
|
+
Paths are resolved via [pathtrace](https://www.npmjs.com/package/pathtrace) and support dot notation, bracket notation, and glob patterns:
|
|
88
282
|
|
|
89
|
-
|
|
283
|
+
```typescript
|
|
284
|
+
container.mount('foo.bar', validator); // nested key
|
|
285
|
+
container.mount('foo[1]', validator); // array index
|
|
286
|
+
container.mount('foo.**.bar', validator); // any depth
|
|
287
|
+
container.mount('**.id', validator); // every `id` anywhere in the tree
|
|
288
|
+
```
|
|
90
289
|
|
|
91
|
-
|
|
92
|
-
An error can contain multiple issues.
|
|
290
|
+
### Nested Containers
|
|
93
291
|
|
|
94
|
-
|
|
95
|
-
Unknown errors will be converted.
|
|
292
|
+
A container can mount another container at any path. The child's results are merged into the parent's output.
|
|
96
293
|
|
|
97
|
-
|
|
294
|
+
```typescript
|
|
295
|
+
const address = new Container<{ city: string; country: string }>();
|
|
296
|
+
address.mount('city', isString);
|
|
297
|
+
address.mount('country', isString);
|
|
98
298
|
|
|
99
|
-
|
|
100
|
-
|
|
299
|
+
const user = new Container<{ name: string; address: { city: string; country: string } }>();
|
|
300
|
+
user.mount('name', isString);
|
|
301
|
+
user.mount('address', address);
|
|
101
302
|
|
|
102
|
-
|
|
303
|
+
const valid = await user.run({
|
|
304
|
+
name: 'Peter',
|
|
305
|
+
address: { city: 'Berlin', country: 'DE' },
|
|
306
|
+
});
|
|
307
|
+
```
|
|
103
308
|
|
|
104
|
-
|
|
105
|
-
>
|
|
309
|
+
### Mounting Without a Path
|
|
106
310
|
|
|
107
|
-
|
|
108
|
-
|
|
311
|
+
A container (but **not** a validator) can be mounted without a path. Its mounts then operate on the parent's input directly — useful for splitting validation rules across multiple files while keeping a flat output shape.
|
|
312
|
+
|
|
313
|
+
```typescript
|
|
314
|
+
const credentials = new Container();
|
|
315
|
+
credentials.mount('email', isString);
|
|
316
|
+
credentials.mount('password', isString);
|
|
109
317
|
|
|
110
|
-
|
|
318
|
+
const profile = new Container();
|
|
319
|
+
profile.mount('name', isString);
|
|
320
|
+
|
|
321
|
+
const signup = new Container();
|
|
322
|
+
signup.mount(credentials); // no path — flatten into root
|
|
323
|
+
signup.mount(profile);
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
## Subclassing
|
|
327
|
+
|
|
328
|
+
For reusable, self-contained validators it's idiomatic to extend `Container<T>` and register your mounts inside the protected `initialize()` hook. The hook is called by the constructor, so consumers can simply `new RoleValidator()` and run it.
|
|
329
|
+
|
|
330
|
+
```typescript
|
|
111
331
|
import { Container } from 'validup';
|
|
332
|
+
import { createValidator } from '@validup/zod';
|
|
333
|
+
import { z } from 'zod';
|
|
334
|
+
|
|
335
|
+
type Role = { name: string; description?: string };
|
|
336
|
+
|
|
337
|
+
class RoleValidator extends Container<Role> {
|
|
338
|
+
protected override initialize() {
|
|
339
|
+
super.initialize();
|
|
340
|
+
|
|
341
|
+
const nameValidator = createValidator(z.string().min(3).max(128));
|
|
342
|
+
|
|
343
|
+
// Required on create, optional on update — same validator, different groups.
|
|
344
|
+
this.mount('name', { group: 'create' }, nameValidator);
|
|
345
|
+
this.mount('name', { group: 'update', optional: true }, nameValidator);
|
|
346
|
+
|
|
347
|
+
this.mount(
|
|
348
|
+
'description',
|
|
349
|
+
{ optional: true },
|
|
350
|
+
createValidator(z.string().max(4096).nullable()),
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const validator = new RoleValidator();
|
|
356
|
+
|
|
357
|
+
const onCreate = await validator.run(input, { group: 'create' });
|
|
358
|
+
const onUpdate = await validator.run(input, { group: 'update' });
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
This pattern keeps validators close to the entities they validate and makes them easy to share across HTTP layers, queue handlers, and CLI tools.
|
|
362
|
+
|
|
363
|
+
## Groups
|
|
364
|
+
|
|
365
|
+
Each mount can opt into one or more **groups**. The `run()` call's `group` option then selects which mounts are executed.
|
|
366
|
+
|
|
367
|
+
```typescript
|
|
368
|
+
const container = new Container<{ id: string; name: string }>();
|
|
369
|
+
|
|
370
|
+
container.mount('id', { group: ['update', 'delete'] }, isString);
|
|
371
|
+
container.mount('name', { group: ['create', 'update'] }, isString);
|
|
372
|
+
|
|
373
|
+
await container.run({ id: 'x', name: 'foo' }, { group: 'create' });
|
|
374
|
+
// → { name: 'foo' } — `id` is not in the 'create' group
|
|
375
|
+
|
|
376
|
+
await container.run({ id: 'x', name: 'foo' }, { group: '*' });
|
|
377
|
+
// → { id: 'x', name: 'foo' } — wildcard runs everything
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
The wildcard token `'*'` (also exported as `GroupKey.WILDCARD`) bypasses the filter — either as the active group, or to mark a mount as always-run.
|
|
381
|
+
|
|
382
|
+
## Optional Values
|
|
383
|
+
|
|
384
|
+
Mark a mount as `optional` to skip it when the input value is "missing". You decide what counts as missing via `optionalValue`:
|
|
385
|
+
|
|
386
|
+
| `optionalValue` | Treats as optional |
|
|
387
|
+
|---------------------------|-----------------------------------------------|
|
|
388
|
+
| `'undefined'` (default) | only `undefined` |
|
|
389
|
+
| `'null'` | `null` and `undefined` |
|
|
390
|
+
| `'falsy'` | any falsy value (`null`, `undefined`, `''`, `0`, `false`) |
|
|
391
|
+
|
|
392
|
+
```typescript
|
|
393
|
+
import { OptionalValue } from 'validup';
|
|
394
|
+
|
|
395
|
+
container.mount('age',
|
|
396
|
+
{ optional: true, optionalValue: OptionalValue.NULL },
|
|
397
|
+
isNumber,
|
|
398
|
+
);
|
|
399
|
+
|
|
400
|
+
await container.run({ age: null }); // ✅ age is skipped
|
|
401
|
+
await container.run({}); // ✅ age is skipped
|
|
402
|
+
await container.run({ age: 28 }); // ✅ age is validated
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
Set `optionalInclude: true` to copy the optional value through into the output instead of dropping it:
|
|
406
|
+
|
|
407
|
+
```typescript
|
|
408
|
+
container.mount('nickname',
|
|
409
|
+
{ optional: true, optionalInclude: true },
|
|
410
|
+
isString,
|
|
411
|
+
);
|
|
412
|
+
|
|
413
|
+
await container.run({}); // → { nickname: undefined }
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
For cases the `optionalValue` enum can't express (e.g. "drop empty string but keep `0`"), pass `optional` as a predicate. Custom predicates win when present and `optionalValue` is ignored:
|
|
417
|
+
|
|
418
|
+
```typescript
|
|
419
|
+
container.mount('name',
|
|
420
|
+
{ optional: (v) => v === '' || typeof v === 'undefined' },
|
|
421
|
+
isString,
|
|
422
|
+
);
|
|
423
|
+
|
|
424
|
+
await container.run({ name: '', count: 0 }); // ✅ name skipped, count validated
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
## oneOf Branches
|
|
428
|
+
|
|
429
|
+
A container created with `{ oneOf: true }` succeeds if **any one** of its mounts succeeds. Failures are aggregated into a single `IssueGroup` (code `one_of_failed`) only when **all** branches fail, and each branch's contribution is wrapped in its own sub-group so consumers can recover per-branch identity.
|
|
430
|
+
|
|
431
|
+
```typescript
|
|
432
|
+
const credential = new Container({ oneOf: true });
|
|
433
|
+
|
|
434
|
+
credential.mount('email', createEmailValidator());
|
|
435
|
+
credential.mount('username', createUsernameValidator());
|
|
436
|
+
|
|
437
|
+
await credential.run({ email: 'peter@example.com' });
|
|
438
|
+
// → { email: 'peter@example.com' } — username branch failure is ignored
|
|
439
|
+
|
|
440
|
+
await credential.run({ email: 'not-an-email', username: 'invalid' });
|
|
441
|
+
// → throws ValidupError. error.issues is shaped:
|
|
442
|
+
// [
|
|
443
|
+
// {
|
|
444
|
+
// type: 'group', code: 'one_of_failed', path: [],
|
|
445
|
+
// issues: [
|
|
446
|
+
// { type: 'group', path: [], data: { branch: 0, name: 'email' }, issues: [...] },
|
|
447
|
+
// { type: 'group', path: [], data: { branch: 1, name: 'username' }, issues: [...] },
|
|
448
|
+
// ],
|
|
449
|
+
// },
|
|
450
|
+
// ]
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
The per-branch sub-group's `data.branch` is the mount index (in registration order) and `data.name` is the mount path. Use `flattenIssueItems(error.issues)` for a flat list of leaf failures regardless of branch, or walk the sub-groups when you need to report which branch failed and why.
|
|
454
|
+
|
|
455
|
+
## Path Filtering
|
|
456
|
+
|
|
457
|
+
Limit or exclude paths at runtime:
|
|
458
|
+
|
|
459
|
+
```typescript
|
|
460
|
+
await container.run(input, { pathsToInclude: ['name', 'email'] }); // only these
|
|
461
|
+
await container.run(input, { pathsToExclude: ['password'] }); // skip these
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
The same options can be set at the container level via `new Container({ pathsToInclude: [...] })`. Run-time options take precedence.
|
|
465
|
+
|
|
466
|
+
## Defaults
|
|
467
|
+
|
|
468
|
+
Provide fallback values for keys that end up missing or `undefined` after validation:
|
|
469
|
+
|
|
470
|
+
```typescript
|
|
471
|
+
await container.run({}, {
|
|
472
|
+
defaults: { role: 'user', active: true },
|
|
473
|
+
});
|
|
474
|
+
// → { role: 'user', active: true }
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
Dotted keys target nested-container output and are sliced through to the matching child:
|
|
478
|
+
|
|
479
|
+
```typescript
|
|
480
|
+
await parent.run({}, {
|
|
481
|
+
defaults: { 'profile.role': 'user' },
|
|
482
|
+
});
|
|
483
|
+
// → { profile: { role: 'user' } }
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
## Context
|
|
112
487
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
488
|
+
Pass request-scoped data (current user, locale, DB connection, request id) to your validators without going through closures or globals. The `context` flows through every nested container unchanged.
|
|
489
|
+
|
|
490
|
+
```typescript
|
|
491
|
+
type AppContext = { userId: string };
|
|
492
|
+
|
|
493
|
+
const container = new Container<{ slug: string }, AppContext>();
|
|
494
|
+
|
|
495
|
+
container.mount('slug', async (ctx) => {
|
|
496
|
+
// ctx.context is typed as AppContext
|
|
497
|
+
const exists = await db.slugExists(ctx.value, ctx.context.userId);
|
|
498
|
+
if (exists) {
|
|
499
|
+
throw new Error('Slug already taken');
|
|
124
500
|
}
|
|
125
|
-
|
|
501
|
+
return ctx.value;
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
await container.run({ slug: 'my-post' }, { context: { userId: 'u-42' } });
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
The `C` parameter on `Container<T, C>`, `Validator<C>`, and `ValidatorContext<C>` defaults to `unknown`, so existing code without a context type compiles unchanged.
|
|
508
|
+
|
|
509
|
+
## Cancellation
|
|
510
|
+
|
|
511
|
+
Pass an `AbortSignal` to abort a run between mounts. The container checks `signal.aborted` before each mount and rethrows `signal.reason`; the signal is also forwarded into `ValidatorContext.signal` so async validators can cancel their own I/O (e.g. `fetch(url, { signal: ctx.signal })`).
|
|
512
|
+
|
|
513
|
+
```typescript
|
|
514
|
+
const controller = new AbortController();
|
|
515
|
+
setTimeout(() => controller.abort(), 100);
|
|
516
|
+
|
|
517
|
+
try {
|
|
518
|
+
await container.run(input, { signal: controller.signal });
|
|
519
|
+
} catch (e) {
|
|
520
|
+
// AbortError — not a ValidupError
|
|
521
|
+
}
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
`safeRun()` rethrows the abort reason (it is never wrapped into a `Result.failure`) so callers can distinguish "validation failed" from "operation cancelled".
|
|
525
|
+
|
|
526
|
+
## Result Caching
|
|
527
|
+
|
|
528
|
+
`Container.run` (and every other run variant) accepts an optional `cache: ResultCache`. When supplied, validator mounts whose `(ctx.value, ctx.context, ctx.group)` snapshot matches a prior invocation are skipped — their cached outcome is replayed instead of re-running the validator. Particularly valuable for forms with slow async validators (network round-trips, regex-heavy schemas): submit-time validation doesn't pay the cost of re-running mounts whose inputs the per-keystroke runs already proved fresh.
|
|
529
|
+
|
|
530
|
+
```typescript
|
|
531
|
+
import { Container, ResultCache, defineValidator } from 'validup';
|
|
532
|
+
|
|
533
|
+
const container = new Container<{ email: string }>();
|
|
534
|
+
let calls = 0;
|
|
535
|
+
container.mount('email', defineValidator({
|
|
536
|
+
run: async (ctx) => {
|
|
537
|
+
calls += 1;
|
|
538
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
539
|
+
return ctx.value;
|
|
540
|
+
},
|
|
541
|
+
}));
|
|
542
|
+
|
|
543
|
+
const cache = new ResultCache();
|
|
544
|
+
const data = { email: 'peter@example.com' };
|
|
545
|
+
|
|
546
|
+
await container.run(data, { cache });
|
|
547
|
+
await container.run(data, { cache });
|
|
548
|
+
// calls === 1 — the second invocation hits the cache
|
|
549
|
+
```
|
|
550
|
+
|
|
551
|
+
**Opt out per validator** with `sideEffect: true` (via `defineValidator` or an adapter's `{ sideEffect: true }` option) for cross-field validators, network calls, or anything else whose result depends on inputs the snapshot doesn't capture. The cache is caller-owned — `Container` never holds a reference, so the lifecycle (per-request / per-form / persistent) is entirely up to you. Implement `IResultCache` directly for LRU eviction, TTL, etc.
|
|
552
|
+
|
|
553
|
+
See [the Caching guide](https://validup.tada5hi.net/guide/caching) for the full snapshot semantics and lifecycle patterns.
|
|
554
|
+
|
|
555
|
+
## Run Modes
|
|
126
556
|
|
|
127
|
-
|
|
128
|
-
|
|
557
|
+
Four methods — `container.run` / `container.runSync` / `container.safeRun` / `container.safeRunSync` — plus a `parallel` flag on the async ones cover three orthogonal axes: **sync vs async**, **throw vs no-throw `Result`**, and **sequential vs parallel** (async only):
|
|
558
|
+
|
|
559
|
+
| Need | Call | Returns |
|
|
560
|
+
|---------------------------------------------------|-----------------------------------------------|-----------------------|
|
|
561
|
+
| Async, throws on validation failure (default) | `container.run(input, opts)` | `Promise<T>` |
|
|
562
|
+
| Async, throws, parallel mounts | `container.run(input, { parallel: true })` | `Promise<T>` |
|
|
563
|
+
| Async, no-throw `Result` | `container.safeRun(input, opts)` | `Promise<Result<T>>` |
|
|
564
|
+
| Async, no-throw, parallel mounts | `container.safeRun(input, { parallel: true })`| `Promise<Result<T>>` |
|
|
565
|
+
| Sync, throws on validation failure | `container.runSync(input, opts)` | `T` |
|
|
566
|
+
| Sync, no-throw `Result` | `container.safeRunSync(input, opts)` | `Result<T>` |
|
|
567
|
+
|
|
568
|
+
`sync + parallel` is intentionally not a combination — `Promise.allSettled` is async by definition, and sync graphs don't benefit from concurrency.
|
|
569
|
+
|
|
570
|
+
**When `safe*` still throws:** the abort reason from `options.signal`, and the structural `RunSyncViolationError` from `safeRunSync` when a validator returns a Promise or a nested container doesn't implement `runSync`. Both bypass the issue-folding path so callers can distinguish them from validation outcomes.
|
|
571
|
+
|
|
572
|
+
Details on each axis below.
|
|
573
|
+
|
|
574
|
+
### Parallel Execution
|
|
575
|
+
|
|
576
|
+
By default mounts run sequentially in registration order. For containers whose mounts hit independent slow async resources (multiple DB lookups, HTTP calls), opt into parallel mode:
|
|
577
|
+
|
|
578
|
+
```typescript
|
|
579
|
+
await container.run(input, { parallel: true });
|
|
129
580
|
```
|
|
130
581
|
|
|
131
|
-
|
|
132
|
-
The reason for this is, that the id key is not registered for the create group.
|
|
582
|
+
All mounts kick off concurrently and the results merge in registration order — `issues[]` ordering is unchanged. The flag is forwarded into nested containers so the whole tree runs concurrently.
|
|
133
583
|
|
|
134
|
-
|
|
135
|
-
> To always execute a mounted container/validator do not specify
|
|
136
|
-
> any group or use the `*` group.
|
|
584
|
+
**Trade-off**: in parallel mode each mount captures its `value` from the input `data` *before* any sibling mount runs, so a later mount can no longer read an earlier mount's transformed `output[key]`. Stick with sequential mode (the default) for chained-key sanitize-then-validate patterns.
|
|
137
585
|
|
|
586
|
+
### Safe Run
|
|
138
587
|
|
|
139
|
-
|
|
588
|
+
`safeRun()` returns a discriminated `Result<T>` instead of throwing — handy when you want to deal with errors without `try/catch`:
|
|
140
589
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
590
|
+
```typescript
|
|
591
|
+
const result = await container.safeRun(input);
|
|
592
|
+
|
|
593
|
+
if (result.success) {
|
|
594
|
+
console.log(result.data); // T
|
|
595
|
+
} else {
|
|
596
|
+
console.error(result.error.issues); // ValidupError
|
|
597
|
+
}
|
|
598
|
+
```
|
|
599
|
+
|
|
600
|
+
### Sync Fast Path
|
|
601
|
+
|
|
602
|
+
When every mounted validator (and every nested container's `runSync`) is synchronous, use `runSync()` / `safeRunSync()` to skip the per-mount microtask overhead of `await`:
|
|
603
|
+
|
|
604
|
+
```typescript
|
|
605
|
+
const out = container.runSync(input); // returns T directly, not Promise<T>
|
|
144
606
|
```
|
|
145
607
|
|
|
146
|
-
|
|
147
|
-
```ts
|
|
148
|
-
type ValidatorContext = {
|
|
149
|
-
/**
|
|
150
|
-
* The expanded mount path in the current container.
|
|
151
|
-
*/
|
|
152
|
-
key: string,
|
|
608
|
+
`runSync()` throws synchronously if a validator returns a Promise or if a nested container does not implement `runSync` — those are *structural* failures (not validation outcomes), so they're surfaced verbatim and never wrapped into `Result.failure` by `safeRunSync`. Use the async `run()` for any graph that mixes sync and async validators.
|
|
153
609
|
|
|
154
|
-
|
|
155
|
-
* The global mount path of the parent container.
|
|
156
|
-
*/
|
|
157
|
-
path: PropertyKey[],
|
|
610
|
+
## Localized Messages
|
|
158
611
|
|
|
159
|
-
|
|
160
|
-
* The actual value, which should be validated.
|
|
161
|
-
*/
|
|
162
|
-
value: unknown,
|
|
612
|
+
`Issue.message` is rendered eagerly in English at construction time. For i18n / custom locales, every issue also carries a structured `data?: Record<string, unknown>` field (populated by the runtime where the message references a non-trivial value — e.g. `{ name: 'email' }` on the wrapping group at a failing mount). Pair it with `formatIssue` and a `code → template` map to render at the consumer side:
|
|
163
613
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
*/
|
|
167
|
-
data: Record<string, any>,
|
|
614
|
+
```typescript
|
|
615
|
+
import { formatIssue, type IssueMessageTemplates } from 'validup';
|
|
168
616
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
group?: string
|
|
617
|
+
const de: IssueMessageTemplates = {
|
|
618
|
+
value_invalid: 'Feld {name} ist ungültig',
|
|
619
|
+
one_of_failed: 'Keine der Varianten war erfolgreich',
|
|
173
620
|
};
|
|
621
|
+
|
|
622
|
+
for (const issue of error.issues) {
|
|
623
|
+
console.log(formatIssue(issue, de)); // Feld email ist ungültig
|
|
624
|
+
}
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
`formatIssue(issue, templates?, fallback?)`:
|
|
628
|
+
|
|
629
|
+
1. If `templates[issue.code]` exists, returns `interpolate(template, issue.data)` (placeholders use the `{name}` syntax from `@ebec/core`).
|
|
630
|
+
2. Otherwise returns `issue.message`.
|
|
631
|
+
3. Otherwise returns `fallback`.
|
|
632
|
+
|
|
633
|
+
Custom validators that want to participate in this flow should pass `data` through `defineIssueItem`/`defineIssueGroup` so consumer-side templates can reference field-specific values. The default `interpolate` is also re-exported for ad-hoc rendering.
|
|
634
|
+
|
|
635
|
+
## Error Handling
|
|
636
|
+
|
|
637
|
+
### ValidupError
|
|
638
|
+
|
|
639
|
+
```typescript
|
|
640
|
+
import type { BaseError } from '@ebec/core';
|
|
641
|
+
|
|
642
|
+
class ValidupError extends BaseError {
|
|
643
|
+
readonly code: string; // 'VALIDUP_ERROR' (auto-derived from class name)
|
|
644
|
+
readonly issues: Issue[];
|
|
645
|
+
cause?: unknown; // inherited from BaseError
|
|
646
|
+
toJSON(): { name, message, code, cause?, issues };
|
|
647
|
+
}
|
|
648
|
+
```
|
|
649
|
+
|
|
650
|
+
`ValidupError` extends [`@ebec/core`](https://github.com/tada5hi/ebec)'s `BaseError`, so it ships with a `code`, an optional `cause`, and a `toJSON()` for clean transport across HTTP/JSON boundaries. The `message` is auto-built from the failing paths (`Property foo is invalid`, `Properties foo, bar are invalid`).
|
|
651
|
+
|
|
652
|
+
Subclass `ValidupError` (or `BaseError` directly) when you need a domain-specific code — ebec derives it from the class name automatically.
|
|
653
|
+
|
|
654
|
+
Use `isValidupError(err)` to check across package boundaries. It is duck-typed (instanceof OR has a valid `issues` array), so it tolerates the case where two copies of `validup` exist in the dependency tree.
|
|
655
|
+
|
|
656
|
+
```typescript
|
|
657
|
+
import { isValidupError } from 'validup';
|
|
658
|
+
|
|
659
|
+
if (isValidupError(error)) {
|
|
660
|
+
error.issues.forEach((issue) => console.log(issue.path, issue.message));
|
|
661
|
+
}
|
|
662
|
+
```
|
|
663
|
+
|
|
664
|
+
### Issue Shape
|
|
665
|
+
|
|
666
|
+
```typescript
|
|
667
|
+
interface IssueItem {
|
|
668
|
+
type: 'item';
|
|
669
|
+
code: string; // e.g. IssueCode.VALUE_INVALID
|
|
670
|
+
path: PropertyKey[];
|
|
671
|
+
message: string;
|
|
672
|
+
received?: unknown;
|
|
673
|
+
expected?: unknown;
|
|
674
|
+
meta?: Record<string, unknown>;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
interface IssueGroup {
|
|
678
|
+
type: 'group';
|
|
679
|
+
code?: string; // e.g. IssueCode.ONE_OF_FAILED
|
|
680
|
+
path: PropertyKey[];
|
|
681
|
+
message: string;
|
|
682
|
+
issues: Issue[]; // recursive
|
|
683
|
+
meta?: Record<string, unknown>;
|
|
684
|
+
}
|
|
685
|
+
```
|
|
686
|
+
|
|
687
|
+
Use the factories — they set `type` correctly and apply default codes:
|
|
688
|
+
|
|
689
|
+
```typescript
|
|
690
|
+
import { defineIssueItem, defineIssueGroup, IssueCode } from 'validup';
|
|
691
|
+
|
|
692
|
+
const item = defineIssueItem({
|
|
693
|
+
path: ['email'],
|
|
694
|
+
message: 'Invalid email',
|
|
695
|
+
expected: 'string (email)',
|
|
696
|
+
received: 42,
|
|
697
|
+
});
|
|
698
|
+
|
|
699
|
+
const group = defineIssueGroup({
|
|
700
|
+
path: ['address'],
|
|
701
|
+
message: 'address is invalid',
|
|
702
|
+
issues: [item],
|
|
703
|
+
});
|
|
704
|
+
```
|
|
705
|
+
|
|
706
|
+
### Issue Codes
|
|
707
|
+
|
|
708
|
+
validup ships a vocabulary of well-known issue codes that adapter packages (`@validup/zod`, `@validup/validator-js`, …) map onto and that i18n catalogs (`@ilingo/validup`) translate from. The vocabulary tracks the common ground across vuelidate, zod, joi, and yup — enough that a translation catalog can ship one localized string per code instead of a generic "invalid value" fallback.
|
|
709
|
+
|
|
710
|
+
| Theme | Code | When | `data` |
|
|
711
|
+
|-------|------|------|----------|
|
|
712
|
+
| **Generic / structural** | `VALUE_INVALID` | Default for any `defineIssueItem(...)` without a code | — |
|
|
713
|
+
| | `ONE_OF_FAILED` | All branches of a `oneOf` container failed (the wrapping group; per-branch sub-groups carry `{ branch, name }`) | — |
|
|
714
|
+
| **Presence** | `REQUIRED` | Value is missing, `undefined`, `null`, or empty | — |
|
|
715
|
+
| **Type assertions** | `ALPHA` | Value contains characters outside the alphabetical set | — |
|
|
716
|
+
| | `ALPHA_NUM` | Value contains characters outside the alphanumeric set | — |
|
|
717
|
+
| | `NUMERIC` | Value is not a number | — |
|
|
718
|
+
| | `INTEGER` | Value is not an integer | — |
|
|
719
|
+
| | `DECIMAL` | Value is not a decimal number | — |
|
|
720
|
+
| **Length** (strings, arrays) | `MIN_LENGTH` | Value is shorter than the configured minimum | `{ min: number }` |
|
|
721
|
+
| | `MAX_LENGTH` | Value is longer than the configured maximum | `{ max: number }` |
|
|
722
|
+
| **Numeric range** | `MIN_VALUE` | Numeric value is below the configured minimum | `{ min: number }` |
|
|
723
|
+
| | `MAX_VALUE` | Numeric value is above the configured maximum | `{ max: number }` |
|
|
724
|
+
| | `BETWEEN` | Numeric value falls outside `[min, max]` | `{ min: number, max: number }` |
|
|
725
|
+
| **String format** | `EMAIL` | Value is not a valid email address | — |
|
|
726
|
+
| | `URL` | Value is not a valid URL | — |
|
|
727
|
+
| | `IP_ADDRESS` | Value is not a valid IP address | — |
|
|
728
|
+
| | `MAC_ADDRESS` | Value is not a valid MAC address | — |
|
|
729
|
+
| | `UUID` | Value is not a valid UUID | — |
|
|
730
|
+
| | `DATE` | Value is not a valid / parseable date | — |
|
|
731
|
+
| | `PATTERN` | Value does not match the expected regex | `{ pattern: string }` |
|
|
732
|
+
| | `JSON` | Value is not valid JSON | — |
|
|
733
|
+
| | `BASE64` | Value is not valid base64 | — |
|
|
734
|
+
| | `STRONG_PASSWORD` | Value doesn't meet the configured strength rules | `{ minLength?, minLowercase?, minUppercase?, minNumbers?, minSymbols? }` |
|
|
735
|
+
| **Comparison** | `SAME_AS` | Value must equal another named field's value (e.g. password-confirm) | `{ other: string }` |
|
|
736
|
+
|
|
737
|
+
Adapters are responsible for mapping foreign codes onto the vocabulary — e.g. `@validup/zod`'s adapter translates zod's `too_small` (string variant) onto `IssueCode.MIN_LENGTH`. When a foreign code has no direct match, the adapter falls back to `IssueCode.VALUE_INVALID` and the consumer-side template uses the eagerly-rendered English `issue.message`.
|
|
738
|
+
|
|
739
|
+
The `IssueCode` const exposes the runtime values; the matching `IssueCode` *type* (a derived `typeof IssueCode[keyof typeof IssueCode]`) gives autocomplete on `IssueItem.code`. For project-specific codes — `'email_taken'`, `'rate_limited'` — `IssueItem.code` is widened to `IssueCode | (string & {})` so the literal string is accepted without ceremony:
|
|
740
|
+
|
|
741
|
+
```typescript
|
|
742
|
+
defineIssueItem({ code: 'email_taken', path: ['email'], message: '…' });
|
|
743
|
+
// → accepted; downstream code paths treat it like any other code
|
|
744
|
+
```
|
|
745
|
+
|
|
746
|
+
If you want a typed const for your own codes (so `AppCode.EMAIL_TAKEN` autocompletes alongside `AppCode.REQUIRED`), define one alongside the shipped vocabulary:
|
|
747
|
+
|
|
748
|
+
```typescript
|
|
749
|
+
import { IssueCode } from 'validup';
|
|
750
|
+
|
|
751
|
+
export const AppCode = {
|
|
752
|
+
...IssueCode,
|
|
753
|
+
EMAIL_TAKEN: 'email_taken',
|
|
754
|
+
RATE_LIMITED: 'rate_limited',
|
|
755
|
+
} as const;
|
|
756
|
+
|
|
757
|
+
export type AppCode = typeof AppCode[keyof typeof AppCode];
|
|
758
|
+
```
|
|
759
|
+
|
|
760
|
+
## API Reference
|
|
761
|
+
|
|
762
|
+
### Container
|
|
763
|
+
|
|
764
|
+
```typescript
|
|
765
|
+
class Container<
|
|
766
|
+
T extends Record<string, any> = Record<string, any>,
|
|
767
|
+
C = unknown,
|
|
768
|
+
> implements IContainer<T, C> {
|
|
769
|
+
constructor(options?: ContainerOptions<T>);
|
|
770
|
+
|
|
771
|
+
mount(container: IContainer): void;
|
|
772
|
+
mount(options: MountOptions, container: IContainer): void;
|
|
773
|
+
mount(key: Path<T>, data: IContainer | Validator<C>): void;
|
|
774
|
+
mount(key: Path<T>, options: MountOptions, data: IContainer | Validator<C>): void;
|
|
775
|
+
|
|
776
|
+
run(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<T>;
|
|
777
|
+
safeRun(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<Result<T>>;
|
|
778
|
+
|
|
779
|
+
// Sync variants — throw if any validator returns a Promise.
|
|
780
|
+
runSync(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): T;
|
|
781
|
+
safeRunSync(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Result<T>;
|
|
782
|
+
}
|
|
174
783
|
```
|
|
175
784
|
|
|
785
|
+
| Option | Where | Description |
|
|
786
|
+
|---------------------------|------------------------|-------------------------------------------------------------------|
|
|
787
|
+
| `oneOf` | `ContainerOptions` | Succeed when any mount succeeds |
|
|
788
|
+
| `pathsToInclude` | `ContainerOptions`, `ContainerRunOptions` | Only mount paths in this list are executed |
|
|
789
|
+
| `pathsToExclude` | `ContainerOptions`, `ContainerRunOptions` | Mount paths in this list are skipped |
|
|
790
|
+
| `defaults` | `ContainerRunOptions` | Fallback values for missing/`undefined` keys |
|
|
791
|
+
| `context` | `ContainerRunOptions` | Caller-supplied value surfaced on `ValidatorContext.context` |
|
|
792
|
+
| `signal` | `ContainerRunOptions` | `AbortSignal` — checked between mounts and forwarded to `ctx.signal` |
|
|
793
|
+
| `parallel` | `ContainerRunOptions` | Run mounts concurrently (forwarded into nested containers) |
|
|
794
|
+
| `group` | `ContainerRunOptions` | Active group (only matching mounts run; `'*'` runs everything) |
|
|
795
|
+
| `flat` | `ContainerRunOptions` | When `true`, the output is a dotted-key map instead of nested |
|
|
796
|
+
| `path` | `ContainerRunOptions` | Used internally when nesting; rarely set by hand |
|
|
797
|
+
| `group` (mount) | `MountOptions` | Group(s) this mount belongs to (`string \| string[]`) |
|
|
798
|
+
| `optional` | `MountOptions` | Skip this mount when value is "optional" |
|
|
799
|
+
| `optionalValue` | `MountOptions` | What counts as optional: `'undefined'` / `'null'` / `'falsy'` |
|
|
800
|
+
| `optionalInclude` | `MountOptions` | Copy optional value into the output instead of dropping it |
|
|
801
|
+
|
|
802
|
+
### defineSchema
|
|
803
|
+
|
|
804
|
+
```typescript
|
|
805
|
+
function defineSchema<C = unknown>(): IBuilder<{}, C>;
|
|
806
|
+
```
|
|
807
|
+
|
|
808
|
+
See [Builder API](#builder-api-compile-time-typing). Each `.mount(...)` call returns a new builder with the accumulated shape; `.build()` materializes a `Container<T, C>`.
|
|
809
|
+
|
|
810
|
+
### Issue Helpers
|
|
811
|
+
|
|
812
|
+
| Export | Purpose |
|
|
813
|
+
|-----------------------|------------------------------------------------------|
|
|
814
|
+
| `defineIssueItem` | Construct an `IssueItem` (sets `type`, default code) |
|
|
815
|
+
| `defineIssueGroup` | Construct an `IssueGroup` (sets `type`) |
|
|
816
|
+
| `createValidupError` | Build a `ValidupError` carrying one `IssueItem` (sugar for the most common single-issue failure shape). Caller throws. |
|
|
817
|
+
| `IssueCode` | Vocabulary of well-known issue codes (`VALUE_INVALID`, `REQUIRED`, `MIN_LENGTH`, …; full table above) |
|
|
818
|
+
| `GroupKey` | `WILDCARD = '*'` |
|
|
819
|
+
| `OptionalValue` | `UNDEFINED` / `NULL` / `FALSY` |
|
|
820
|
+
|
|
821
|
+
### Validator Composition
|
|
822
|
+
|
|
823
|
+
```typescript
|
|
824
|
+
import { compose, composeOneOf, type ComposeOptions, type ComposeElement } from 'validup';
|
|
825
|
+
|
|
826
|
+
type ComposeElement<C = unknown> = Validator<C> | IContainer<any, any>;
|
|
827
|
+
|
|
828
|
+
function compose<C = unknown>(
|
|
829
|
+
elements: ComposeElement<C>[],
|
|
830
|
+
options?: ComposeOptions,
|
|
831
|
+
): Validator<C>;
|
|
832
|
+
|
|
833
|
+
function composeOneOf<C = unknown>(
|
|
834
|
+
elements: ComposeElement<C>[],
|
|
835
|
+
): Validator<C>;
|
|
836
|
+
```
|
|
837
|
+
|
|
838
|
+
Build a single `Validator` from many. Each element can be a bare `Validator<C>` function OR a fully-built `IContainer<T, C>` instance — the dispatcher picks the right call shape (containers receive the threaded value as their input, validators receive `ctx`). The strategy is picked via `options.oneOf`:
|
|
839
|
+
|
|
840
|
+
- **`oneOf: false`** (default) — every element must pass. Stages thread their return value into the next so sanitize-then-validate patterns work; `options.bail` controls fail-fast (`true`, default) vs. collect-all (`false`).
|
|
841
|
+
- **`oneOf: true`** — branches run as alternatives in registration order; the first one to succeed wins, subsequent branches are not invoked, and the composed validator returns the winning branch's value. When every branch fails, the composed validator throws a `ValidupError` whose first issue is an `IssueGroup` with `code: IssueCode.ONE_OF_FAILED` carrying every branch's failures (each tagged with `data: { branch }`). `bail` is rejected at the type level under this mode — there's no chain to fail-fast over.
|
|
842
|
+
|
|
843
|
+
`composeOneOf([...])` is sugar for `compose([...], { oneOf: true })`.
|
|
844
|
+
|
|
845
|
+
```typescript
|
|
846
|
+
// sanitize-then-validate
|
|
847
|
+
container.mount('email', compose([trim(), isEmail(), isLength({ max: 254 })]));
|
|
848
|
+
|
|
849
|
+
// every broken rule surfaces in one pass
|
|
850
|
+
container.mount('password', compose([
|
|
851
|
+
isLength({ min: 8 }),
|
|
852
|
+
isAlphanumeric(),
|
|
853
|
+
matches(/[0-9]/),
|
|
854
|
+
], { bail: false }));
|
|
855
|
+
|
|
856
|
+
// accept either an email or a phone number on the same field
|
|
857
|
+
container.mount('contact', composeOneOf([isEmail(), isMobilePhone()]));
|
|
858
|
+
|
|
859
|
+
// any-of with a container branch — accept a string-formatted contact
|
|
860
|
+
// OR a nested address object validated by its own container.
|
|
861
|
+
container.mount('contact', composeOneOf([
|
|
862
|
+
isEmail(),
|
|
863
|
+
isMobilePhone(),
|
|
864
|
+
addressContainer,
|
|
865
|
+
]));
|
|
866
|
+
```
|
|
867
|
+
|
|
868
|
+
Threading notes:
|
|
869
|
+
- A stage that returns `undefined` is treated as a pass-through — the upstream value continues down the chain. Validators that DO want to explicitly clear the field must throw or return a sentinel.
|
|
870
|
+
- Container elements receive `ctx.value` as their `input` (normalised to `{}` for non-object values, matching how a nested container mounted directly handles a non-object mount value). Their `path` / `group` / `context` / `signal` flow from the threaded `ctx`, so issues from a container branch carry absolute paths from the outer mount (`composeOneOf` mounted at `foo` with a child schema's `street` field surfaces issues at `['foo', 'street']`).
|
|
871
|
+
|
|
872
|
+
### Type Guards
|
|
873
|
+
|
|
874
|
+
| Export | Returns |
|
|
875
|
+
|-----------------------|------------------------------------------------------|
|
|
876
|
+
| `isValidupError(e)` | `e is ValidupError` (duck-typed across package copies) |
|
|
877
|
+
| `isError(e)` | `e is Error & {[key: string]: any}` |
|
|
878
|
+
| `isContainer(x)` | `x is IContainer` (duck-typed) |
|
|
879
|
+
| `isIssue(x)` | `x is Issue` |
|
|
880
|
+
| `isIssueItem(x)` | `x is IssueItem` |
|
|
881
|
+
| `isIssueGroup(x)` | `x is IssueGroup` |
|
|
882
|
+
|
|
883
|
+
## Integrations
|
|
884
|
+
|
|
885
|
+
Use one of the official integration packages to bridge an existing validator library, framework, or UI runtime into validup:
|
|
886
|
+
|
|
887
|
+
| Package | Connects |
|
|
888
|
+
|--------------------------------------------------------------------------------------|--------------------------------------------------------------------------------|
|
|
889
|
+
| [`@validup/standard-schema`](https://npmjs.com/package/@validup/standard-schema) | Any [Standard Schema](https://standardschema.dev) library — zod 3.24+, valibot, arktype, effect-schema, … |
|
|
890
|
+
| [`@validup/zod`](https://npmjs.com/package/@validup/zod) | [zod](https://zod.dev) schemas (vendor-specific issue mapping with `expected` / `received`) |
|
|
891
|
+
| [`@validup/validator-js`](https://npmjs.com/package/@validup/validator-js) | [validator.js](https://github.com/validatorjs/validator.js) string validators — pre-baked factories per common rule, plus a generic `createValidator(fn, {...})` for the long tail |
|
|
892
|
+
| [`@validup/vue`](https://npmjs.com/package/@validup/vue) | [Vue 3](https://vuejs.org) composable for reactive client-side form state |
|
|
893
|
+
|
|
894
|
+
## Stability
|
|
895
|
+
|
|
896
|
+
What's covered by semver:
|
|
897
|
+
|
|
898
|
+
- **Public exports** — everything re-exported from `validup`'s entry barrel (`Container`, `defineSchema`, `ValidupError`, `Issue` / factories / guards, `IssueCode`, `GroupKey`, `OptionalValue`, helpers in `formatIssue` / `flattenIssue*`).
|
|
899
|
+
- **`Container` runtime contract** — `run` / `runSync` / `runParallel` (via `parallel: true`) / `safeRun` / `safeRunSync`, including their throw-contracts as documented on `IContainer` (`safeRun` throws only on abort).
|
|
900
|
+
- **`Issue` and `ValidupError` shape** — the discriminated union (`type: 'item' | 'group'`), `data`, `meta`, `code` widening to `IssueCode | (string & {})`.
|
|
901
|
+
- **Mount API** — variadic `mount(...)` argument forms listed in [Mounting](#mounting).
|
|
902
|
+
- **`oneOf` aggregation shape** — `IssueCode.ONE_OF_FAILED` group wrapping per-branch sub-groups (see [oneOf Branches](#oneof-branches)).
|
|
903
|
+
|
|
904
|
+
Extension points:
|
|
905
|
+
|
|
906
|
+
- **`IssueCode` widening** — `IssueItem.code` accepts any `string & {}` so consumers can use project-specific codes without ceremony. Define your own const that spreads `IssueCode` for typed autocomplete on your codes (see [Issue Codes](#issue-codes)).
|
|
907
|
+
- **`Validator<C, Out>`** — `C` (context) and `Out` (return type) generics participate in builder inference; defaults stay `unknown`.
|
|
908
|
+
- **`IContainer`** — opt-in interface; integration packages can implement it to be mountable as a nested container.
|
|
909
|
+
- **`isContainer` / `isValidupError`** — duck-typed guards that tolerate package duplicates and cross-realm throws. Prefer these over `instanceof` at boundaries.
|
|
910
|
+
|
|
911
|
+
Internal (no semver guarantee):
|
|
912
|
+
|
|
913
|
+
- Anything not re-exported from `src/index.ts`, including private helpers (`recordMountError`, `finalizeOutput`, etc.) and the `RunSyncViolationError` class.
|
|
914
|
+
- Default English `Issue.message` strings — re-render via `formatIssue` and a `code → template` map if you depend on specific wording.
|
|
915
|
+
|
|
916
|
+
Deprecation policy: a removal lands in at least one minor release as a deprecation (JSDoc `@deprecated` + console warning where feasible) before the next major drops it.
|
|
917
|
+
|
|
176
918
|
## License
|
|
177
919
|
|
|
178
920
|
Made with 💚
|
|
179
921
|
|
|
180
|
-
Published under [
|
|
922
|
+
Published under [Apache 2.0 License](./LICENSE).
|
|
923
|
+
|
|
924
|
+
[npm-version-src]: https://badge.fury.io/js/validup.svg
|
|
925
|
+
[npm-version-href]: https://npmjs.com/package/validup
|
|
926
|
+
[workflow-src]: https://github.com/tada5hi/validup/actions/workflows/main.yml/badge.svg
|
|
927
|
+
[workflow-href]: https://github.com/tada5hi/validup/actions/workflows/main.yml
|
|
928
|
+
[codeql-src]: https://github.com/tada5hi/validup/actions/workflows/codeql.yml/badge.svg
|
|
929
|
+
[codeql-href]: https://github.com/tada5hi/validup/actions/workflows/codeql.yml
|
|
930
|
+
[snyk-src]: https://snyk.io/test/github/tada5hi/validup/badge.svg
|
|
931
|
+
[snyk-href]: https://snyk.io/test/github/tada5hi/validup
|
|
932
|
+
[conventional-src]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white
|
|
933
|
+
[conventional-href]: https://conventionalcommits.org
|