@railway-ts/pipelines 0.1.29 → 0.2.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.
@@ -1,1265 +0,0 @@
1
- import { Result } from '../result/index.cjs';
2
-
3
- /**
4
- * Represents a validation error with path information and a message.
5
- */
6
- type ValidationError = {
7
- path: string[];
8
- message: string;
9
- };
10
- /**
11
- * A synchronous validator function that checks if a value meets certain criteria.
12
- *
13
- * @param value - The value to validate
14
- * @param path - The path to the current value (used for nested objects)
15
- * @returns A Result containing either the validated value or validation errors
16
- */
17
- type Validator<I, O = I> = (value: I, path?: string[]) => Result<O, ValidationError[]>;
18
- /**
19
- * An asynchronous validator function that always returns a Promise.
20
- *
21
- * @param value - The value to validate
22
- * @param path - The path to the current value (used for nested objects)
23
- * @returns A Promise resolving to a Result
24
- */
25
- type AsyncValidator<I, O = I> = (value: I, path?: string[]) => Promise<Result<O, ValidationError[]>>;
26
- /**
27
- * A validator function that may return either a synchronous Result or a Promise.
28
- * Use this type when a validator accepts both sync and async validators
29
- * (e.g., in `object()` schemas that mix sync and async field validators).
30
- *
31
- * @param value - The value to validate
32
- * @param path - The path to the current value (used for nested objects)
33
- * @returns A Result or Promise of Result
34
- */
35
- type MaybeAsyncValidator<I, O = I> = (value: I, path?: string[]) => Result<O, ValidationError[]> | Promise<Result<O, ValidationError[]>>;
36
- /**
37
- * Extracts the union of output types from a validator map.
38
- * Used by {@link discriminatedUnion} to infer the output type from the map's validators.
39
- */
40
- type ValidatorMapOutput<M extends Record<string, MaybeAsyncValidator<unknown, unknown>>> = {
41
- [K in keyof M]: M[K] extends MaybeAsyncValidator<unknown, infer O> ? O : never;
42
- }[keyof M];
43
- type AtomicType = string | number | boolean | Date | null | undefined | bigint;
44
- type RemoveUndefined<T> = T extends undefined ? never : T;
45
- type ProcessType<T> = T extends AtomicType ? T : T extends readonly [unknown, ...unknown[]] ? {
46
- [K in keyof T]: ProcessType<T[K]>;
47
- } : T extends [unknown, ...unknown[]] ? {
48
- [K in keyof T]: ProcessType<T[K]>;
49
- } : T extends Array<infer U> ? Array<ProcessType<U>> : T extends object ? {
50
- [K in keyof T as undefined extends T[K] ? never : K]: ProcessType<T[K]>;
51
- } & {
52
- [K in keyof T as undefined extends T[K] ? K : never]?: ProcessType<RemoveUndefined<T[K]>>;
53
- } extends infer O ? {
54
- [K in keyof O]: O[K];
55
- } : never : T;
56
- type InferType<V> = V extends Validator<unknown, infer O> ? O : V extends AsyncValidator<unknown, infer O> ? O : V extends MaybeAsyncValidator<unknown, infer O> ? O : never;
57
- /**
58
- * Infer the output type of a validator or schema after processing.
59
- * Useful for getting the TypeScript type that a validator will produce.
60
- */
61
- type InferSchemaType<V> = ProcessType<InferType<V>>;
62
- /**
63
- * A validation schema where each key maps to a synchronous validator for that field.
64
- */
65
- type SyncSchema<T = Record<string, unknown>> = {
66
- [K in keyof T]: Validator<unknown, T[K]>;
67
- };
68
- /**
69
- * A validation schema that accepts both sync and async validators.
70
- * Use {@link SyncSchema} when all validators are synchronous to preserve sync return types.
71
- */
72
- type Schema<T = Record<string, unknown>> = {
73
- [K in keyof T]: MaybeAsyncValidator<unknown, T[K]>;
74
- };
75
- /**
76
- * The result of a validation operation.
77
- */
78
- type ValidationResult<T> = {
79
- valid: true;
80
- data: T;
81
- } | {
82
- valid: false;
83
- errors: Record<string, string>;
84
- };
85
- /**
86
- * Create a validator for objects based on a schema.
87
- *
88
- * @example
89
- * const userSchema = object({
90
- * name: required(string()),
91
- * age: required(chain(parseNumber(), min(18))),
92
- * });
93
- * userSchema({ name: 'John', age: 25 }); // ok({ name: "John", age: 25 })
94
- *
95
- * @param schema - An object where each key contains a validator for that property
96
- * @param options - Options object. `strict` (default true) rejects extra properties
97
- * @returns A validator that validates objects against the schema
98
- */
99
- declare function object<T extends Record<string, unknown>>(schema: SyncSchema<T>, options?: {
100
- strict?: boolean;
101
- }): Validator<unknown, T>;
102
- declare function object<T extends Record<string, unknown>>(schema: Schema<T>, options?: {
103
- strict?: boolean;
104
- }): MaybeAsyncValidator<unknown, T>;
105
- /**
106
- * Create a validator that requires a value to be defined (not null or undefined).
107
- *
108
- * @example
109
- * const validate = required(string());
110
- * validate('hello'); // ok("hello")
111
- * validate(undefined); // err([{ path: [], message: 'Field is required' }])
112
- *
113
- * @param validator - The validator to apply if the value is defined
114
- * @param message - Error message when value is null or undefined
115
- * @returns A validator that checks the value is defined
116
- */
117
- declare function required<I, O>(validator: Validator<I, O>, message?: string): Validator<I | undefined | null, O>;
118
- declare function required<I, O>(validator: MaybeAsyncValidator<I, O>, message?: string): MaybeAsyncValidator<I | undefined | null, O>;
119
- /**
120
- * Create a validator that makes a field optional.
121
- * Returns undefined for null/undefined values, otherwise applies the validator.
122
- *
123
- * @example
124
- * const validate = optional(string());
125
- * validate(undefined); // ok(undefined)
126
- * validate('hello'); // ok("hello")
127
- *
128
- * @param validator - The validator to apply if the value is defined
129
- * @returns A validator that allows undefined values
130
- */
131
- declare function optional<I, O>(validator: Validator<I, O>): Validator<I | undefined | null, O | undefined>;
132
- declare function optional<I, O>(validator: MaybeAsyncValidator<I, O>): MaybeAsyncValidator<I | undefined | null, O | undefined>;
133
- /**
134
- * Create a validator that only accepts null values.
135
- *
136
- * @example
137
- * const validate = nullable();
138
- * validate(null); // ok(null)
139
- * validate('some value'); // err([{ path: [], message: 'Must be null' }])
140
- *
141
- * @param message - Custom error message
142
- * @returns A validator that ensures the value is exactly null
143
- */
144
- declare function nullable(message?: string): Validator<unknown, null>;
145
- /**
146
- * Create a validator that treats empty strings, empty arrays, and empty objects as optional.
147
- *
148
- * @example
149
- * const schema = object({
150
- * bio: emptyAsOptional(chain(string(), maxLength(500))),
151
- * });
152
- * schema({ bio: '' }); // ok({ bio: undefined })
153
- * schema({ bio: 'Hello' }); // ok({ bio: "Hello" })
154
- *
155
- * @param validator - The validator to apply if the value is not empty
156
- * @returns A validator that treats empty values as undefined
157
- */
158
- declare function emptyAsOptional<I, O>(validator: Validator<I, O>): Validator<I | undefined | null, O | undefined>;
159
- declare function emptyAsOptional<I, O>(validator: MaybeAsyncValidator<I, O>): MaybeAsyncValidator<I | undefined | null, O | undefined>;
160
- /**
161
- * Create a validator that checks if a value exactly matches the expected literal.
162
- *
163
- * @example
164
- * const validate = literal('active');
165
- * validate('active'); // ok("active")
166
- * validate('completed'); // err([{ path: [], message: "Value must be 'active'" }])
167
- *
168
- * @param expectedValue - The exact value that should be matched
169
- * @param message - Custom error message
170
- * @returns A validator that checks if the value matches the literal
171
- */
172
- declare function literal<T>(expectedValue: T, message?: string): Validator<unknown, T>;
173
-
174
- /**
175
- * Options for controlling validation behavior.
176
- */
177
- type ValidateOptions = {
178
- abortEarly?: boolean;
179
- };
180
- /**
181
- * The key used in formatted error objects for root-level validation errors (i.e. errors with an empty path).
182
- */
183
- declare const ROOT_ERROR_KEY = "_root";
184
- /**
185
- * Combine multiple validators into a single validator, applying them in sequence.
186
- * Each validator's output feeds into the next. Short-circuits on first error.
187
- */
188
- declare function chain<A, B>(v1: Validator<A, B>): Validator<A, B>;
189
- declare function chain<A, B, C>(v1: Validator<A, B>, v2: Validator<B, C>): Validator<A, C>;
190
- declare function chain<A, B, C, D>(v1: Validator<A, B>, v2: Validator<B, C>, v3: Validator<C, D>): Validator<A, D>;
191
- declare function chain<A, B, C, D, E>(v1: Validator<A, B>, v2: Validator<B, C>, v3: Validator<C, D>, v4: Validator<D, E>): Validator<A, E>;
192
- declare function chain<A, B, C, D, E, F>(v1: Validator<A, B>, v2: Validator<B, C>, v3: Validator<C, D>, v4: Validator<D, E>, v5: Validator<E, F>): Validator<A, F>;
193
- declare function chain<A, B, C, D, E, F, G>(v1: Validator<A, B>, v2: Validator<B, C>, v3: Validator<C, D>, v4: Validator<D, E>, v5: Validator<E, F>, v6: Validator<F, G>): Validator<A, G>;
194
- declare function chain<A, B, C, D, E, F, G, H>(v1: Validator<A, B>, v2: Validator<B, C>, v3: Validator<C, D>, v4: Validator<D, E>, v5: Validator<E, F>, v6: Validator<F, G>, v7: Validator<G, H>): Validator<A, H>;
195
- declare function chain<A, B, C, D, E, F, G, H, I>(v1: Validator<A, B>, v2: Validator<B, C>, v3: Validator<C, D>, v4: Validator<D, E>, v5: Validator<E, F>, v6: Validator<F, G>, v7: Validator<G, H>, v8: Validator<H, I>): Validator<A, I>;
196
- declare function chain<A, B, C, D, E, F, G, H, I, J>(v1: Validator<A, B>, v2: Validator<B, C>, v3: Validator<C, D>, v4: Validator<D, E>, v5: Validator<E, F>, v6: Validator<F, G>, v7: Validator<G, H>, v8: Validator<H, I>, v9: Validator<I, J>): Validator<A, J>;
197
- declare function chain<A, B, C, D, E, F, G, H, I, J, K>(v1: Validator<A, B>, v2: Validator<B, C>, v3: Validator<C, D>, v4: Validator<D, E>, v5: Validator<E, F>, v6: Validator<F, G>, v7: Validator<G, H>, v8: Validator<H, I>, v9: Validator<I, J>, v10: Validator<J, K>): Validator<A, K>;
198
- /**
199
- * Combine multiple validators (sync or async) into a single async validator.
200
- * Each validator's output feeds into the next. Short-circuits on first error.
201
- * This is the async counterpart of {@link chain}.
202
- *
203
- * @example
204
- * const validate = chainAsync(
205
- * string(),
206
- * email(),
207
- * refineAsync(async (e) => !(await db.users.exists({ email: e })), 'Taken')
208
- * );
209
- * const result = await validate('new@example.com'); // ok("new@example.com")
210
- *
211
- * @param validators - A list of sync or async validators to compose
212
- * @returns A combined async validator that applies all validators in sequence
213
- */
214
- declare function chainAsync<A, B>(v1: MaybeAsyncValidator<A, B>): AsyncValidator<A, B>;
215
- declare function chainAsync<A, B, C>(v1: MaybeAsyncValidator<A, B>, v2: MaybeAsyncValidator<B, C>): AsyncValidator<A, C>;
216
- declare function chainAsync<A, B, C, D>(v1: MaybeAsyncValidator<A, B>, v2: MaybeAsyncValidator<B, C>, v3: MaybeAsyncValidator<C, D>): AsyncValidator<A, D>;
217
- declare function chainAsync<A, B, C, D, E>(v1: MaybeAsyncValidator<A, B>, v2: MaybeAsyncValidator<B, C>, v3: MaybeAsyncValidator<C, D>, v4: MaybeAsyncValidator<D, E>): AsyncValidator<A, E>;
218
- declare function chainAsync<A, B, C, D, E, F>(v1: MaybeAsyncValidator<A, B>, v2: MaybeAsyncValidator<B, C>, v3: MaybeAsyncValidator<C, D>, v4: MaybeAsyncValidator<D, E>, v5: MaybeAsyncValidator<E, F>): AsyncValidator<A, F>;
219
- declare function chainAsync<A, B, C, D, E, F, G>(v1: MaybeAsyncValidator<A, B>, v2: MaybeAsyncValidator<B, C>, v3: MaybeAsyncValidator<C, D>, v4: MaybeAsyncValidator<D, E>, v5: MaybeAsyncValidator<E, F>, v6: MaybeAsyncValidator<F, G>): AsyncValidator<A, G>;
220
- declare function chainAsync<A, B, C, D, E, F, G, H>(v1: MaybeAsyncValidator<A, B>, v2: MaybeAsyncValidator<B, C>, v3: MaybeAsyncValidator<C, D>, v4: MaybeAsyncValidator<D, E>, v5: MaybeAsyncValidator<E, F>, v6: MaybeAsyncValidator<F, G>, v7: MaybeAsyncValidator<G, H>): AsyncValidator<A, H>;
221
- declare function chainAsync<A, B, C, D, E, F, G, H, I>(v1: MaybeAsyncValidator<A, B>, v2: MaybeAsyncValidator<B, C>, v3: MaybeAsyncValidator<C, D>, v4: MaybeAsyncValidator<D, E>, v5: MaybeAsyncValidator<E, F>, v6: MaybeAsyncValidator<F, G>, v7: MaybeAsyncValidator<G, H>, v8: MaybeAsyncValidator<H, I>): AsyncValidator<A, I>;
222
- declare function chainAsync<A, B, C, D, E, F, G, H, I, J>(v1: MaybeAsyncValidator<A, B>, v2: MaybeAsyncValidator<B, C>, v3: MaybeAsyncValidator<C, D>, v4: MaybeAsyncValidator<D, E>, v5: MaybeAsyncValidator<E, F>, v6: MaybeAsyncValidator<F, G>, v7: MaybeAsyncValidator<G, H>, v8: MaybeAsyncValidator<H, I>, v9: MaybeAsyncValidator<I, J>): AsyncValidator<A, J>;
223
- declare function chainAsync<A, B, C, D, E, F, G, H, I, J, K>(v1: MaybeAsyncValidator<A, B>, v2: MaybeAsyncValidator<B, C>, v3: MaybeAsyncValidator<C, D>, v4: MaybeAsyncValidator<D, E>, v5: MaybeAsyncValidator<E, F>, v6: MaybeAsyncValidator<F, G>, v7: MaybeAsyncValidator<G, H>, v8: MaybeAsyncValidator<H, I>, v9: MaybeAsyncValidator<I, J>, v10: MaybeAsyncValidator<J, K>): AsyncValidator<A, K>;
224
- /**
225
- * Validate a value against a validator.
226
- *
227
- * @example
228
- * const result = validate(10, chain(number(), min(5)));
229
- * // ok(10)
230
- *
231
- * @example
232
- * // With abortEarly option — stops on first error
233
- * const result = validate(input, userSchema, { abortEarly: true });
234
- *
235
- * @param value - The value to validate
236
- * @param validator - The validator to apply
237
- * @param pathOrOptions - Optional base path for error reporting, or options object
238
- * @param maybeOptions - Options object when path is also provided
239
- * @returns A Result containing either the validated value or validation errors
240
- */
241
- declare function validate<T>(value: unknown, validator: Validator<unknown, T>): Result<T, ValidationError[]>;
242
- declare function validate<T>(value: unknown, validator: Validator<unknown, T>, path: string[]): Result<T, ValidationError[]>;
243
- declare function validate<T>(value: unknown, validator: Validator<unknown, T>, options: ValidateOptions): Result<T, ValidationError[]>;
244
- declare function validate<T>(value: unknown, validator: Validator<unknown, T>, path: string[], options: ValidateOptions): Result<T, ValidationError[]>;
245
- declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
246
- declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, path: string[]): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
247
- declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, options: ValidateOptions): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
248
- declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, path: string[], options: ValidateOptions): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
249
- /**
250
- * Check whether a value satisfies a validator, returning a boolean.
251
- * Always short-circuits on first error for maximum performance.
252
- *
253
- * @example
254
- * is('hello', string()); // true
255
- * is(42, string()); // false
256
- * is(input, asyncValidator()); // Promise<boolean>
257
- *
258
- * @param value - The value to check
259
- * @param validator - The validator to apply
260
- * @returns `true` if valid, `false` otherwise (or a Promise for async validators)
261
- */
262
- declare function is(value: unknown, validator: Validator<unknown, unknown>): boolean;
263
- declare function is(value: unknown, validator: MaybeAsyncValidator<unknown, unknown>): boolean | Promise<boolean>;
264
- /**
265
- * Format validation errors into a user-friendly object.
266
- * Converts array paths to dot/bracket notation strings.
267
- *
268
- * @example
269
- * formatErrors([
270
- * { path: ['name'], message: 'Required' },
271
- * { path: ['items', '1'], message: 'Must be a number' },
272
- * ]);
273
- * // { name: 'Required', 'items[1]': 'Must be a number' }
274
- *
275
- * @param errors - The array of validation errors to format
276
- * @returns An object mapping paths to error messages
277
- */
278
- declare function formatErrors(errors: ValidationError[]): Record<string, string>;
279
- /**
280
- * Validate input and return a formatted ValidationResult in one call.
281
- * Combines validate() + formatErrors() + match() into a single operation.
282
- *
283
- * @example
284
- * const result = validateAndFormatResult(input, userSchema);
285
- * // { valid: true, data: { email: "user@example.com", age: 25 } }
286
- * // or { valid: false, errors: { email: "Invalid email", age: "Must be at least 18" } }
287
- *
288
- * @param input - The untrusted input to validate
289
- * @param schema - The validator/schema to validate against
290
- * @returns An object with either `{ valid: true, data }` or `{ valid: false, errors }`
291
- */
292
- declare function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>, options?: ValidateOptions): ValidationResult<T>;
293
- declare function validateAndFormatResult<T>(input: unknown, schema: MaybeAsyncValidator<unknown, T>, options?: ValidateOptions): ValidationResult<T> | Promise<ValidationResult<T>>;
294
- /**
295
- * Create a validator that transforms a value during validation.
296
- * The transformer function must be pure and not throw exceptions.
297
- *
298
- * @example
299
- * const normalize = chain(string(), email(), transform(s => s.toLowerCase()));
300
- * normalize('User@Example.COM'); // ok("user@example.com")
301
- *
302
- * @param transformer - A pure function that transforms the input value
303
- * @returns A validator that applies the transformation
304
- */
305
- declare function transform<I, O>(transformer: (value: I) => O): Validator<I, O>;
306
- /**
307
- * Create a validator that refines a value with a custom predicate.
308
- *
309
- * @example
310
- * const isEven = refine<number>(n => n % 2 === 0, 'Must be even');
311
- * isEven(4); // ok(4)
312
- * isEven(3); // err([{ path: [], message: 'Must be even' }])
313
- *
314
- * @param predicate - A function that returns true if the value is valid
315
- * @param message - The error message if validation fails
316
- * @returns A validator that checks the predicate
317
- */
318
- declare function refine<T>(predicate: (value: T) => boolean, message?: string): Validator<T, T>;
319
- /**
320
- * Create an async validator that refines a value with an asynchronous predicate.
321
- * This is the async counterpart of {@link refine}.
322
- *
323
- * @example
324
- * const unique = refineAsync<string>(
325
- * async (name) => !(await db.users.exists({ name })),
326
- * 'Already taken'
327
- * );
328
- *
329
- * @param predicate - An async function returning true if the value is valid
330
- * @param message - The error message if validation fails
331
- * @returns An async validator that checks the predicate
332
- */
333
- declare function refineAsync<T>(predicate: (value: T) => Promise<boolean>, message?: string): AsyncValidator<T, T>;
334
- /**
335
- * Create a validator that targets a specific field path with cross-field validation.
336
- * Unlike `refine`, receives the entire parent object and attaches errors to a specific field.
337
- *
338
- * @example
339
- * const validate = chain(
340
- * object({ password: required(string()), confirm: required(string()) }),
341
- * refineAt('confirm', (d) => d.password === d.confirm, 'Passwords must match')
342
- * );
343
- *
344
- * @param targetPath - The field path where the error should be attached
345
- * @param predicate - Validation function that receives the entire parent object
346
- * @param message - Error message when validation fails
347
- * @returns A validator for cross-field validation
348
- *
349
- * @see refine - For single-field validation without cross-field dependencies
350
- */
351
- declare function refineAt<T>(targetPath: string | string[], predicate: (value: T) => boolean, message: string): Validator<T, T>;
352
- /**
353
- * Create an async validator that targets a specific field path with cross-field validation.
354
- * This is the async counterpart of {@link refineAt}.
355
- *
356
- * @example
357
- * const validate = chainAsync(
358
- * object({ username: required(string()), email: required(email()) }),
359
- * refineAtAsync(
360
- * 'username',
361
- * async (d) => !(await db.users.exists({ username: d.username })),
362
- * 'Username taken'
363
- * )
364
- * );
365
- *
366
- * @param targetPath - The field path where the error should be attached
367
- * @param predicate - An async function that receives the entire parent object
368
- * @param message - Error message when validation fails
369
- * @returns An async validator for cross-field validation
370
- *
371
- * @see refineAt - For synchronous cross-field validation
372
- */
373
- declare function refineAtAsync<T>(targetPath: string | string[], predicate: (value: T) => Promise<boolean>, message: string): AsyncValidator<T, T>;
374
- /**
375
- * Create a conditional validator that applies different validators based on a predicate.
376
- * When the predicate returns true, `thenValidator` is applied.
377
- * When false, `elseValidator` is applied (if provided), otherwise the value passes through.
378
- *
379
- * @example
380
- * const validate = when<FormData>(
381
- * (data) => data.contactMethod === 'email',
382
- * refineAt('email', (d) => d.email.includes('@'), 'Valid email required'),
383
- * refineAt('phone', (d) => d.phone.length > 0, 'Phone required'),
384
- * );
385
- *
386
- * @param predicate - A function that determines which validator to apply
387
- * @param thenValidator - Validator applied when predicate returns true
388
- * @param elseValidator - Optional validator applied when predicate returns false
389
- * @returns A validator that conditionally applies validation
390
- */
391
- declare function when<T>(predicate: (data: T) => boolean, thenValidator: Validator<T, T>, elseValidator?: Validator<T, T>): Validator<T, T>;
392
- /**
393
- * Create a conditional async validator that applies different validators based on a predicate.
394
- * This is the async counterpart of {@link when}.
395
- *
396
- * @example
397
- * const validate = whenAsync<FormData>(
398
- * (data) => data.requiresVerification,
399
- * refineAtAsync('code', async (d) => await verifyCode(d.code), 'Invalid code'),
400
- * );
401
- *
402
- * @param predicate - A function that determines which validator to apply
403
- * @param thenValidator - Validator applied when predicate returns true
404
- * @param elseValidator - Optional validator applied when predicate returns false
405
- * @returns An async validator that conditionally applies validation
406
- */
407
- declare function whenAsync<T>(predicate: (data: T) => boolean, thenValidator: MaybeAsyncValidator<T, T>, elseValidator?: MaybeAsyncValidator<T, T>): AsyncValidator<T, T>;
408
-
409
- /**
410
- * Create a validator for arrays where each item is validated by the provided validator.
411
- *
412
- * @example
413
- * const validate = array(string());
414
- * validate(['a', 'b']); // ok(["a", "b"])
415
- * validate('not array'); // err([{ path: [], message: 'Expected an array' }])
416
- *
417
- * @param itemValidator - The validator to apply to each array item
418
- * @returns A validator that validates arrays of items
419
- */
420
- declare function array<I, O>(itemValidator: Validator<I, O>): Validator<unknown, O[]>;
421
- declare function array<I, O>(itemValidator: MaybeAsyncValidator<I, O>): MaybeAsyncValidator<unknown, O[]>;
422
- /**
423
- * Validate that an array has at least a minimum number of items.
424
- *
425
- * @example
426
- * const validate = minItems(2);
427
- * validate([1, 2, 3]); // ok([1, 2, 3])
428
- * validate([1]); // err([{ path: [], message: 'Array must have at least 2 items' }])
429
- *
430
- * @param min - The minimum number of items required
431
- * @param message - Custom error message
432
- * @returns A validator that checks minimum array length
433
- */
434
- declare function minItems<T>(min: number, message?: string): Validator<T[], T[]>;
435
- /**
436
- * Validate that an array has at most a maximum number of items.
437
- *
438
- * @example
439
- * const validate = maxItems(2);
440
- * validate([1, 2]); // ok([1, 2])
441
- * validate([1, 2, 3]); // err([{ path: [], message: 'Array must have at most 2 items' }])
442
- *
443
- * @param max - The maximum number of items allowed
444
- * @param message - Custom error message
445
- * @returns A validator that checks maximum array length
446
- */
447
- declare function maxItems<T>(max: number, message?: string): Validator<T[], T[]>;
448
- /**
449
- * Validate that an array is not empty.
450
- *
451
- * @example
452
- * const validate = notEmpty();
453
- * validate([1]); // ok([1])
454
- * validate([]); // err([{ path: [], message: 'Array must not be empty' }])
455
- *
456
- * @param message - Custom error message
457
- * @returns A validator that checks the array is not empty
458
- */
459
- declare function notEmpty<T>(message?: string): Validator<T[], T[]>;
460
- /**
461
- * Validate that an array contains only unique values.
462
- *
463
- * @example
464
- * const validate = unique();
465
- * validate([1, 2, 3]); // ok([1, 2, 3])
466
- * validate([1, 2, 2, 3]); // err([{ path: ['2'], message: 'Array must contain unique values' }])
467
- *
468
- * @example
469
- * // With custom key extractor for objects
470
- * const validate = unique<{ id: number }>('Duplicate ID', (item) => item.id);
471
- *
472
- * @param message - Custom error message
473
- * @param keyExtractor - Optional function to extract a comparison key from each item
474
- * @returns A validator that checks for unique array values
475
- */
476
- declare function unique<T>(message?: string, keyExtractor?: (item: T) => unknown): Validator<T[], T[]>;
477
- /**
478
- * Create a validator that ensures a value is one of the allowed values.
479
- *
480
- * @example
481
- * const validate = oneOf(['pending', 'approved', 'rejected']);
482
- * validate('approved'); // ok("approved")
483
- * validate('unknown'); // err([{ path: [], message: 'Value must be one of: pending, approved, rejected' }])
484
- *
485
- * @param allowedValues - Array of acceptable values
486
- * @param message - Custom error message
487
- * @returns A validator that checks if a value is in the allowed list
488
- */
489
- declare function oneOf<T>(allowedValues: T[], message?: string): Validator<T>;
490
- /**
491
- * Create a validator that ensures a value is a string and one of the allowed enum values.
492
- *
493
- * @example
494
- * const validate = stringEnum(['admin', 'user']);
495
- * validate('admin'); // ok("admin")
496
- * validate(42); // err([{ path: [], message: 'Value must be a string' }])
497
- * validate('other'); // err([{ path: [], message: 'Value must be one of: admin, user' }])
498
- *
499
- * @param allowedValues - Array of acceptable string enum values
500
- * @param message - Custom error message
501
- * @returns A validator that checks if a value is a string and in the allowed list
502
- */
503
- declare function stringEnum<T extends string>(allowedValues: T[], message?: string): Validator<unknown, T>;
504
-
505
- /**
506
- * Validate a heterogeneous tuple where each position has its own validator.
507
- *
508
- * @example
509
- * const validate = tuple([string(), number(), boolean()]);
510
- * validate(['a', 1, true]); // ok(["a", 1, true])
511
- * validate(['a', 1]); // err([{ path: [], message: 'Expected tuple of length 3, got 2' }])
512
- *
513
- * @param validators - Array of validators, one for each tuple position
514
- * @returns A validator that ensures the input is a tuple matching the validator array
515
- */
516
- declare function tuple<V extends ReadonlyArray<Validator<unknown, unknown>>>(validators: V): Validator<unknown, TupleType<V>>;
517
- declare function tuple<V extends ReadonlyArray<MaybeAsyncValidator<unknown, unknown>>>(validators: V): MaybeAsyncValidator<unknown, TupleType<V>>;
518
- /**
519
- * Validate a homogeneous tuple where all elements share the same type and fixed length.
520
- *
521
- * @example
522
- * const point3D = tupleOf(number(), 3); // [number, number, number]
523
- * point3D([1, 2, 3]); // ok([1, 2, 3])
524
- * point3D([1, 2]); // err([{ path: [], message: 'Expected tuple of length 3, got 2' }])
525
- *
526
- * @param elementValidator - Validator to apply to each element
527
- * @param length - Fixed length of the tuple
528
- * @returns A validator that ensures the input is a tuple of the specified length
529
- */
530
- declare function tupleOf<T>(elementValidator: Validator<unknown, T>, length: 1): Validator<unknown, [T]>;
531
- declare function tupleOf<T>(elementValidator: MaybeAsyncValidator<unknown, T>, length: 1): MaybeAsyncValidator<unknown, [T]>;
532
- declare function tupleOf<T>(elementValidator: Validator<unknown, T>, length: 2): Validator<unknown, [T, T]>;
533
- declare function tupleOf<T>(elementValidator: MaybeAsyncValidator<unknown, T>, length: 2): MaybeAsyncValidator<unknown, [T, T]>;
534
- declare function tupleOf<T>(elementValidator: Validator<unknown, T>, length: 3): Validator<unknown, [T, T, T]>;
535
- declare function tupleOf<T>(elementValidator: MaybeAsyncValidator<unknown, T>, length: 3): MaybeAsyncValidator<unknown, [T, T, T]>;
536
- declare function tupleOf<T>(elementValidator: Validator<unknown, T>, length: 4): Validator<unknown, [T, T, T, T]>;
537
- declare function tupleOf<T>(elementValidator: MaybeAsyncValidator<unknown, T>, length: 4): MaybeAsyncValidator<unknown, [T, T, T, T]>;
538
- declare function tupleOf<T>(elementValidator: Validator<unknown, T>, length: 5): Validator<unknown, [T, T, T, T, T]>;
539
- declare function tupleOf<T>(elementValidator: MaybeAsyncValidator<unknown, T>, length: 5): MaybeAsyncValidator<unknown, [T, T, T, T, T]>;
540
- declare function tupleOf<T>(elementValidator: Validator<unknown, T>, length: 6): Validator<unknown, [T, T, T, T, T, T]>;
541
- declare function tupleOf<T>(elementValidator: MaybeAsyncValidator<unknown, T>, length: 6): MaybeAsyncValidator<unknown, [T, T, T, T, T, T]>;
542
- declare function tupleOf<T>(elementValidator: Validator<unknown, T>, length: 7): Validator<unknown, [T, T, T, T, T, T, T]>;
543
- declare function tupleOf<T>(elementValidator: MaybeAsyncValidator<unknown, T>, length: 7): MaybeAsyncValidator<unknown, [T, T, T, T, T, T, T]>;
544
- declare function tupleOf<T>(elementValidator: Validator<unknown, T>, length: 8): Validator<unknown, [T, T, T, T, T, T, T, T]>;
545
- declare function tupleOf<T>(elementValidator: MaybeAsyncValidator<unknown, T>, length: 8): MaybeAsyncValidator<unknown, [T, T, T, T, T, T, T, T]>;
546
- declare function tupleOf<T>(elementValidator: Validator<unknown, T>, length: 9): Validator<unknown, [T, T, T, T, T, T, T, T, T]>;
547
- declare function tupleOf<T>(elementValidator: MaybeAsyncValidator<unknown, T>, length: 9): MaybeAsyncValidator<unknown, [T, T, T, T, T, T, T, T, T]>;
548
- declare function tupleOf<T>(elementValidator: Validator<unknown, T>, length: 10): Validator<unknown, [T, T, T, T, T, T, T, T, T, T]>;
549
- declare function tupleOf<T>(elementValidator: MaybeAsyncValidator<unknown, T>, length: 10): MaybeAsyncValidator<unknown, [T, T, T, T, T, T, T, T, T, T]>;
550
- declare function tupleOf<T>(elementValidator: Validator<unknown, T>, length: number): Validator<unknown, T[]>;
551
- declare function tupleOf<T>(elementValidator: MaybeAsyncValidator<unknown, T>, length: number): MaybeAsyncValidator<unknown, T[]>;
552
-
553
- /**
554
- * Create a validator that ensures a value is a number and not NaN.
555
- *
556
- * @example
557
- * const validate = number();
558
- * validate(25); // ok(25)
559
- * validate('not a number'); // err([{ path: [], message: 'Must be a number' }])
560
- *
561
- * @param message - Custom error message
562
- * @returns A validator that checks if a value is a number
563
- */
564
- declare function number(message?: string): Validator<unknown, number>;
565
- /**
566
- * Create a validator that ensures a number is at least a minimum value.
567
- *
568
- * @example
569
- * const validate = min(18);
570
- * validate(21); // ok(21)
571
- * validate(16); // err([{ path: [], message: 'Must be at least 18' }])
572
- *
573
- * @param value - The minimum value (inclusive)
574
- * @param message - Custom error message
575
- * @returns A validator that checks if a number is at least the minimum
576
- */
577
- declare function min(value: number, message?: string): Validator<number>;
578
- /**
579
- * Create a validator that ensures a number is at most a maximum value.
580
- *
581
- * @example
582
- * const validate = max(100);
583
- * validate(75); // ok(75)
584
- * validate(150); // err([{ path: [], message: 'Must be at most 100' }])
585
- *
586
- * @param value - The maximum value (inclusive)
587
- * @param message - Custom error message
588
- * @returns A validator that checks if a number is at most the maximum
589
- */
590
- declare function max(value: number, message?: string): Validator<number>;
591
- /**
592
- * Create a validator that ensures a number is between a minimum and maximum (inclusive).
593
- *
594
- * @example
595
- * const validate = between(1, 10);
596
- * validate(7); // ok(7)
597
- * validate(15); // err([{ path: [], message: 'Must be between 1 and 10' }])
598
- *
599
- * @param min - The minimum value (inclusive)
600
- * @param max - The maximum value (inclusive)
601
- * @param message - Custom error message
602
- * @returns A validator that checks if a number is between min and max
603
- */
604
- declare function between(min: number, max: number, message?: string): Validator<number>;
605
- /**
606
- * Create a validator that ensures a number is an integer.
607
- *
608
- * @example
609
- * const validate = integer();
610
- * validate(42); // ok(42)
611
- * validate(3.14); // err([{ path: [], message: 'Must be an integer' }])
612
- *
613
- * @param message - Custom error message
614
- * @returns A validator that checks if a number is an integer
615
- */
616
- declare function integer(message?: string): Validator<number>;
617
- /**
618
- * Create a validator that ensures a number is positive (greater than zero).
619
- *
620
- * @example
621
- * const validate = positive();
622
- * validate(29.99); // ok(29.99)
623
- * validate(0); // err([{ path: [], message: 'Must be a positive number' }])
624
- *
625
- * @param message - Custom error message
626
- * @returns A validator that checks if a number is positive
627
- */
628
- declare function positive(message?: string): Validator<number>;
629
- /**
630
- * Create a validator that ensures a number is negative (less than zero).
631
- *
632
- * @example
633
- * const validate = negative();
634
- * validate(-5); // ok(-5)
635
- * validate(0); // err([{ path: [], message: 'Must be a negative number' }])
636
- *
637
- * @param message - Custom error message
638
- * @returns A validator that checks if a number is negative
639
- */
640
- declare function negative(message?: string): Validator<number>;
641
- /**
642
- * Create a validator that ensures a number is not zero.
643
- *
644
- * @example
645
- * const validate = nonZero();
646
- * validate(5); // ok(5)
647
- * validate(0); // err([{ path: [], message: 'Must not be zero' }])
648
- *
649
- * @param message - Custom error message
650
- * @returns A validator that checks if a number is not zero
651
- */
652
- declare function nonZero(message?: string): Validator<number>;
653
- /**
654
- * Create a validator that ensures a number is divisible by a specific divisor.
655
- *
656
- * @example
657
- * const validate = divisibleBy(5);
658
- * validate(15); // ok(15)
659
- * validate(12); // err([{ path: [], message: 'Must be divisible by 5' }])
660
- *
661
- * @param divisor - The number that the input must be divisible by
662
- * @param message - Custom error message
663
- * @returns A validator that checks if a number is divisible by the divisor
664
- */
665
- declare function divisibleBy(divisor: number, message?: string): Validator<number>;
666
- /**
667
- * Create a validator that ensures a number has at most the specified decimal places.
668
- *
669
- * @example
670
- * const validate = precision(2);
671
- * validate(10.99); // ok(10.99)
672
- * validate(10.999); // err([{ path: [], message: 'Must have at most 2 decimal places' }])
673
- *
674
- * @param maxDecimalPlaces - The maximum number of decimal places allowed
675
- * @param message - Custom error message
676
- * @returns A validator that checks the number's decimal precision
677
- */
678
- declare function precision(maxDecimalPlaces: number, message?: string): Validator<number>;
679
- /**
680
- * Create a validator that ensures a number is finite (not Infinity or -Infinity).
681
- *
682
- * @example
683
- * const validate = finite();
684
- * validate(42); // ok(42)
685
- * validate(Infinity); // err([{ path: [], message: 'Must be a finite number' }])
686
- *
687
- * @param message - Custom error message
688
- * @returns A validator that checks if a number is finite
689
- */
690
- declare function finite(message?: string): Validator<number>;
691
-
692
- /**
693
- * Create a validator that ensures a value is a string.
694
- *
695
- * @example
696
- * const validate = string();
697
- * validate('John'); // ok("John")
698
- * validate(42); // err([{ path: [], message: 'Must be a string' }])
699
- *
700
- * @param message - Custom error message
701
- * @returns A validator that checks if a value is a string
702
- */
703
- declare function string(message?: string): Validator<unknown, string>;
704
- /**
705
- * Create a validator that ensures a string's length is at least a minimum value.
706
- *
707
- * @example
708
- * const validate = minLength(3);
709
- * validate('john_doe'); // ok("john_doe")
710
- * validate('jo'); // err([{ path: [], message: 'Must be at least 3 characters' }])
711
- *
712
- * @param min - The minimum length (inclusive)
713
- * @param message - Custom error message
714
- * @returns A validator that checks if a string meets the minimum length
715
- */
716
- declare function minLength(min: number, message?: string): Validator<string>;
717
- /**
718
- * Create a validator that ensures a string's length is at most a maximum value.
719
- *
720
- * @example
721
- * const validate = maxLength(10);
722
- * validate('short'); // ok("short")
723
- * validate('this is too long!!!'); // err([{ path: [], message: 'Must be at most 10 characters' }])
724
- *
725
- * @param max - The maximum length (inclusive)
726
- * @param message - Custom error message
727
- * @returns A validator that checks if a string meets the maximum length
728
- */
729
- declare function maxLength(max: number, message?: string): Validator<string>;
730
- /**
731
- * Create a validator that ensures a string matches a regular expression pattern.
732
- *
733
- * @example
734
- * const validate = pattern(/^[a-zA-Z0-9]+$/);
735
- * validate('abc123'); // ok("abc123")
736
- * validate('abc!'); // err([{ path: [], message: 'Invalid format' }])
737
- *
738
- * @param regex - The regular expression to test against
739
- * @param message - Custom error message
740
- * @returns A validator that checks if a string matches the pattern
741
- */
742
- declare function pattern(regex: RegExp, message?: string): Validator<string>;
743
- /**
744
- * Create a validator that ensures a string is not empty after trimming whitespace.
745
- *
746
- * @example
747
- * const validate = nonEmpty();
748
- * validate('John'); // ok("John")
749
- * validate(''); // err([{ path: [], message: 'Field must not be empty' }])
750
- * validate(' '); // err([{ path: [], message: 'Field must not be empty' }])
751
- *
752
- * @param message - Custom error message
753
- * @returns A validator that checks if a string is not empty
754
- */
755
- declare function nonEmpty(message?: string): Validator<string>;
756
- /**
757
- * Create a validator that ensures a string is a valid email address.
758
- *
759
- * @example
760
- * const validate = email();
761
- * validate('user@example.com'); // ok("user@example.com")
762
- * validate('not-an-email'); // err([{ path: [], message: 'Invalid email format' }])
763
- *
764
- * @param message - Custom error message
765
- * @returns A validator that checks if a string is a valid email
766
- */
767
- declare function email(message?: string): Validator<string>;
768
- /**
769
- * Create a validator that ensures a string is a valid URL.
770
- *
771
- * @example
772
- * const validate = url();
773
- * validate('https://example.com'); // ok("https://example.com")
774
- * validate('not-a-url'); // err([{ path: [], message: 'Invalid URL format' }])
775
- *
776
- * @param message - Custom error message
777
- * @returns A validator that checks if a string is a valid URL
778
- */
779
- declare function url(message?: string): Validator<string>;
780
- /**
781
- * Create a validator that ensures a string is a valid phone number.
782
- * Accepts common formats including international (+), spaces, dashes, and parentheses.
783
- *
784
- * @example
785
- * const validate = phoneNumber();
786
- * validate('+1-555-123-4567'); // ok("+1-555-123-4567")
787
- * validate('not-a-phone'); // err([{ path: [], message: 'Invalid phone number format' }])
788
- *
789
- * @param message - Custom error message
790
- * @returns A validator that checks if a string is a valid phone number
791
- */
792
- declare function phoneNumber(message?: string): Validator<string>;
793
- /**
794
- * Create a validator that ensures a string is a valid UUID (RFC 4122).
795
- * Accepts any UUID version including NIL UUIDs (all zeros).
796
- *
797
- * @example
798
- * const validate = uuid();
799
- * validate('550e8400-e29b-41d4-a716-446655440000'); // ok(...)
800
- * validate('not-a-uuid'); // err([{ path: [], message: 'Invalid UUID format' }])
801
- *
802
- * @param message - Custom error message
803
- * @returns A validator that checks if a string is a valid UUID
804
- */
805
- declare function uuid(message?: string): Validator<string>;
806
- /**
807
- * Create a validator that ensures a string is a valid ISO 8601 date (YYYY-MM-DD).
808
- * Validates both format and calendar correctness (e.g., rejects Feb 30).
809
- *
810
- * @example
811
- * const validate = isoDate();
812
- * validate('2024-01-15'); // ok("2024-01-15")
813
- * validate('2024-02-30'); // err([{ path: [], message: 'Invalid ISO date format' }])
814
- *
815
- * @param message - Custom error message
816
- * @returns A validator that checks if a string is a valid ISO date
817
- */
818
- declare function isoDate(message?: string): Validator<string>;
819
- /**
820
- * Create a validator that ensures a string is a valid ISO 8601 / RFC 3339 time.
821
- * Format: `HH:mm:ss[.fractional][Z|±HH:mm]`. Timezone is optional.
822
- *
823
- * @example
824
- * const validate = isoTime();
825
- * validate('14:30:00'); // ok("14:30:00")
826
- * validate('14:30:00Z'); // ok("14:30:00Z")
827
- * validate('14:30:00+05:30'); // ok("14:30:00+05:30")
828
- * validate('25:00:00'); // err([{ path: [], message: 'Invalid ISO time format' }])
829
- *
830
- * @param message - Custom error message
831
- * @returns A validator that checks if a string is a valid ISO time
832
- */
833
- declare function isoTime(message?: string): Validator<string>;
834
- /**
835
- * Create a validator that ensures a string is a valid ISO 8601 / RFC 3339 datetime.
836
- * Format: `YYYY-MM-DDTHH:mm:ss[.fractional][Z|±HH:mm]`.
837
- *
838
- * @example
839
- * const validate = isoDateTime();
840
- * validate('2024-01-15T14:30:00Z'); // ok(...)
841
- * validate('2024-01-15T14:30:00+05:30'); // ok(...)
842
- * validate('2024-02-30T14:30:00Z'); // err([{ path: [], message: 'Invalid ISO datetime format' }])
843
- *
844
- * @param message - Custom error message
845
- * @returns A validator that checks if a string is a valid ISO datetime
846
- */
847
- declare function isoDateTime(message?: string): Validator<string>;
848
- /**
849
- * Create a validator that ensures a string is a valid ISO 8601 duration.
850
- * Format: `PnYnMnDTnHnMnS` or `PnW`.
851
- *
852
- * @example
853
- * const validate = isoDuration();
854
- * validate('P1Y2M3D'); // ok("P1Y2M3D")
855
- * validate('PT1H30M'); // ok("PT1H30M")
856
- * validate('P4W'); // ok("P4W")
857
- * validate('P'); // err([{ path: [], message: 'Invalid ISO duration format' }])
858
- *
859
- * @param message - Custom error message
860
- * @returns A validator that checks if a string is a valid ISO duration
861
- */
862
- declare function isoDuration(message?: string): Validator<string>;
863
-
864
- /**
865
- * Create a validator that parses input into a number.
866
- * Accepts both numbers and string representations of numbers.
867
- *
868
- * @example
869
- * const validate = parseNumber();
870
- * validate('25'); // ok(25)
871
- * validate(42); // ok(42)
872
- * validate('not a number'); // err([{ path: [], message: 'Must be a valid number' }])
873
- *
874
- * @param message - Custom error message
875
- * @returns A validator that parses and validates numbers
876
- */
877
- declare function parseNumber(message?: string): Validator<unknown, number>;
878
- /**
879
- * Create a validator that parses input into a BigInt.
880
- * Accepts BigInt values, strings, and integer numbers.
881
- *
882
- * @example
883
- * const validate = parseBigInt();
884
- * validate("9007199254740993"); // ok(9007199254740993n)
885
- * validate(123n); // ok(123n)
886
- * validate(42); // ok(42n)
887
- *
888
- * @param message - Custom error message
889
- * @returns A validator that parses and validates BigInt values
890
- */
891
- declare function parseBigInt(message?: string): Validator<unknown, bigint>;
892
- /**
893
- * Create a validator that parses input into enum values.
894
- * Handles string/number to enum conversions with flexible matching.
895
- *
896
- * @example
897
- * enum Status { Pending = "PENDING", Approved = "APPROVED" }
898
- * const validate = parseEnum(Status);
899
- * validate("PENDING"); // ok("PENDING")
900
- * validate("pending"); // ok("PENDING") — case-insensitive key match
901
- *
902
- * @param enumObject - The enum object to parse values into
903
- * @param message - Custom error message
904
- * @returns A validator that parses to enum values
905
- */
906
- declare function parseEnum<T extends Record<string, string | number>>(enumObject: T, message?: string): Validator<unknown, T[keyof T]>;
907
- /**
908
- * Create a validator that parses input into a Date object.
909
- * Accepts Date objects, date strings, and numeric timestamps.
910
- *
911
- * @example
912
- * const validate = parseDate();
913
- * validate('1990-05-15'); // ok(Date)
914
- * validate(1621036800000); // ok(Date)
915
- * validate('not a date'); // err([{ path: [], message: 'Must be a valid date' }])
916
- *
917
- * @param message - Custom error message
918
- * @returns A validator that parses and validates dates
919
- */
920
- declare function parseDate(message?: string): Validator<unknown, Date>;
921
- /**
922
- * Create a validator that parses input into a boolean.
923
- * Accepts booleans, 0/1, and strings like 'true'/'false', 'yes'/'no'.
924
- *
925
- * @example
926
- * const validate = parseBool();
927
- * validate('yes'); // ok(true)
928
- * validate('false'); // ok(false)
929
- * validate(1); // ok(true)
930
- * validate('maybe'); // err([{ path: [], message: 'Must be a valid boolean value' }])
931
- *
932
- * @param message - Custom error message
933
- * @returns A validator that parses and validates booleans
934
- */
935
- declare function parseBool(message?: string): Validator<unknown, boolean>;
936
- /**
937
- * Create a validator that parses input into a string.
938
- * Accepts strings and any value convertible to string, except null and undefined.
939
- *
940
- * @example
941
- * const validate = parseString();
942
- * validate(12345); // ok("12345")
943
- * validate('hello'); // ok("hello")
944
- * validate(null); // err([{ path: [], message: 'Must be convertible to string' }])
945
- *
946
- * @param message - Custom error message
947
- * @returns A validator that parses and validates strings
948
- */
949
- declare function parseString(message?: string): Validator<unknown, string>;
950
- /**
951
- * Create a validator that parses JSON strings into objects.
952
- * Accepts JSON strings or already-parsed objects.
953
- *
954
- * @example
955
- * const validate = parseJSON();
956
- * validate('{"name":"John"}'); // ok({ name: "John" })
957
- * validate({ name: 'John' }); // ok({ name: "John" })
958
- * validate('{invalid}'); // err([{ path: [], message: 'Must be valid JSON' }])
959
- *
960
- * @param message - Custom error message
961
- * @returns A validator that parses and validates JSON
962
- */
963
- declare function parseJSON(message?: string): Validator<unknown, unknown>;
964
- /**
965
- * Create a validator that parses ISO date strings (YYYY-MM-DD) into Date objects.
966
- * Performs strict validation of the date format and validity.
967
- *
968
- * @example
969
- * const validate = parseISODate();
970
- * validate('2021-05-15'); // ok(Date)
971
- * validate('15/05/2021'); // err([{ path: [], message: 'Must be a valid ISO date string' }])
972
- * validate('2021-02-30'); // err(...) — invalid calendar date
973
- *
974
- * @param message - Custom error message
975
- * @returns A validator that parses and validates ISO date strings
976
- */
977
- declare function parseISODate(message?: string): Validator<unknown, Date>;
978
- /**
979
- * Create a validator that parses string URLs into URL objects.
980
- *
981
- * @example
982
- * const validate = parseURL();
983
- * validate('https://example.com'); // ok(URL)
984
- * validate('not-a-url'); // err([{ path: [], message: 'Must be a valid URL' }])
985
- *
986
- * @param message - Custom error message
987
- * @returns A validator that parses and validates URLs
988
- */
989
- declare function parseURL(message?: string): Validator<unknown, URL>;
990
-
991
- /**
992
- * Create a validator that ensures a value is a valid Date object.
993
- *
994
- * @example
995
- * const validate = date();
996
- * validate(new Date()); // ok(Date)
997
- * validate('not a date'); // err([{ path: [], message: 'Must be a Date object' }])
998
- *
999
- * @param message - Custom error message
1000
- * @returns A validator that checks if value is a valid Date
1001
- */
1002
- declare function date(message?: string): Validator<unknown, Date>;
1003
- /**
1004
- * Create a validator that ensures a Date is within a specified range.
1005
- *
1006
- * @example
1007
- * const validate = dateRange(new Date('2023-01-01'), new Date('2023-12-31'));
1008
- * validate(new Date('2023-06-15')); // ok(Date)
1009
- * validate(new Date('2024-01-01')); // err(...)
1010
- *
1011
- * @param min - The minimum valid date (inclusive)
1012
- * @param max - The maximum valid date (inclusive)
1013
- * @param message - Custom error message
1014
- * @returns A validator that checks if a date is between min and max
1015
- */
1016
- declare function dateRange(min: Date, max: Date, message?: string): Validator<Date>;
1017
- /**
1018
- * Create a validator that ensures a Date is in the past.
1019
- *
1020
- * @example
1021
- * const validate = pastDate();
1022
- * validate(new Date('1990-01-01')); // ok(Date)
1023
- *
1024
- * @param message - Custom error message
1025
- * @returns A validator that checks if a date is in the past
1026
- */
1027
- declare function pastDate(message?: string): Validator<Date>;
1028
- /**
1029
- * Create a validator that ensures a Date is in the future.
1030
- *
1031
- * @example
1032
- * const validate = futureDate();
1033
- * const nextYear = new Date();
1034
- * nextYear.setFullYear(nextYear.getFullYear() + 1);
1035
- * validate(nextYear); // ok(Date)
1036
- *
1037
- * @param message - Custom error message
1038
- * @returns A validator that checks if a date is in the future
1039
- */
1040
- declare function futureDate(message?: string): Validator<Date>;
1041
- /**
1042
- * Create a validator that ensures a Date is today or in the future.
1043
- * Uses calendar date comparison (ignoring time portions).
1044
- *
1045
- * @example
1046
- * const validate = todayOrFuture();
1047
- * validate(new Date()); // ok(Date)
1048
- *
1049
- * @param message - Custom error message
1050
- * @returns A validator that checks if a date is today or in the future
1051
- */
1052
- declare function todayOrFuture(message?: string): Validator<Date>;
1053
-
1054
- /**
1055
- * Create a validator that ensures a value is a boolean.
1056
- *
1057
- * @example
1058
- * const validate = boolean();
1059
- * validate(true); // ok(true)
1060
- * validate('not a boolean'); // err([{ path: [], message: 'Must be a boolean' }])
1061
- *
1062
- * @param message - Custom error message
1063
- * @returns A validator that checks if a value is a boolean
1064
- */
1065
- declare function boolean(message?: string): Validator<unknown, boolean>;
1066
- /**
1067
- * Create a validator that ensures a boolean matches the expected value.
1068
- *
1069
- * @example
1070
- * const validate = matches(true);
1071
- * validate(true); // ok(true)
1072
- * validate(false); // err([{ path: [], message: 'Value must be true' }])
1073
- *
1074
- * @param expected - The expected boolean value
1075
- * @param message - Custom error message
1076
- * @returns A validator that confirms the value matches the expected boolean
1077
- */
1078
- declare function matches(expected: boolean, message?: string): Validator<boolean>;
1079
-
1080
- /**
1081
- * Create a validator that checks if a value matches any of the provided validators.
1082
- * Returns the result of the first successful validator, or all errors if none match.
1083
- *
1084
- * @example
1085
- * const validate = union([string(), number()]);
1086
- * validate('hello'); // ok("hello")
1087
- * validate(42); // ok(42)
1088
- * validate(true); // err([...all errors...])
1089
- *
1090
- * @param validators - Array of validators to try in order
1091
- * @param options - Configuration options
1092
- * @returns A validator that succeeds if any of the provided validators succeed
1093
- */
1094
- declare function union<I>(validators: [], options?: {
1095
- collectAllErrors?: boolean;
1096
- errorPrefix?: string;
1097
- }): Validator<I, never>;
1098
- declare function union<I, O1>(validators: [Validator<I, O1>], options?: {
1099
- collectAllErrors?: boolean;
1100
- errorPrefix?: string;
1101
- }): Validator<I, O1>;
1102
- declare function union<I, O1>(validators: [MaybeAsyncValidator<I, O1>], options?: {
1103
- collectAllErrors?: boolean;
1104
- errorPrefix?: string;
1105
- }): MaybeAsyncValidator<I, O1>;
1106
- declare function union<I, O1, O2>(validators: [Validator<I, O1>, Validator<I, O2>], options?: {
1107
- collectAllErrors?: boolean;
1108
- errorPrefix?: string;
1109
- }): Validator<I, O1 | O2>;
1110
- declare function union<I, O1, O2>(validators: [MaybeAsyncValidator<I, O1>, MaybeAsyncValidator<I, O2>], options?: {
1111
- collectAllErrors?: boolean;
1112
- errorPrefix?: string;
1113
- }): MaybeAsyncValidator<I, O1 | O2>;
1114
- declare function union<I, O1, O2, O3>(validators: [Validator<I, O1>, Validator<I, O2>, Validator<I, O3>], options?: {
1115
- collectAllErrors?: boolean;
1116
- errorPrefix?: string;
1117
- }): Validator<I, O1 | O2 | O3>;
1118
- declare function union<I, O1, O2, O3>(validators: [MaybeAsyncValidator<I, O1>, MaybeAsyncValidator<I, O2>, MaybeAsyncValidator<I, O3>], options?: {
1119
- collectAllErrors?: boolean;
1120
- errorPrefix?: string;
1121
- }): MaybeAsyncValidator<I, O1 | O2 | O3>;
1122
- declare function union<I, O1, O2, O3, O4>(validators: [Validator<I, O1>, Validator<I, O2>, Validator<I, O3>, Validator<I, O4>], options?: {
1123
- collectAllErrors?: boolean;
1124
- errorPrefix?: string;
1125
- }): Validator<I, O1 | O2 | O3 | O4>;
1126
- declare function union<I, O1, O2, O3, O4>(validators: [
1127
- MaybeAsyncValidator<I, O1>,
1128
- MaybeAsyncValidator<I, O2>,
1129
- MaybeAsyncValidator<I, O3>,
1130
- MaybeAsyncValidator<I, O4>
1131
- ], options?: {
1132
- collectAllErrors?: boolean;
1133
- errorPrefix?: string;
1134
- }): MaybeAsyncValidator<I, O1 | O2 | O3 | O4>;
1135
- declare function union<I, O1, O2, O3, O4, O5>(validators: [Validator<I, O1>, Validator<I, O2>, Validator<I, O3>, Validator<I, O4>, Validator<I, O5>], options?: {
1136
- collectAllErrors?: boolean;
1137
- errorPrefix?: string;
1138
- }): Validator<I, O1 | O2 | O3 | O4 | O5>;
1139
- declare function union<I, O1, O2, O3, O4, O5>(validators: [
1140
- MaybeAsyncValidator<I, O1>,
1141
- MaybeAsyncValidator<I, O2>,
1142
- MaybeAsyncValidator<I, O3>,
1143
- MaybeAsyncValidator<I, O4>,
1144
- MaybeAsyncValidator<I, O5>
1145
- ], options?: {
1146
- collectAllErrors?: boolean;
1147
- errorPrefix?: string;
1148
- }): MaybeAsyncValidator<I, O1 | O2 | O3 | O4 | O5>;
1149
- declare function union<I, O>(validators: Array<Validator<I, O>>, options?: {
1150
- collectAllErrors?: boolean;
1151
- errorPrefix?: string;
1152
- }): Validator<I, O>;
1153
- declare function union<I, O>(validators: Array<MaybeAsyncValidator<I, O>>, options?: {
1154
- collectAllErrors?: boolean;
1155
- errorPrefix?: string;
1156
- }): MaybeAsyncValidator<I, O>;
1157
- /**
1158
- * Create a discriminated union validator that selects the validator based on
1159
- * a discriminant field's value.
1160
- *
1161
- * @example
1162
- * const validate = discriminatedUnion('type', {
1163
- * text: object({ type: required(literal('text')), content: required(string()) }),
1164
- * image: object({ type: required(literal('image')), url: required(string()) }),
1165
- * });
1166
- * validate({ type: 'text', content: 'hello' }); // ok(...)
1167
- * validate({ type: 'unknown' }); // err(...)
1168
- *
1169
- * @param discriminantField - The name of the field to use as discriminant
1170
- * @param validatorMap - Map of discriminant values to validators
1171
- * @param fallbackMessage - Message when the discriminant value is not found
1172
- * @returns A validator that selects the appropriate schema based on the discriminant
1173
- */
1174
- declare function discriminatedUnion<const M extends Record<string, Validator<unknown, unknown>>>(discriminantField: string, validatorMap: M, fallbackMessage?: string): Validator<unknown, ValidatorMapOutput<M>>;
1175
- declare function discriminatedUnion<const M extends Record<string, MaybeAsyncValidator<unknown, unknown>>>(discriminantField: string, validatorMap: M, fallbackMessage?: string): MaybeAsyncValidator<unknown, ValidatorMapOutput<M>>;
1176
-
1177
- /**
1178
- * Create a validator for TypeScript enum values.
1179
- * Works with both string and numeric enums.
1180
- *
1181
- * @example
1182
- * enum Status { Pending = "PENDING", Approved = "APPROVED" }
1183
- * const validate = enumValue(Status);
1184
- * validate("PENDING"); // ok("PENDING")
1185
- * validate("INVALID"); // err([{ path: [], message: 'Value must be one of: PENDING, APPROVED' }])
1186
- *
1187
- * @example
1188
- * // With excluded values
1189
- * const validate = enumValue(Status, "Not allowed", [Status.Pending]);
1190
- * validate("PENDING"); // err(...)
1191
- *
1192
- * @param enumObject - The enum object to validate against
1193
- * @param message - Custom error message
1194
- * @param excludedValues - Values to exclude from the valid set
1195
- * @returns A validator that ensures the value is a valid enum value
1196
- */
1197
- declare function enumValue<T extends Record<string, string | number>>(enumObject: T, message?: string, excludedValues?: T[keyof T][]): Validator<unknown, T[keyof T]>;
1198
-
1199
- /**
1200
- * Create a validator that ensures a value is a bigint.
1201
- *
1202
- * @example
1203
- * const validate = bigint();
1204
- * validate(9007199254740993n); // ok(9007199254740993n)
1205
- * validate(123); // err([{ path: [], message: 'Must be a bigint' }])
1206
- *
1207
- * @param message - Custom error message
1208
- * @returns A validator that checks if the value is a bigint
1209
- */
1210
- declare function bigint(message?: string): Validator<unknown, bigint>;
1211
-
1212
- interface StandardSchemaV1<Input = unknown, Output = Input> {
1213
- readonly '~standard': StandardSchemaV1.Props<Input, Output>;
1214
- }
1215
- declare namespace StandardSchemaV1 {
1216
- interface Props<Input = unknown, Output = Input> {
1217
- readonly version: 1;
1218
- readonly vendor: string;
1219
- readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
1220
- readonly types?: Types<Input, Output> | undefined;
1221
- }
1222
- type Result<Output> = {
1223
- readonly value: Output;
1224
- readonly issues?: undefined;
1225
- } | {
1226
- readonly issues: ReadonlyArray<Issue>;
1227
- };
1228
- interface Issue {
1229
- readonly message: string;
1230
- readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
1231
- }
1232
- interface PathSegment {
1233
- readonly key: PropertyKey;
1234
- }
1235
- interface Types<Input = unknown, Output = Input> {
1236
- readonly input: Input;
1237
- readonly output: Output;
1238
- }
1239
- type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
1240
- type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
1241
- }
1242
-
1243
- /**
1244
- * Wrap a validator as a Standard Schema v1 object.
1245
- *
1246
- * The returned object satisfies the `StandardSchemaV1` interface, making
1247
- * it compatible with tRPC, TanStack Form/Router, React Hook Form, Hono,
1248
- * Next.js Server Actions, and any other tool that consumes Standard Schema.
1249
- *
1250
- * @example
1251
- * const userSchema = object({
1252
- * name: required(string()),
1253
- * email: required(email()),
1254
- * });
1255
- *
1256
- * // Wrap for Standard Schema consumers
1257
- * const standardUserSchema = toStandardSchema(userSchema);
1258
- *
1259
- * @param validator - A sync or async validator to wrap
1260
- * @returns A Standard Schema v1 object
1261
- */
1262
- declare function toStandardSchema<O>(validator: Validator<unknown, O>): StandardSchemaV1<unknown, O>;
1263
- declare function toStandardSchema<O>(validator: MaybeAsyncValidator<unknown, O>): StandardSchemaV1<unknown, O>;
1264
-
1265
- export { type AsyncValidator, type InferSchemaType, type MaybeAsyncValidator, ROOT_ERROR_KEY, type Schema, StandardSchemaV1, type SyncSchema, type ValidateOptions, type ValidationError, type ValidationResult, type Validator, type ValidatorMapOutput, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, is, isoDate, isoDateTime, isoDuration, isoTime, literal, matches, max, maxItems, maxLength, min, minItems, minLength, negative, nonEmpty, nonZero, notEmpty, nullable, number, object, oneOf, optional, parseBigInt, parseBool, parseDate, parseEnum, parseISODate, parseJSON, parseNumber, parseString, parseURL, pastDate, pattern, phoneNumber, positive, precision, refine, refineAsync, refineAt, refineAtAsync, required, string, stringEnum, toStandardSchema, todayOrFuture, transform, tuple, tupleOf, union, unique, url, uuid, validate, validateAndFormatResult, when, whenAsync };