@railway-ts/pipelines 0.1.30 → 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,1088 +1,1756 @@
1
- // src/result/result.ts
2
- var RESULT_BRAND = /* @__PURE__ */ Symbol("RESULT_BRAND");
3
- function ok(value) {
4
- return {
5
- ok: true,
6
- value,
7
- [RESULT_BRAND]: "ok"
8
- };
9
- }
10
- function err(error) {
11
- return { ok: false, error, [RESULT_BRAND]: "error" };
12
- }
13
- function isOk(result) {
14
- return result.ok;
15
- }
16
- function isErr(result) {
17
- return !result.ok;
18
- }
19
- function mapErr(result, fn) {
20
- return result.ok ? result : err(fn(result.error));
21
- }
22
- function match(result, patterns) {
23
- if (isOk(result)) {
24
- const okFn = patterns.ok;
25
- return okFn(result.value);
26
- }
27
- const errFn = patterns.err;
28
- return errFn(result.error);
29
- }
30
- function fromTry(f) {
31
- try {
32
- return ok(f());
33
- } catch (error) {
34
- return err(error instanceof Error ? error.message : String(error));
35
- }
36
- }
37
-
1
+ import { D as err, I as isErr, L as isOk, P as fromTry, U as match, W as ok, z as mapErr } from "../option-BQCaaEBP.mjs";
38
2
  // src/schema/core.ts
39
- var _abortEarly = false;
3
+ let _abortEarly = false;
4
+ /** @internal */
40
5
  function _getAbortEarly() {
41
- return _abortEarly;
6
+ return _abortEarly;
42
7
  }
8
+ /** @internal - Sets abortEarly for the duration of fn's synchronous execution */
43
9
  function _withAbortEarly(enabled, fn) {
44
- const prev = _abortEarly;
45
- _abortEarly = enabled;
46
- try {
47
- return fn();
48
- } finally {
49
- _abortEarly = prev;
50
- }
10
+ const prev = _abortEarly;
11
+ _abortEarly = enabled;
12
+ try {
13
+ return fn();
14
+ } finally {
15
+ _abortEarly = prev;
16
+ }
51
17
  }
52
18
  function object(schema, { strict = true } = {}) {
53
- return (obj, parentPath = []) => {
54
- if (obj === null || typeof obj !== "object") {
55
- return err([{ path: parentPath, message: "Expected an object" }]);
56
- }
57
- const abortEarly = _getAbortEarly();
58
- const allErrors = [];
59
- const validatedObj = {};
60
- if (strict !== false) {
61
- const extraKeys = Object.keys(obj).filter((key) => !Object.prototype.hasOwnProperty.call(schema, key));
62
- if (extraKeys.length > 0) {
63
- if (abortEarly) {
64
- return err([{ path: [...parentPath, extraKeys[0]], message: `Unexpected field: '${extraKeys[0]}'` }]);
65
- }
66
- for (const key of extraKeys) {
67
- allErrors.push({
68
- path: [...parentPath, key],
69
- message: `Unexpected field: '${key}'`
70
- });
71
- }
72
- }
73
- }
74
- if (abortEarly && allErrors.length > 0) return err(allErrors);
75
- const pendingResults = [];
76
- for (const key in schema) {
77
- if (!Object.prototype.hasOwnProperty.call(schema, key)) continue;
78
- const validator = schema[key];
79
- if (!validator) continue;
80
- if (abortEarly && allErrors.length > 0) break;
81
- const value = obj[key];
82
- const fieldPath = [...parentPath, key];
83
- const result = validator(value, fieldPath);
84
- if (result instanceof Promise) {
85
- if (abortEarly && allErrors.length > 0) continue;
86
- pendingResults.push(
87
- result.then((r) => {
88
- if (isOk(r)) {
89
- validatedObj[key] = r.value;
90
- } else {
91
- allErrors.push(...r.error);
92
- }
93
- })
94
- );
95
- } else if (isOk(result)) {
96
- validatedObj[key] = result.value;
97
- } else {
98
- allErrors.push(...result.error);
99
- if (abortEarly) break;
100
- }
101
- }
102
- if (pendingResults.length > 0) {
103
- return Promise.all(pendingResults).then(() => {
104
- if (allErrors.length > 0) return err(allErrors);
105
- return ok(validatedObj);
106
- });
107
- }
108
- if (allErrors.length > 0) return err(allErrors);
109
- return ok(validatedObj);
110
- };
19
+ return (obj, parentPath = []) => {
20
+ if (obj === null || typeof obj !== "object") return err([{
21
+ path: parentPath,
22
+ message: "Expected an object"
23
+ }]);
24
+ const abortEarly = _getAbortEarly();
25
+ const allErrors = [];
26
+ const validatedObj = {};
27
+ if (strict !== false) {
28
+ const extraKeys = Object.keys(obj).filter((key) => !Object.prototype.hasOwnProperty.call(schema, key));
29
+ if (extraKeys.length > 0) {
30
+ if (abortEarly) return err([{
31
+ path: [...parentPath, extraKeys[0]],
32
+ message: `Unexpected field: '${extraKeys[0]}'`
33
+ }]);
34
+ for (const key of extraKeys) allErrors.push({
35
+ path: [...parentPath, key],
36
+ message: `Unexpected field: '${key}'`
37
+ });
38
+ }
39
+ }
40
+ if (abortEarly && allErrors.length > 0) return err(allErrors);
41
+ const pendingResults = [];
42
+ for (const key in schema) {
43
+ if (!Object.prototype.hasOwnProperty.call(schema, key)) continue;
44
+ const validator = schema[key];
45
+ if (!validator) continue;
46
+ if (abortEarly && allErrors.length > 0) break;
47
+ const result = validator(obj[key], [...parentPath, key]);
48
+ if (result instanceof Promise) {
49
+ if (abortEarly && allErrors.length > 0) continue;
50
+ pendingResults.push(result.then((r) => {
51
+ if (isOk(r)) validatedObj[key] = r.value;
52
+ else allErrors.push(...r.error);
53
+ }));
54
+ } else if (isOk(result)) validatedObj[key] = result.value;
55
+ else {
56
+ allErrors.push(...result.error);
57
+ if (abortEarly) break;
58
+ }
59
+ }
60
+ if (pendingResults.length > 0) return Promise.all(pendingResults).then(() => {
61
+ if (allErrors.length > 0) return err(allErrors);
62
+ return ok(validatedObj);
63
+ });
64
+ if (allErrors.length > 0) return err(allErrors);
65
+ return ok(validatedObj);
66
+ };
111
67
  }
112
68
  function required(validator, message = "Field is required") {
113
- return (value, path = []) => {
114
- if (value === void 0 || value === null) {
115
- return err([{ path, message }]);
116
- }
117
- return validator(value, path);
118
- };
69
+ return (value, path = []) => {
70
+ if (value === void 0 || value === null) return err([{
71
+ path,
72
+ message
73
+ }]);
74
+ return validator(value, path);
75
+ };
119
76
  }
120
77
  function optional(validator) {
121
- return (value, path = []) => {
122
- if (value === void 0 || value === null) {
123
- return ok(void 0);
124
- }
125
- return validator(value, path);
126
- };
127
- }
78
+ return (value, path = []) => {
79
+ if (value === void 0 || value === null) return ok(void 0);
80
+ return validator(value, path);
81
+ };
82
+ }
83
+ /**
84
+ * Create a validator that only accepts null values.
85
+ *
86
+ * @example
87
+ * const validate = nullable();
88
+ * validate(null); // ok(null)
89
+ * validate('some value'); // err([{ path: [], message: 'Must be null' }])
90
+ *
91
+ * @param message - Custom error message
92
+ * @returns A validator that ensures the value is exactly null
93
+ */
128
94
  function nullable(message = "Must be null") {
129
- return (value, path = []) => {
130
- if (value !== null) {
131
- return err([{ path, message }]);
132
- }
133
- return ok(null);
134
- };
95
+ return (value, path = []) => {
96
+ if (value !== null) return err([{
97
+ path,
98
+ message
99
+ }]);
100
+ return ok(null);
101
+ };
135
102
  }
136
103
  function emptyAsOptional(validator) {
137
- return (value, path = []) => {
138
- if (value === "" || Array.isArray(value) && value.length === 0 || typeof value === "object" && value !== null && Object.keys(value).length === 0) {
139
- return ok(void 0);
140
- }
141
- return optional(validator)(value, path);
142
- };
143
- }
104
+ return (value, path = []) => {
105
+ if (value === "" || Array.isArray(value) && value.length === 0 || typeof value === "object" && value !== null && Object.keys(value).length === 0) return ok(void 0);
106
+ return optional(validator)(value, path);
107
+ };
108
+ }
109
+ /**
110
+ * Create a validator that checks if a value exactly matches the expected literal.
111
+ *
112
+ * @example
113
+ * const validate = literal('active');
114
+ * validate('active'); // ok("active")
115
+ * validate('completed'); // err([{ path: [], message: "Value must be 'active'" }])
116
+ *
117
+ * @param expectedValue - The exact value that should be matched
118
+ * @param message - Custom error message
119
+ * @returns A validator that checks if the value matches the literal
120
+ */
144
121
  function literal(expectedValue, message = `Value must be '${String(expectedValue)}'`) {
145
- return (value, path = []) => {
146
- if (value !== expectedValue) {
147
- return err([{ path, message }]);
148
- }
149
- return ok(expectedValue);
150
- };
122
+ return (value, path = []) => {
123
+ if (value !== expectedValue) return err([{
124
+ path,
125
+ message
126
+ }]);
127
+ return ok(expectedValue);
128
+ };
151
129
  }
152
-
153
130
  // src/schema/utils.ts
154
- var ROOT_ERROR_KEY = "_root";
131
+ /**
132
+ * The key used in formatted error objects for root-level validation errors (i.e. errors with an empty path).
133
+ */
134
+ const ROOT_ERROR_KEY = "_root";
135
+ /**
136
+ * Combine multiple validators into a single validator, applying them in sequence.
137
+ * Each validator's output feeds into the next. Short-circuits on first error.
138
+ *
139
+ * @example
140
+ * const validate = chain(string(), nonEmpty(), minLength(8));
141
+ * validate('password123'); // ok("password123")
142
+ * validate('abc'); // err([{ path: [], message: 'Must be at least 8 characters' }])
143
+ *
144
+ * @param validators - A list of validators to compose
145
+ * @returns A combined validator that applies all validators in sequence
146
+ */
155
147
  function chain(...validators) {
156
- return (value, path = []) => {
157
- let result = ok(value);
158
- for (const validator of validators) {
159
- if (isErr(result)) return result;
160
- const nextResult = validator(result.value, path);
161
- result = isErr(nextResult) ? nextResult : ok(nextResult.value);
162
- }
163
- return result;
164
- };
148
+ return (value, path = []) => {
149
+ let result = ok(value);
150
+ for (const validator of validators) {
151
+ if (isErr(result)) return result;
152
+ const nextResult = validator(result.value, path);
153
+ result = isErr(nextResult) ? nextResult : ok(nextResult.value);
154
+ }
155
+ return result;
156
+ };
165
157
  }
166
158
  function chainAsync(...validators) {
167
- return async (value, path = []) => {
168
- let current = value;
169
- for (const validator of validators) {
170
- const result = await validator(current, path);
171
- if (isErr(result)) return result;
172
- current = result.value;
173
- }
174
- return ok(current);
175
- };
159
+ return async (value, path = []) => {
160
+ let current = value;
161
+ for (const validator of validators) {
162
+ const result = await validator(current, path);
163
+ if (isErr(result)) return result;
164
+ current = result.value;
165
+ }
166
+ return ok(current);
167
+ };
176
168
  }
177
169
  function validate(value, validator, pathOrOptions = [], maybeOptions) {
178
- const path = Array.isArray(pathOrOptions) ? pathOrOptions : [];
179
- const options = Array.isArray(pathOrOptions) ? maybeOptions : pathOrOptions;
180
- if (options?.abortEarly) {
181
- return _withAbortEarly(true, () => validator(value, path));
182
- }
183
- return validator(value, path);
170
+ const path = Array.isArray(pathOrOptions) ? pathOrOptions : [];
171
+ if ((Array.isArray(pathOrOptions) ? maybeOptions : pathOrOptions)?.abortEarly) return _withAbortEarly(true, () => validator(value, path));
172
+ return validator(value, path);
184
173
  }
185
174
  function is(value, validator) {
186
- const result = _withAbortEarly(true, () => validator(value));
187
- if (result instanceof Promise) {
188
- return result.then((r) => r.ok);
189
- }
190
- return result.ok;
191
- }
175
+ const result = _withAbortEarly(true, () => validator(value));
176
+ if (result instanceof Promise) return result.then((r) => r.ok);
177
+ return result.ok;
178
+ }
179
+ /**
180
+ * Format validation errors into a user-friendly object.
181
+ * Converts array paths to dot/bracket notation strings.
182
+ *
183
+ * @example
184
+ * formatErrors([
185
+ * { path: ['name'], message: 'Required' },
186
+ * { path: ['items', '1'], message: 'Must be a number' },
187
+ * ]);
188
+ * // { name: 'Required', 'items[1]': 'Must be a number' }
189
+ *
190
+ * @param errors - The array of validation errors to format
191
+ * @returns An object mapping paths to error messages
192
+ */
192
193
  function formatErrors(errors) {
193
- return errors.reduce(
194
- (acc, error) => {
195
- const formattedPath = error.path.reduce((path, segment, index) => {
196
- if (/^\d+$/.test(segment)) {
197
- return `${path}[${segment}]`;
198
- }
199
- return index === 0 ? segment : `${path}.${segment}`;
200
- }, "");
201
- acc[formattedPath || ROOT_ERROR_KEY] = error.message;
202
- return acc;
203
- },
204
- {}
205
- );
194
+ return errors.reduce((acc, error) => {
195
+ const formattedPath = error.path.reduce((path, segment, index) => {
196
+ if (/^\d+$/.test(segment)) return `${path}[${segment}]`;
197
+ return index === 0 ? segment : `${path}.${segment}`;
198
+ }, "");
199
+ acc[formattedPath || "_root"] = error.message;
200
+ return acc;
201
+ }, {});
206
202
  }
207
203
  function validateAndFormatResult(input, schema, options) {
208
- const run = () => {
209
- const result = schema(input);
210
- if (result instanceof Promise) {
211
- return result.then(
212
- (r) => match(r, {
213
- ok: (data) => ({ valid: true, data }),
214
- err: (errors) => ({ valid: false, errors: formatErrors(errors) })
215
- })
216
- );
217
- }
218
- return match(result, {
219
- ok: (data) => ({ valid: true, data }),
220
- err: (errors) => ({ valid: false, errors: formatErrors(errors) })
221
- });
222
- };
223
- if (options?.abortEarly) {
224
- return _withAbortEarly(true, run);
225
- }
226
- return run();
227
- }
204
+ const run = () => {
205
+ const result = schema(input);
206
+ if (result instanceof Promise) return result.then((r) => match(r, {
207
+ ok: (data) => ({
208
+ valid: true,
209
+ data
210
+ }),
211
+ err: (errors) => ({
212
+ valid: false,
213
+ errors: formatErrors(errors)
214
+ })
215
+ }));
216
+ return match(result, {
217
+ ok: (data) => ({
218
+ valid: true,
219
+ data
220
+ }),
221
+ err: (errors) => ({
222
+ valid: false,
223
+ errors: formatErrors(errors)
224
+ })
225
+ });
226
+ };
227
+ if (options?.abortEarly) return _withAbortEarly(true, run);
228
+ return run();
229
+ }
230
+ /**
231
+ * Create a validator that transforms a value during validation.
232
+ * The transformer function must be pure and not throw exceptions.
233
+ *
234
+ * @example
235
+ * const normalize = chain(string(), email(), transform(s => s.toLowerCase()));
236
+ * normalize('User@Example.COM'); // ok("user@example.com")
237
+ *
238
+ * @param transformer - A pure function that transforms the input value
239
+ * @returns A validator that applies the transformation
240
+ */
228
241
  function transform(transformer) {
229
- return (value) => ok(transformer(value));
230
- }
242
+ return (value) => ok(transformer(value));
243
+ }
244
+ /**
245
+ * Create a validator that refines a value with a custom predicate.
246
+ *
247
+ * @example
248
+ * const isEven = refine<number>(n => n % 2 === 0, 'Must be even');
249
+ * isEven(4); // ok(4)
250
+ * isEven(3); // err([{ path: [], message: 'Must be even' }])
251
+ *
252
+ * @param predicate - A function that returns true if the value is valid
253
+ * @param message - The error message if validation fails
254
+ * @returns A validator that checks the predicate
255
+ */
231
256
  function refine(predicate, message = "Custom validation failed") {
232
- return (value, path = []) => {
233
- if (!predicate(value)) {
234
- return err([{ path, message }]);
235
- }
236
- return ok(value);
237
- };
238
- }
257
+ return (value, path = []) => {
258
+ if (!predicate(value)) return err([{
259
+ path,
260
+ message
261
+ }]);
262
+ return ok(value);
263
+ };
264
+ }
265
+ /**
266
+ * Create an async validator that refines a value with an asynchronous predicate.
267
+ * This is the async counterpart of {@link refine}.
268
+ *
269
+ * @example
270
+ * const unique = refineAsync<string>(
271
+ * async (name) => !(await db.users.exists({ name })),
272
+ * 'Already taken'
273
+ * );
274
+ *
275
+ * @param predicate - An async function returning true if the value is valid
276
+ * @param message - The error message if validation fails
277
+ * @returns An async validator that checks the predicate
278
+ */
239
279
  function refineAsync(predicate, message = "Custom validation failed") {
240
- return async (value, path = []) => {
241
- if (!await predicate(value)) {
242
- return err([{ path, message }]);
243
- }
244
- return ok(value);
245
- };
246
- }
280
+ return async (value, path = []) => {
281
+ if (!await predicate(value)) return err([{
282
+ path,
283
+ message
284
+ }]);
285
+ return ok(value);
286
+ };
287
+ }
288
+ /**
289
+ * Create a validator that targets a specific field path with cross-field validation.
290
+ * Unlike `refine`, receives the entire parent object and attaches errors to a specific field.
291
+ *
292
+ * @example
293
+ * const validate = chain(
294
+ * object({ password: required(string()), confirm: required(string()) }),
295
+ * refineAt('confirm', (d) => d.password === d.confirm, 'Passwords must match')
296
+ * );
297
+ *
298
+ * @param targetPath - The field path where the error should be attached
299
+ * @param predicate - Validation function that receives the entire parent object
300
+ * @param message - Error message when validation fails
301
+ * @returns A validator for cross-field validation
302
+ *
303
+ * @see refine - For single-field validation without cross-field dependencies
304
+ */
247
305
  function refineAt(targetPath, predicate, message) {
248
- return (value, parentPath = []) => {
249
- if (!predicate(value)) {
250
- const fieldPath = Array.isArray(targetPath) ? targetPath : [targetPath];
251
- return err([{ path: [...parentPath, ...fieldPath], message }]);
252
- }
253
- return ok(value);
254
- };
255
- }
306
+ return (value, parentPath = []) => {
307
+ if (!predicate(value)) {
308
+ const fieldPath = Array.isArray(targetPath) ? targetPath : [targetPath];
309
+ return err([{
310
+ path: [...parentPath, ...fieldPath],
311
+ message
312
+ }]);
313
+ }
314
+ return ok(value);
315
+ };
316
+ }
317
+ /**
318
+ * Create an async validator that targets a specific field path with cross-field validation.
319
+ * This is the async counterpart of {@link refineAt}.
320
+ *
321
+ * @example
322
+ * const validate = chainAsync(
323
+ * object({ username: required(string()), email: required(email()) }),
324
+ * refineAtAsync(
325
+ * 'username',
326
+ * async (d) => !(await db.users.exists({ username: d.username })),
327
+ * 'Username taken'
328
+ * )
329
+ * );
330
+ *
331
+ * @param targetPath - The field path where the error should be attached
332
+ * @param predicate - An async function that receives the entire parent object
333
+ * @param message - Error message when validation fails
334
+ * @returns An async validator for cross-field validation
335
+ *
336
+ * @see refineAt - For synchronous cross-field validation
337
+ */
256
338
  function refineAtAsync(targetPath, predicate, message) {
257
- return async (value, parentPath = []) => {
258
- if (!await predicate(value)) {
259
- const fieldPath = Array.isArray(targetPath) ? targetPath : [targetPath];
260
- return err([{ path: [...parentPath, ...fieldPath], message }]);
261
- }
262
- return ok(value);
263
- };
264
- }
339
+ return async (value, parentPath = []) => {
340
+ if (!await predicate(value)) {
341
+ const fieldPath = Array.isArray(targetPath) ? targetPath : [targetPath];
342
+ return err([{
343
+ path: [...parentPath, ...fieldPath],
344
+ message
345
+ }]);
346
+ }
347
+ return ok(value);
348
+ };
349
+ }
350
+ /**
351
+ * Create a conditional validator that applies different validators based on a predicate.
352
+ * When the predicate returns true, `thenValidator` is applied.
353
+ * When false, `elseValidator` is applied (if provided), otherwise the value passes through.
354
+ *
355
+ * @example
356
+ * const validate = when<FormData>(
357
+ * (data) => data.contactMethod === 'email',
358
+ * refineAt('email', (d) => d.email.includes('@'), 'Valid email required'),
359
+ * refineAt('phone', (d) => d.phone.length > 0, 'Phone required'),
360
+ * );
361
+ *
362
+ * @param predicate - A function that determines which validator to apply
363
+ * @param thenValidator - Validator applied when predicate returns true
364
+ * @param elseValidator - Optional validator applied when predicate returns false
365
+ * @returns A validator that conditionally applies validation
366
+ */
265
367
  function when(predicate, thenValidator, elseValidator) {
266
- return (value, path = []) => {
267
- if (predicate(value)) {
268
- return thenValidator(value, path);
269
- }
270
- return elseValidator ? elseValidator(value, path) : ok(value);
271
- };
272
- }
368
+ return (value, path = []) => {
369
+ if (predicate(value)) return thenValidator(value, path);
370
+ return elseValidator ? elseValidator(value, path) : ok(value);
371
+ };
372
+ }
373
+ /**
374
+ * Create a conditional async validator that applies different validators based on a predicate.
375
+ * This is the async counterpart of {@link when}.
376
+ *
377
+ * @example
378
+ * const validate = whenAsync<FormData>(
379
+ * (data) => data.requiresVerification,
380
+ * refineAtAsync('code', async (d) => await verifyCode(d.code), 'Invalid code'),
381
+ * );
382
+ *
383
+ * @param predicate - A function that determines which validator to apply
384
+ * @param thenValidator - Validator applied when predicate returns true
385
+ * @param elseValidator - Optional validator applied when predicate returns false
386
+ * @returns An async validator that conditionally applies validation
387
+ */
273
388
  function whenAsync(predicate, thenValidator, elseValidator) {
274
- return async (value, path = []) => {
275
- if (predicate(value)) {
276
- return thenValidator(value, path);
277
- }
278
- return elseValidator ? elseValidator(value, path) : ok(value);
279
- };
389
+ return async (value, path = []) => {
390
+ if (predicate(value)) return thenValidator(value, path);
391
+ return elseValidator ? elseValidator(value, path) : ok(value);
392
+ };
280
393
  }
281
-
282
394
  // src/schema/string.ts
395
+ /**
396
+ * Create a validator that ensures a value is a string.
397
+ *
398
+ * @example
399
+ * const validate = string();
400
+ * validate('John'); // ok("John")
401
+ * validate(42); // err([{ path: [], message: 'Must be a string' }])
402
+ *
403
+ * @param message - Custom error message
404
+ * @returns A validator that checks if a value is a string
405
+ */
283
406
  function string(message = "Must be a string") {
284
- return (value, path = []) => {
285
- if (typeof value !== "string") {
286
- return err([{ path, message }]);
287
- }
288
- return ok(value);
289
- };
290
- }
291
- function minLength(min2, message = `Must be at least ${min2} characters`) {
292
- return (value, path = []) => {
293
- if (value.length < min2) {
294
- return err([{ path, message }]);
295
- }
296
- return ok(value);
297
- };
298
- }
299
- function maxLength(max2, message = `Must be at most ${max2} characters`) {
300
- return (value, path = []) => {
301
- if (value.length > max2) {
302
- return err([{ path, message }]);
303
- }
304
- return ok(value);
305
- };
306
- }
407
+ return (value, path = []) => {
408
+ if (typeof value !== "string") return err([{
409
+ path,
410
+ message
411
+ }]);
412
+ return ok(value);
413
+ };
414
+ }
415
+ /**
416
+ * Create a validator that ensures a string's length is at least a minimum value.
417
+ *
418
+ * @example
419
+ * const validate = minLength(3);
420
+ * validate('john_doe'); // ok("john_doe")
421
+ * validate('jo'); // err([{ path: [], message: 'Must be at least 3 characters' }])
422
+ *
423
+ * @param min - The minimum length (inclusive)
424
+ * @param message - Custom error message
425
+ * @returns A validator that checks if a string meets the minimum length
426
+ */
427
+ function minLength(min, message = `Must be at least ${min} characters`) {
428
+ return (value, path = []) => {
429
+ if (value.length < min) return err([{
430
+ path,
431
+ message
432
+ }]);
433
+ return ok(value);
434
+ };
435
+ }
436
+ /**
437
+ * Create a validator that ensures a string's length is at most a maximum value.
438
+ *
439
+ * @example
440
+ * const validate = maxLength(10);
441
+ * validate('short'); // ok("short")
442
+ * validate('this is too long!!!'); // err([{ path: [], message: 'Must be at most 10 characters' }])
443
+ *
444
+ * @param max - The maximum length (inclusive)
445
+ * @param message - Custom error message
446
+ * @returns A validator that checks if a string meets the maximum length
447
+ */
448
+ function maxLength(max, message = `Must be at most ${max} characters`) {
449
+ return (value, path = []) => {
450
+ if (value.length > max) return err([{
451
+ path,
452
+ message
453
+ }]);
454
+ return ok(value);
455
+ };
456
+ }
457
+ /**
458
+ * Create a validator that ensures a string matches a regular expression pattern.
459
+ *
460
+ * @example
461
+ * const validate = pattern(/^[a-zA-Z0-9]+$/);
462
+ * validate('abc123'); // ok("abc123")
463
+ * validate('abc!'); // err([{ path: [], message: 'Invalid format' }])
464
+ *
465
+ * @param regex - The regular expression to test against
466
+ * @param message - Custom error message
467
+ * @returns A validator that checks if a string matches the pattern
468
+ */
307
469
  function pattern(regex, message = "Invalid format") {
308
- return (value, path = []) => {
309
- if (!regex.test(value)) {
310
- return err([{ path, message }]);
311
- }
312
- return ok(value);
313
- };
314
- }
470
+ return (value, path = []) => {
471
+ if (!regex.test(value)) return err([{
472
+ path,
473
+ message
474
+ }]);
475
+ return ok(value);
476
+ };
477
+ }
478
+ /**
479
+ * Create a validator that ensures a string is not empty after trimming whitespace.
480
+ *
481
+ * @example
482
+ * const validate = nonEmpty();
483
+ * validate('John'); // ok("John")
484
+ * validate(''); // err([{ path: [], message: 'Field must not be empty' }])
485
+ * validate(' '); // err([{ path: [], message: 'Field must not be empty' }])
486
+ *
487
+ * @param message - Custom error message
488
+ * @returns A validator that checks if a string is not empty
489
+ */
315
490
  function nonEmpty(message = "Field must not be empty") {
316
- return (value, path = []) => {
317
- if (value.trim().length === 0) {
318
- return err([{ path, message }]);
319
- }
320
- return ok(value);
321
- };
322
- }
491
+ return (value, path = []) => {
492
+ if (value.trim().length === 0) return err([{
493
+ path,
494
+ message
495
+ }]);
496
+ return ok(value);
497
+ };
498
+ }
499
+ /**
500
+ * Create a validator that ensures a string is a valid email address.
501
+ *
502
+ * @example
503
+ * const validate = email();
504
+ * validate('user@example.com'); // ok("user@example.com")
505
+ * validate('not-an-email'); // err([{ path: [], message: 'Invalid email format' }])
506
+ *
507
+ * @param message - Custom error message
508
+ * @returns A validator that checks if a string is a valid email
509
+ */
323
510
  function email(message = "Invalid email format") {
324
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
325
- return pattern(emailRegex, message);
326
- }
511
+ return pattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, message);
512
+ }
513
+ /**
514
+ * Create a validator that ensures a string is a valid URL.
515
+ *
516
+ * @example
517
+ * const validate = url();
518
+ * validate('https://example.com'); // ok("https://example.com")
519
+ * validate('not-a-url'); // err([{ path: [], message: 'Invalid URL format' }])
520
+ *
521
+ * @param message - Custom error message
522
+ * @returns A validator that checks if a string is a valid URL
523
+ */
327
524
  function url(message = "Invalid URL format") {
328
- return (value, path = []) => {
329
- try {
330
- new URL(value);
331
- return ok(value);
332
- } catch {
333
- return err([{ path, message }]);
334
- }
335
- };
336
- }
525
+ return (value, path = []) => {
526
+ try {
527
+ new URL(value);
528
+ return ok(value);
529
+ } catch {
530
+ return err([{
531
+ path,
532
+ message
533
+ }]);
534
+ }
535
+ };
536
+ }
537
+ /**
538
+ * Create a validator that ensures a string is a valid phone number.
539
+ * Accepts common formats including international (+), spaces, dashes, and parentheses.
540
+ *
541
+ * @example
542
+ * const validate = phoneNumber();
543
+ * validate('+1-555-123-4567'); // ok("+1-555-123-4567")
544
+ * validate('not-a-phone'); // err([{ path: [], message: 'Invalid phone number format' }])
545
+ *
546
+ * @param message - Custom error message
547
+ * @returns A validator that checks if a string is a valid phone number
548
+ */
337
549
  function phoneNumber(message = "Invalid phone number format") {
338
- const phoneRegex = /^\+?[\d\-()]{8,20}$/;
339
- return (value, path = []) => {
340
- const cleanedValue = value.replaceAll(/\s+/g, "");
341
- if (!phoneRegex.test(cleanedValue) || cleanedValue.replaceAll(/\D/g, "").length < 7) {
342
- return err([{ path, message }]);
343
- }
344
- return ok(value);
345
- };
346
- }
550
+ const phoneRegex = /^\+?[\d\-()]{8,20}$/;
551
+ return (value, path = []) => {
552
+ const cleanedValue = value.replaceAll(/\s+/g, "");
553
+ if (!phoneRegex.test(cleanedValue) || cleanedValue.replaceAll(/\D/g, "").length < 7) return err([{
554
+ path,
555
+ message
556
+ }]);
557
+ return ok(value);
558
+ };
559
+ }
560
+ /**
561
+ * Create a validator that ensures a string is a valid UUID (RFC 4122).
562
+ * Accepts any UUID version including NIL UUIDs (all zeros).
563
+ *
564
+ * @example
565
+ * const validate = uuid();
566
+ * validate('550e8400-e29b-41d4-a716-446655440000'); // ok(...)
567
+ * validate('not-a-uuid'); // err([{ path: [], message: 'Invalid UUID format' }])
568
+ *
569
+ * @param message - Custom error message
570
+ * @returns A validator that checks if a string is a valid UUID
571
+ */
347
572
  function uuid(message = "Invalid UUID format") {
348
- const uuidRegex = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
349
- return pattern(uuidRegex, message);
350
- }
573
+ return pattern(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i, message);
574
+ }
575
+ /**
576
+ * Create a validator that ensures a string is a valid ISO 8601 date (YYYY-MM-DD).
577
+ * Validates both format and calendar correctness (e.g., rejects Feb 30).
578
+ *
579
+ * @example
580
+ * const validate = isoDate();
581
+ * validate('2024-01-15'); // ok("2024-01-15")
582
+ * validate('2024-02-30'); // err([{ path: [], message: 'Invalid ISO date format' }])
583
+ *
584
+ * @param message - Custom error message
585
+ * @returns A validator that checks if a string is a valid ISO date
586
+ */
351
587
  function isoDate(message = "Invalid ISO date format") {
352
- const isoDateRegex = /^\d{4}-\d{2}-\d{2}$/;
353
- return (value, path = []) => {
354
- if (!isoDateRegex.test(value)) {
355
- return err([{ path, message }]);
356
- }
357
- const date2 = /* @__PURE__ */ new Date(value + "T00:00:00Z");
358
- if (Number.isNaN(date2.getTime()) || date2.toISOString().slice(0, 10) !== value) {
359
- return err([{ path, message }]);
360
- }
361
- return ok(value);
362
- };
363
- }
588
+ const isoDateRegex = /^\d{4}-\d{2}-\d{2}$/;
589
+ return (value, path = []) => {
590
+ if (!isoDateRegex.test(value)) return err([{
591
+ path,
592
+ message
593
+ }]);
594
+ const date = /* @__PURE__ */ new Date(value + "T00:00:00Z");
595
+ if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value) return err([{
596
+ path,
597
+ message
598
+ }]);
599
+ return ok(value);
600
+ };
601
+ }
602
+ /**
603
+ * Create a validator that ensures a string is a valid ISO 8601 / RFC 3339 time.
604
+ * Format: `HH:mm:ss[.fractional][Z|±HH:mm]`. Timezone is optional.
605
+ *
606
+ * @example
607
+ * const validate = isoTime();
608
+ * validate('14:30:00'); // ok("14:30:00")
609
+ * validate('14:30:00Z'); // ok("14:30:00Z")
610
+ * validate('14:30:00+05:30'); // ok("14:30:00+05:30")
611
+ * validate('25:00:00'); // err([{ path: [], message: 'Invalid ISO time format' }])
612
+ *
613
+ * @param message - Custom error message
614
+ * @returns A validator that checks if a string is a valid ISO time
615
+ */
364
616
  function isoTime(message = "Invalid ISO time format") {
365
- const isoTimeRegex = /^(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))?$/;
366
- return (value, path = []) => {
367
- const match2 = isoTimeRegex.exec(value);
368
- if (!match2) {
369
- return err([{ path, message }]);
370
- }
371
- const hours = Number(match2[1]);
372
- const minutes = Number(match2[2]);
373
- const seconds = Number(match2[3]);
374
- if (hours > 23 || minutes > 59 || seconds > 59) {
375
- return err([{ path, message }]);
376
- }
377
- if (match2[4]) {
378
- const tzHours = Number(match2[5]);
379
- const tzMinutes = Number(match2[6]);
380
- if (tzHours > 23 || tzMinutes > 59) {
381
- return err([{ path, message }]);
382
- }
383
- }
384
- return ok(value);
385
- };
386
- }
617
+ const isoTimeRegex = /^(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))?$/;
618
+ return (value, path = []) => {
619
+ const match = isoTimeRegex.exec(value);
620
+ if (!match) return err([{
621
+ path,
622
+ message
623
+ }]);
624
+ const hours = Number(match[1]);
625
+ const minutes = Number(match[2]);
626
+ const seconds = Number(match[3]);
627
+ if (hours > 23 || minutes > 59 || seconds > 59) return err([{
628
+ path,
629
+ message
630
+ }]);
631
+ if (match[4]) {
632
+ const tzHours = Number(match[5]);
633
+ const tzMinutes = Number(match[6]);
634
+ if (tzHours > 23 || tzMinutes > 59) return err([{
635
+ path,
636
+ message
637
+ }]);
638
+ }
639
+ return ok(value);
640
+ };
641
+ }
642
+ /**
643
+ * Create a validator that ensures a string is a valid ISO 8601 / RFC 3339 datetime.
644
+ * Format: `YYYY-MM-DDTHH:mm:ss[.fractional][Z|±HH:mm]`.
645
+ *
646
+ * @example
647
+ * const validate = isoDateTime();
648
+ * validate('2024-01-15T14:30:00Z'); // ok(...)
649
+ * validate('2024-01-15T14:30:00+05:30'); // ok(...)
650
+ * validate('2024-02-30T14:30:00Z'); // err([{ path: [], message: 'Invalid ISO datetime format' }])
651
+ *
652
+ * @param message - Custom error message
653
+ * @returns A validator that checks if a string is a valid ISO datetime
654
+ */
387
655
  function isoDateTime(message = "Invalid ISO datetime format") {
388
- const isoDateTimeRegex = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))?$/;
389
- return (value, path = []) => {
390
- const match2 = isoDateTimeRegex.exec(value);
391
- if (!match2) {
392
- return err([{ path, message }]);
393
- }
394
- const datePart = match2[1];
395
- const date2 = /* @__PURE__ */ new Date(datePart + "T00:00:00Z");
396
- if (Number.isNaN(date2.getTime()) || date2.toISOString().slice(0, 10) !== datePart) {
397
- return err([{ path, message }]);
398
- }
399
- const hours = Number(match2[2]);
400
- const minutes = Number(match2[3]);
401
- const seconds = Number(match2[4]);
402
- if (hours > 23 || minutes > 59 || seconds > 59) {
403
- return err([{ path, message }]);
404
- }
405
- if (match2[5]) {
406
- const tzHours = Number(match2[6]);
407
- const tzMinutes = Number(match2[7]);
408
- if (tzHours > 23 || tzMinutes > 59) {
409
- return err([{ path, message }]);
410
- }
411
- }
412
- return ok(value);
413
- };
414
- }
656
+ const isoDateTimeRegex = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))?$/;
657
+ return (value, path = []) => {
658
+ const match = isoDateTimeRegex.exec(value);
659
+ if (!match) return err([{
660
+ path,
661
+ message
662
+ }]);
663
+ const datePart = match[1];
664
+ const date = /* @__PURE__ */ new Date(datePart + "T00:00:00Z");
665
+ if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== datePart) return err([{
666
+ path,
667
+ message
668
+ }]);
669
+ const hours = Number(match[2]);
670
+ const minutes = Number(match[3]);
671
+ const seconds = Number(match[4]);
672
+ if (hours > 23 || minutes > 59 || seconds > 59) return err([{
673
+ path,
674
+ message
675
+ }]);
676
+ if (match[5]) {
677
+ const tzHours = Number(match[6]);
678
+ const tzMinutes = Number(match[7]);
679
+ if (tzHours > 23 || tzMinutes > 59) return err([{
680
+ path,
681
+ message
682
+ }]);
683
+ }
684
+ return ok(value);
685
+ };
686
+ }
687
+ /**
688
+ * Create a validator that ensures a string is a valid ISO 8601 duration.
689
+ * Format: `PnYnMnDTnHnMnS` or `PnW`.
690
+ *
691
+ * @example
692
+ * const validate = isoDuration();
693
+ * validate('P1Y2M3D'); // ok("P1Y2M3D")
694
+ * validate('PT1H30M'); // ok("PT1H30M")
695
+ * validate('P4W'); // ok("P4W")
696
+ * validate('P'); // err([{ path: [], message: 'Invalid ISO duration format' }])
697
+ *
698
+ * @param message - Custom error message
699
+ * @returns A validator that checks if a string is a valid ISO duration
700
+ */
415
701
  function isoDuration(message = "Invalid ISO duration format") {
416
- const isoDurationRegex = /^P(?:\d+W|(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?)$/;
417
- return (value, path = []) => {
418
- if (!isoDurationRegex.test(value) || value === "P" || value.endsWith("T")) {
419
- return err([{ path, message }]);
420
- }
421
- return ok(value);
422
- };
702
+ const isoDurationRegex = /^P(?:\d+W|(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?)$/;
703
+ return (value, path = []) => {
704
+ if (!isoDurationRegex.test(value) || value === "P" || value.endsWith("T")) return err([{
705
+ path,
706
+ message
707
+ }]);
708
+ return ok(value);
709
+ };
423
710
  }
424
-
425
711
  // src/schema/array.ts
426
712
  function array(itemValidator) {
427
- return (value, parentPath = []) => {
428
- if (!Array.isArray(value)) {
429
- return err([{ path: parentPath, message: "Expected an array" }]);
430
- }
431
- const abortEarly = _getAbortEarly();
432
- const allErrors = [];
433
- const validatedItems = Array.from({ length: value.length });
434
- const pendingResults = [];
435
- for (const [i, item] of value.entries()) {
436
- if (abortEarly && allErrors.length > 0) break;
437
- const itemPath = [...parentPath, i.toString()];
438
- const result = itemValidator(item, itemPath);
439
- if (result instanceof Promise) {
440
- if (abortEarly && allErrors.length > 0) continue;
441
- const index = i;
442
- pendingResults.push(
443
- result.then((r) => {
444
- if (isOk(r)) {
445
- validatedItems[index] = r.value;
446
- } else {
447
- allErrors.push(...r.error);
448
- }
449
- })
450
- );
451
- } else if (isOk(result)) {
452
- validatedItems[i] = result.value;
453
- } else {
454
- allErrors.push(...result.error);
455
- if (abortEarly) break;
456
- }
457
- }
458
- if (pendingResults.length > 0) {
459
- return Promise.all(pendingResults).then(() => {
460
- if (allErrors.length > 0) return err(allErrors);
461
- return ok(validatedItems);
462
- });
463
- }
464
- if (allErrors.length > 0) return err(allErrors);
465
- return ok(validatedItems);
466
- };
467
- }
468
- function minItems(min2, message = `Array must have at least ${min2} items`) {
469
- return (value, path = []) => {
470
- if (value.length < min2) {
471
- return err([{ path, message }]);
472
- }
473
- return ok(value);
474
- };
475
- }
476
- function maxItems(max2, message = `Array must have at most ${max2} items`) {
477
- return (value, path = []) => {
478
- if (value.length > max2) {
479
- return err([{ path, message }]);
480
- }
481
- return ok(value);
482
- };
483
- }
713
+ return (value, parentPath = []) => {
714
+ if (!Array.isArray(value)) return err([{
715
+ path: parentPath,
716
+ message: "Expected an array"
717
+ }]);
718
+ const abortEarly = _getAbortEarly();
719
+ const allErrors = [];
720
+ const validatedItems = Array.from({ length: value.length });
721
+ const pendingResults = [];
722
+ for (const [i, item] of value.entries()) {
723
+ if (abortEarly && allErrors.length > 0) break;
724
+ const result = itemValidator(item, [...parentPath, i.toString()]);
725
+ if (result instanceof Promise) {
726
+ if (abortEarly && allErrors.length > 0) continue;
727
+ const index = i;
728
+ pendingResults.push(result.then((r) => {
729
+ if (isOk(r)) validatedItems[index] = r.value;
730
+ else allErrors.push(...r.error);
731
+ }));
732
+ } else if (isOk(result)) validatedItems[i] = result.value;
733
+ else {
734
+ allErrors.push(...result.error);
735
+ if (abortEarly) break;
736
+ }
737
+ }
738
+ if (pendingResults.length > 0) return Promise.all(pendingResults).then(() => {
739
+ if (allErrors.length > 0) return err(allErrors);
740
+ return ok(validatedItems);
741
+ });
742
+ if (allErrors.length > 0) return err(allErrors);
743
+ return ok(validatedItems);
744
+ };
745
+ }
746
+ /**
747
+ * Validate that an array has at least a minimum number of items.
748
+ *
749
+ * @example
750
+ * const validate = minItems(2);
751
+ * validate([1, 2, 3]); // ok([1, 2, 3])
752
+ * validate([1]); // err([{ path: [], message: 'Array must have at least 2 items' }])
753
+ *
754
+ * @param min - The minimum number of items required
755
+ * @param message - Custom error message
756
+ * @returns A validator that checks minimum array length
757
+ */
758
+ function minItems(min, message = `Array must have at least ${min} items`) {
759
+ return (value, path = []) => {
760
+ if (value.length < min) return err([{
761
+ path,
762
+ message
763
+ }]);
764
+ return ok(value);
765
+ };
766
+ }
767
+ /**
768
+ * Validate that an array has at most a maximum number of items.
769
+ *
770
+ * @example
771
+ * const validate = maxItems(2);
772
+ * validate([1, 2]); // ok([1, 2])
773
+ * validate([1, 2, 3]); // err([{ path: [], message: 'Array must have at most 2 items' }])
774
+ *
775
+ * @param max - The maximum number of items allowed
776
+ * @param message - Custom error message
777
+ * @returns A validator that checks maximum array length
778
+ */
779
+ function maxItems(max, message = `Array must have at most ${max} items`) {
780
+ return (value, path = []) => {
781
+ if (value.length > max) return err([{
782
+ path,
783
+ message
784
+ }]);
785
+ return ok(value);
786
+ };
787
+ }
788
+ /**
789
+ * Validate that an array is not empty.
790
+ *
791
+ * @example
792
+ * const validate = notEmpty();
793
+ * validate([1]); // ok([1])
794
+ * validate([]); // err([{ path: [], message: 'Array must not be empty' }])
795
+ *
796
+ * @param message - Custom error message
797
+ * @returns A validator that checks the array is not empty
798
+ */
484
799
  function notEmpty(message = "Array must not be empty") {
485
- return minItems(1, message);
486
- }
800
+ return minItems(1, message);
801
+ }
802
+ /**
803
+ * Validate that an array contains only unique values.
804
+ *
805
+ * @example
806
+ * const validate = unique();
807
+ * validate([1, 2, 3]); // ok([1, 2, 3])
808
+ * validate([1, 2, 2, 3]); // err([{ path: ['2'], message: 'Array must contain unique values' }])
809
+ *
810
+ * @example
811
+ * // With custom key extractor for objects
812
+ * const validate = unique<{ id: number }>('Duplicate ID', (item) => item.id);
813
+ *
814
+ * @param message - Custom error message
815
+ * @param keyExtractor - Optional function to extract a comparison key from each item
816
+ * @returns A validator that checks for unique array values
817
+ */
487
818
  function unique(message = "Array must contain unique values", keyExtractor) {
488
- return (value, path = []) => {
489
- const seen = /* @__PURE__ */ new Set();
490
- for (const [i, item] of value.entries()) {
491
- const key = keyExtractor ? keyExtractor(item) : item;
492
- if (seen.has(key)) {
493
- return err([
494
- {
495
- path: [...path, i.toString()],
496
- message
497
- }
498
- ]);
499
- }
500
- seen.add(key);
501
- }
502
- return ok(value);
503
- };
504
- }
819
+ return (value, path = []) => {
820
+ const seen = /* @__PURE__ */ new Set();
821
+ for (const [i, item] of value.entries()) {
822
+ const key = keyExtractor ? keyExtractor(item) : item;
823
+ if (seen.has(key)) return err([{
824
+ path: [...path, i.toString()],
825
+ message
826
+ }]);
827
+ seen.add(key);
828
+ }
829
+ return ok(value);
830
+ };
831
+ }
832
+ /**
833
+ * Create a validator that ensures a value is one of the allowed values.
834
+ *
835
+ * @example
836
+ * const validate = oneOf(['pending', 'approved', 'rejected']);
837
+ * validate('approved'); // ok("approved")
838
+ * validate('unknown'); // err([{ path: [], message: 'Value must be one of: pending, approved, rejected' }])
839
+ *
840
+ * @param allowedValues - Array of acceptable values
841
+ * @param message - Custom error message
842
+ * @returns A validator that checks if a value is in the allowed list
843
+ */
505
844
  function oneOf(allowedValues, message = `Value must be one of: ${allowedValues.join(", ")}`) {
506
- return (value, path = []) => {
507
- if (!allowedValues.includes(value)) {
508
- return err([{ path, message }]);
509
- }
510
- return ok(value);
511
- };
512
- }
845
+ return (value, path = []) => {
846
+ if (!allowedValues.includes(value)) return err([{
847
+ path,
848
+ message
849
+ }]);
850
+ return ok(value);
851
+ };
852
+ }
853
+ /**
854
+ * Create a validator that ensures a value is a string and one of the allowed enum values.
855
+ *
856
+ * @example
857
+ * const validate = stringEnum(['admin', 'user']);
858
+ * validate('admin'); // ok("admin")
859
+ * validate(42); // err([{ path: [], message: 'Value must be a string' }])
860
+ * validate('other'); // err([{ path: [], message: 'Value must be one of: admin, user' }])
861
+ *
862
+ * @param allowedValues - Array of acceptable string enum values
863
+ * @param message - Custom error message
864
+ * @returns A validator that checks if a value is a string and in the allowed list
865
+ */
513
866
  function stringEnum(allowedValues, message = `Value must be one of: ${allowedValues.join(", ")}`) {
514
- return chain(string("Value must be a string"), (value, path = []) => {
515
- if (!allowedValues.includes(value)) {
516
- return err([{ path, message }]);
517
- }
518
- return ok(value);
519
- });
867
+ return chain(string("Value must be a string"), (value, path = []) => {
868
+ if (!allowedValues.includes(value)) return err([{
869
+ path,
870
+ message
871
+ }]);
872
+ return ok(value);
873
+ });
520
874
  }
521
-
522
875
  // src/schema/tuple.ts
523
876
  function tuple(validators) {
524
- return (value, parentPath = []) => {
525
- if (!Array.isArray(value)) {
526
- return err([{ path: parentPath, message: "Expected an array" }]);
527
- }
528
- if (value.length !== validators.length) {
529
- return err([
530
- {
531
- path: parentPath,
532
- message: `Expected tuple of length ${validators.length}, got ${value.length}`
533
- }
534
- ]);
535
- }
536
- const abortEarly = _getAbortEarly();
537
- const allErrors = [];
538
- const validatedItems = Array.from({ length: validators.length });
539
- const pendingResults = [];
540
- for (const [i, validator] of validators.entries()) {
541
- if (abortEarly && allErrors.length > 0) break;
542
- const itemPath = [...parentPath, i.toString()];
543
- const item = value.at(i);
544
- const result = validator(item, itemPath);
545
- if (result instanceof Promise) {
546
- if (abortEarly && allErrors.length > 0) continue;
547
- const index = i;
548
- pendingResults.push(
549
- result.then((r) => {
550
- if (isOk(r)) {
551
- validatedItems[index] = r.value;
552
- } else {
553
- allErrors.push(...r.error);
554
- }
555
- })
556
- );
557
- } else if (isOk(result)) {
558
- validatedItems[i] = result.value;
559
- } else {
560
- allErrors.push(...result.error);
561
- if (abortEarly) break;
562
- }
563
- }
564
- if (pendingResults.length > 0) {
565
- return Promise.all(pendingResults).then(() => {
566
- if (allErrors.length > 0) return err(allErrors);
567
- return ok(validatedItems);
568
- });
569
- }
570
- if (allErrors.length > 0) return err(allErrors);
571
- return ok(validatedItems);
572
- };
877
+ return (value, parentPath = []) => {
878
+ if (!Array.isArray(value)) return err([{
879
+ path: parentPath,
880
+ message: "Expected an array"
881
+ }]);
882
+ if (value.length !== validators.length) return err([{
883
+ path: parentPath,
884
+ message: `Expected tuple of length ${validators.length}, got ${value.length}`
885
+ }]);
886
+ const abortEarly = _getAbortEarly();
887
+ const allErrors = [];
888
+ const validatedItems = Array.from({ length: validators.length });
889
+ const pendingResults = [];
890
+ for (const [i, validator] of validators.entries()) {
891
+ if (abortEarly && allErrors.length > 0) break;
892
+ const itemPath = [...parentPath, i.toString()];
893
+ const result = validator(value.at(i), itemPath);
894
+ if (result instanceof Promise) {
895
+ if (abortEarly && allErrors.length > 0) continue;
896
+ const index = i;
897
+ pendingResults.push(result.then((r) => {
898
+ if (isOk(r)) validatedItems[index] = r.value;
899
+ else allErrors.push(...r.error);
900
+ }));
901
+ } else if (isOk(result)) validatedItems[i] = result.value;
902
+ else {
903
+ allErrors.push(...result.error);
904
+ if (abortEarly) break;
905
+ }
906
+ }
907
+ if (pendingResults.length > 0) return Promise.all(pendingResults).then(() => {
908
+ if (allErrors.length > 0) return err(allErrors);
909
+ return ok(validatedItems);
910
+ });
911
+ if (allErrors.length > 0) return err(allErrors);
912
+ return ok(validatedItems);
913
+ };
573
914
  }
574
915
  function tupleOf(elementValidator, length) {
575
- return (value, parentPath = []) => {
576
- if (!Array.isArray(value)) {
577
- return err([{ path: parentPath, message: "Expected an array" }]);
578
- }
579
- if (value.length !== length) {
580
- return err([
581
- {
582
- path: parentPath,
583
- message: `Expected tuple of length ${length}, got ${value.length}`
584
- }
585
- ]);
586
- }
587
- const abortEarly = _getAbortEarly();
588
- const allErrors = [];
589
- const validatedItems = Array.from({ length });
590
- const pendingResults = [];
591
- for (const [i, item] of value.entries()) {
592
- if (abortEarly && allErrors.length > 0) break;
593
- const itemPath = [...parentPath, i.toString()];
594
- const result = elementValidator(item, itemPath);
595
- if (result instanceof Promise) {
596
- if (abortEarly && allErrors.length > 0) continue;
597
- const index = i;
598
- pendingResults.push(
599
- result.then((r) => {
600
- if (isOk(r)) {
601
- validatedItems[index] = r.value;
602
- } else {
603
- allErrors.push(...r.error);
604
- }
605
- })
606
- );
607
- } else if (isOk(result)) {
608
- validatedItems[i] = result.value;
609
- } else {
610
- allErrors.push(...result.error);
611
- if (abortEarly) break;
612
- }
613
- }
614
- if (pendingResults.length > 0) {
615
- return Promise.all(pendingResults).then(() => {
616
- if (allErrors.length > 0) return err(allErrors);
617
- return ok(validatedItems);
618
- });
619
- }
620
- if (allErrors.length > 0) return err(allErrors);
621
- return ok(validatedItems);
622
- };
916
+ return (value, parentPath = []) => {
917
+ if (!Array.isArray(value)) return err([{
918
+ path: parentPath,
919
+ message: "Expected an array"
920
+ }]);
921
+ if (value.length !== length) return err([{
922
+ path: parentPath,
923
+ message: `Expected tuple of length ${length}, got ${value.length}`
924
+ }]);
925
+ const abortEarly = _getAbortEarly();
926
+ const allErrors = [];
927
+ const validatedItems = Array.from({ length });
928
+ const pendingResults = [];
929
+ for (const [i, item] of value.entries()) {
930
+ if (abortEarly && allErrors.length > 0) break;
931
+ const result = elementValidator(item, [...parentPath, i.toString()]);
932
+ if (result instanceof Promise) {
933
+ if (abortEarly && allErrors.length > 0) continue;
934
+ const index = i;
935
+ pendingResults.push(result.then((r) => {
936
+ if (isOk(r)) validatedItems[index] = r.value;
937
+ else allErrors.push(...r.error);
938
+ }));
939
+ } else if (isOk(result)) validatedItems[i] = result.value;
940
+ else {
941
+ allErrors.push(...result.error);
942
+ if (abortEarly) break;
943
+ }
944
+ }
945
+ if (pendingResults.length > 0) return Promise.all(pendingResults).then(() => {
946
+ if (allErrors.length > 0) return err(allErrors);
947
+ return ok(validatedItems);
948
+ });
949
+ if (allErrors.length > 0) return err(allErrors);
950
+ return ok(validatedItems);
951
+ };
623
952
  }
624
-
625
953
  // src/schema/number.ts
954
+ /**
955
+ * Create a validator that ensures a value is a number and not NaN.
956
+ *
957
+ * @example
958
+ * const validate = number();
959
+ * validate(25); // ok(25)
960
+ * validate('not a number'); // err([{ path: [], message: 'Must be a number' }])
961
+ *
962
+ * @param message - Custom error message
963
+ * @returns A validator that checks if a value is a number
964
+ */
626
965
  function number(message = "Must be a number") {
627
- return (value, path = []) => {
628
- if (typeof value !== "number" || Number.isNaN(value)) {
629
- return err([{ path, message }]);
630
- }
631
- return ok(value);
632
- };
633
- }
966
+ return (value, path = []) => {
967
+ if (typeof value !== "number" || Number.isNaN(value)) return err([{
968
+ path,
969
+ message
970
+ }]);
971
+ return ok(value);
972
+ };
973
+ }
974
+ /**
975
+ * Create a validator that ensures a number is at least a minimum value.
976
+ *
977
+ * @example
978
+ * const validate = min(18);
979
+ * validate(21); // ok(21)
980
+ * validate(16); // err([{ path: [], message: 'Must be at least 18' }])
981
+ *
982
+ * @param value - The minimum value (inclusive)
983
+ * @param message - Custom error message
984
+ * @returns A validator that checks if a number is at least the minimum
985
+ */
634
986
  function min(value, message = `Must be at least ${value}`) {
635
- return (input, path = []) => {
636
- if (input < value) {
637
- return err([{ path, message }]);
638
- }
639
- return ok(input);
640
- };
641
- }
987
+ return (input, path = []) => {
988
+ if (input < value) return err([{
989
+ path,
990
+ message
991
+ }]);
992
+ return ok(input);
993
+ };
994
+ }
995
+ /**
996
+ * Create a validator that ensures a number is at most a maximum value.
997
+ *
998
+ * @example
999
+ * const validate = max(100);
1000
+ * validate(75); // ok(75)
1001
+ * validate(150); // err([{ path: [], message: 'Must be at most 100' }])
1002
+ *
1003
+ * @param value - The maximum value (inclusive)
1004
+ * @param message - Custom error message
1005
+ * @returns A validator that checks if a number is at most the maximum
1006
+ */
642
1007
  function max(value, message = `Must be at most ${value}`) {
643
- return (input, path = []) => {
644
- if (input > value) {
645
- return err([{ path, message }]);
646
- }
647
- return ok(input);
648
- };
649
- }
650
- function between(min2, max2, message = `Must be between ${min2} and ${max2}`) {
651
- return (input, path = []) => {
652
- if (input < min2 || input > max2) {
653
- return err([{ path, message }]);
654
- }
655
- return ok(input);
656
- };
657
- }
1008
+ return (input, path = []) => {
1009
+ if (input > value) return err([{
1010
+ path,
1011
+ message
1012
+ }]);
1013
+ return ok(input);
1014
+ };
1015
+ }
1016
+ /**
1017
+ * Create a validator that ensures a number is between a minimum and maximum (inclusive).
1018
+ *
1019
+ * @example
1020
+ * const validate = between(1, 10);
1021
+ * validate(7); // ok(7)
1022
+ * validate(15); // err([{ path: [], message: 'Must be between 1 and 10' }])
1023
+ *
1024
+ * @param min - The minimum value (inclusive)
1025
+ * @param max - The maximum value (inclusive)
1026
+ * @param message - Custom error message
1027
+ * @returns A validator that checks if a number is between min and max
1028
+ */
1029
+ function between(min, max, message = `Must be between ${min} and ${max}`) {
1030
+ return (input, path = []) => {
1031
+ if (input < min || input > max) return err([{
1032
+ path,
1033
+ message
1034
+ }]);
1035
+ return ok(input);
1036
+ };
1037
+ }
1038
+ /**
1039
+ * Create a validator that ensures a number is an integer.
1040
+ *
1041
+ * @example
1042
+ * const validate = integer();
1043
+ * validate(42); // ok(42)
1044
+ * validate(3.14); // err([{ path: [], message: 'Must be an integer' }])
1045
+ *
1046
+ * @param message - Custom error message
1047
+ * @returns A validator that checks if a number is an integer
1048
+ */
658
1049
  function integer(message = "Must be an integer") {
659
- return (value, path = []) => {
660
- if (!Number.isInteger(value)) {
661
- return err([{ path, message }]);
662
- }
663
- return ok(value);
664
- };
665
- }
1050
+ return (value, path = []) => {
1051
+ if (!Number.isInteger(value)) return err([{
1052
+ path,
1053
+ message
1054
+ }]);
1055
+ return ok(value);
1056
+ };
1057
+ }
1058
+ /**
1059
+ * Create a validator that ensures a number is positive (greater than zero).
1060
+ *
1061
+ * @example
1062
+ * const validate = positive();
1063
+ * validate(29.99); // ok(29.99)
1064
+ * validate(0); // err([{ path: [], message: 'Must be a positive number' }])
1065
+ *
1066
+ * @param message - Custom error message
1067
+ * @returns A validator that checks if a number is positive
1068
+ */
666
1069
  function positive(message = "Must be a positive number") {
667
- return (value, path = []) => {
668
- if (value <= 0) {
669
- return err([{ path, message }]);
670
- }
671
- return ok(value);
672
- };
673
- }
1070
+ return (value, path = []) => {
1071
+ if (value <= 0) return err([{
1072
+ path,
1073
+ message
1074
+ }]);
1075
+ return ok(value);
1076
+ };
1077
+ }
1078
+ /**
1079
+ * Create a validator that ensures a number is negative (less than zero).
1080
+ *
1081
+ * @example
1082
+ * const validate = negative();
1083
+ * validate(-5); // ok(-5)
1084
+ * validate(0); // err([{ path: [], message: 'Must be a negative number' }])
1085
+ *
1086
+ * @param message - Custom error message
1087
+ * @returns A validator that checks if a number is negative
1088
+ */
674
1089
  function negative(message = "Must be a negative number") {
675
- return (value, path = []) => {
676
- if (value >= 0) {
677
- return err([{ path, message }]);
678
- }
679
- return ok(value);
680
- };
681
- }
1090
+ return (value, path = []) => {
1091
+ if (value >= 0) return err([{
1092
+ path,
1093
+ message
1094
+ }]);
1095
+ return ok(value);
1096
+ };
1097
+ }
1098
+ /**
1099
+ * Create a validator that ensures a number is not zero.
1100
+ *
1101
+ * @example
1102
+ * const validate = nonZero();
1103
+ * validate(5); // ok(5)
1104
+ * validate(0); // err([{ path: [], message: 'Must not be zero' }])
1105
+ *
1106
+ * @param message - Custom error message
1107
+ * @returns A validator that checks if a number is not zero
1108
+ */
682
1109
  function nonZero(message = "Must not be zero") {
683
- return (value, path = []) => {
684
- if (value === 0) {
685
- return err([{ path, message }]);
686
- }
687
- return ok(value);
688
- };
689
- }
1110
+ return (value, path = []) => {
1111
+ if (value === 0) return err([{
1112
+ path,
1113
+ message
1114
+ }]);
1115
+ return ok(value);
1116
+ };
1117
+ }
1118
+ /**
1119
+ * Create a validator that ensures a number is divisible by a specific divisor.
1120
+ *
1121
+ * @example
1122
+ * const validate = divisibleBy(5);
1123
+ * validate(15); // ok(15)
1124
+ * validate(12); // err([{ path: [], message: 'Must be divisible by 5' }])
1125
+ *
1126
+ * @param divisor - The number that the input must be divisible by
1127
+ * @param message - Custom error message
1128
+ * @returns A validator that checks if a number is divisible by the divisor
1129
+ */
690
1130
  function divisibleBy(divisor, message = `Must be divisible by ${divisor}`) {
691
- return (value, path = []) => {
692
- if (value % divisor !== 0) {
693
- return err([{ path, message }]);
694
- }
695
- return ok(value);
696
- };
697
- }
1131
+ return (value, path = []) => {
1132
+ if (value % divisor !== 0) return err([{
1133
+ path,
1134
+ message
1135
+ }]);
1136
+ return ok(value);
1137
+ };
1138
+ }
1139
+ /**
1140
+ * Create a validator that ensures a number has at most the specified decimal places.
1141
+ *
1142
+ * @example
1143
+ * const validate = precision(2);
1144
+ * validate(10.99); // ok(10.99)
1145
+ * validate(10.999); // err([{ path: [], message: 'Must have at most 2 decimal places' }])
1146
+ *
1147
+ * @param maxDecimalPlaces - The maximum number of decimal places allowed
1148
+ * @param message - Custom error message
1149
+ * @returns A validator that checks the number's decimal precision
1150
+ */
698
1151
  function precision(maxDecimalPlaces, message = `Must have at most ${maxDecimalPlaces} decimal places`) {
699
- return (value, path = []) => {
700
- const str = value.toString();
701
- const decimalPlaces = (str.split(".", 2)[1] || "").length;
702
- if (decimalPlaces > maxDecimalPlaces) {
703
- return err([{ path, message }]);
704
- }
705
- return ok(value);
706
- };
707
- }
1152
+ return (value, path = []) => {
1153
+ if ((value.toString().split(".", 2)[1] || "").length > maxDecimalPlaces) return err([{
1154
+ path,
1155
+ message
1156
+ }]);
1157
+ return ok(value);
1158
+ };
1159
+ }
1160
+ /**
1161
+ * Create a validator that ensures a number is finite (not Infinity or -Infinity).
1162
+ *
1163
+ * @example
1164
+ * const validate = finite();
1165
+ * validate(42); // ok(42)
1166
+ * validate(Infinity); // err([{ path: [], message: 'Must be a finite number' }])
1167
+ *
1168
+ * @param message - Custom error message
1169
+ * @returns A validator that checks if a number is finite
1170
+ */
708
1171
  function finite(message = "Must be a finite number") {
709
- return (value, path = []) => {
710
- if (!Number.isFinite(value)) {
711
- return err([{ path, message }]);
712
- }
713
- return ok(value);
714
- };
1172
+ return (value, path = []) => {
1173
+ if (!Number.isFinite(value)) return err([{
1174
+ path,
1175
+ message
1176
+ }]);
1177
+ return ok(value);
1178
+ };
715
1179
  }
716
-
717
1180
  // src/schema/parsers.ts
1181
+ /**
1182
+ * Create a validator that parses input into a number.
1183
+ * Accepts both numbers and string representations of numbers.
1184
+ *
1185
+ * @example
1186
+ * const validate = parseNumber();
1187
+ * validate('25'); // ok(25)
1188
+ * validate(42); // ok(42)
1189
+ * validate('not a number'); // err([{ path: [], message: 'Must be a valid number' }])
1190
+ *
1191
+ * @param message - Custom error message
1192
+ * @returns A validator that parses and validates numbers
1193
+ */
718
1194
  function parseNumber(message = "Must be a valid number") {
719
- return (value, path = []) => {
720
- if (typeof value === "number") {
721
- return ok(value);
722
- }
723
- if (typeof value === "string") {
724
- const trimmed = value.trim();
725
- if (trimmed === "") {
726
- return err([{ path, message }]);
727
- }
728
- const num = Number(trimmed);
729
- if (!Number.isNaN(num)) {
730
- return ok(num);
731
- }
732
- }
733
- return err([{ path, message }]);
734
- };
735
- }
1195
+ return (value, path = []) => {
1196
+ if (typeof value === "number") return ok(value);
1197
+ if (typeof value === "string") {
1198
+ const trimmed = value.trim();
1199
+ if (trimmed === "") return err([{
1200
+ path,
1201
+ message
1202
+ }]);
1203
+ const num = Number(trimmed);
1204
+ if (!Number.isNaN(num)) return ok(num);
1205
+ }
1206
+ return err([{
1207
+ path,
1208
+ message
1209
+ }]);
1210
+ };
1211
+ }
1212
+ /**
1213
+ * Create a validator that parses input into a BigInt.
1214
+ * Accepts BigInt values, strings, and integer numbers.
1215
+ *
1216
+ * @example
1217
+ * const validate = parseBigInt();
1218
+ * validate("9007199254740993"); // ok(9007199254740993n)
1219
+ * validate(123n); // ok(123n)
1220
+ * validate(42); // ok(42n)
1221
+ *
1222
+ * @param message - Custom error message
1223
+ * @returns A validator that parses and validates BigInt values
1224
+ */
736
1225
  function parseBigInt(message = "Must be a valid BigInt") {
737
- return (value, path = []) => {
738
- if (typeof value === "bigint") {
739
- return ok(value);
740
- }
741
- if (typeof value === "string" || typeof value === "number") {
742
- try {
743
- if (typeof value === "number" && !Number.isInteger(value)) {
744
- return err([
745
- {
746
- path,
747
- message: "Cannot convert non-integer number to BigInt"
748
- }
749
- ]);
750
- }
751
- const bigIntValue = BigInt(value);
752
- return ok(bigIntValue);
753
- } catch {
754
- return err([{ path, message }]);
755
- }
756
- }
757
- return err([{ path, message }]);
758
- };
759
- }
1226
+ return (value, path = []) => {
1227
+ if (typeof value === "bigint") return ok(value);
1228
+ if (typeof value === "string" || typeof value === "number") try {
1229
+ if (typeof value === "number" && !Number.isInteger(value)) return err([{
1230
+ path,
1231
+ message: "Cannot convert non-integer number to BigInt"
1232
+ }]);
1233
+ const bigIntValue = BigInt(value);
1234
+ return ok(bigIntValue);
1235
+ } catch {
1236
+ return err([{
1237
+ path,
1238
+ message
1239
+ }]);
1240
+ }
1241
+ return err([{
1242
+ path,
1243
+ message
1244
+ }]);
1245
+ };
1246
+ }
1247
+ /**
1248
+ * Create a validator that parses input into enum values.
1249
+ * Handles string/number to enum conversions with flexible matching.
1250
+ *
1251
+ * @example
1252
+ * enum Status { Pending = "PENDING", Approved = "APPROVED" }
1253
+ * const validate = parseEnum(Status);
1254
+ * validate("PENDING"); // ok("PENDING")
1255
+ * validate("pending"); // ok("PENDING") — case-insensitive key match
1256
+ *
1257
+ * @param enumObject - The enum object to parse values into
1258
+ * @param message - Custom error message
1259
+ * @returns A validator that parses to enum values
1260
+ */
760
1261
  function parseEnum(enumObject, message = `Must be a valid enum value`) {
761
- return (value, path = []) => {
762
- const enumEntries = Object.entries(enumObject).filter(
763
- ([key]) => Number.isNaN(Number(key)) || !Number.isInteger(Number(key))
764
- );
765
- const enumValues = enumEntries.map(([, val]) => val);
766
- if (enumValues.includes(value)) {
767
- return ok(value);
768
- }
769
- if (typeof value === "string") {
770
- const parsed = Number(value);
771
- if (!Number.isNaN(parsed) && enumValues.includes(parsed)) {
772
- return ok(parsed);
773
- }
774
- const exactEntry = enumEntries.find(([key]) => key === value);
775
- if (exactEntry) {
776
- return ok(exactEntry[1]);
777
- }
778
- const lowerValue = value.toLowerCase();
779
- const caseInsensitiveEntry = enumEntries.find(([key]) => key.toLowerCase() === lowerValue);
780
- if (caseInsensitiveEntry) {
781
- return ok(caseInsensitiveEntry[1]);
782
- }
783
- }
784
- return err([
785
- {
786
- path,
787
- message
788
- }
789
- ]);
790
- };
791
- }
1262
+ return (value, path = []) => {
1263
+ const enumEntries = Object.entries(enumObject).filter(([key]) => Number.isNaN(Number(key)) || !Number.isInteger(Number(key)));
1264
+ const enumValues = enumEntries.map(([, val]) => val);
1265
+ if (enumValues.includes(value)) return ok(value);
1266
+ if (typeof value === "string") {
1267
+ const parsed = Number(value);
1268
+ if (!Number.isNaN(parsed) && enumValues.includes(parsed)) return ok(parsed);
1269
+ const exactEntry = enumEntries.find(([key]) => key === value);
1270
+ if (exactEntry) return ok(exactEntry[1]);
1271
+ const lowerValue = value.toLowerCase();
1272
+ const caseInsensitiveEntry = enumEntries.find(([key]) => key.toLowerCase() === lowerValue);
1273
+ if (caseInsensitiveEntry) return ok(caseInsensitiveEntry[1]);
1274
+ }
1275
+ return err([{
1276
+ path,
1277
+ message
1278
+ }]);
1279
+ };
1280
+ }
1281
+ /**
1282
+ * Create a validator that parses input into a Date object.
1283
+ * Accepts Date objects, date strings, and numeric timestamps.
1284
+ *
1285
+ * @example
1286
+ * const validate = parseDate();
1287
+ * validate('1990-05-15'); // ok(Date)
1288
+ * validate(1621036800000); // ok(Date)
1289
+ * validate('not a date'); // err([{ path: [], message: 'Must be a valid date' }])
1290
+ *
1291
+ * @param message - Custom error message
1292
+ * @returns A validator that parses and validates dates
1293
+ */
792
1294
  function parseDate(message = "Must be a valid date") {
793
- return (value, path = []) => {
794
- if (value instanceof Date) {
795
- return ok(value);
796
- }
797
- let dateValue;
798
- if (typeof value === "string" || typeof value === "number") {
799
- dateValue = new Date(value);
800
- } else {
801
- return err([{ path, message }]);
802
- }
803
- if (Number.isNaN(dateValue.getTime())) {
804
- return err([{ path, message }]);
805
- }
806
- return ok(dateValue);
807
- };
808
- }
1295
+ return (value, path = []) => {
1296
+ if (value instanceof Date) return ok(value);
1297
+ let dateValue;
1298
+ if (typeof value === "string" || typeof value === "number") dateValue = new Date(value);
1299
+ else return err([{
1300
+ path,
1301
+ message
1302
+ }]);
1303
+ if (Number.isNaN(dateValue.getTime())) return err([{
1304
+ path,
1305
+ message
1306
+ }]);
1307
+ return ok(dateValue);
1308
+ };
1309
+ }
1310
+ /**
1311
+ * Create a validator that parses input into a boolean.
1312
+ * Accepts booleans, 0/1, and strings like 'true'/'false', 'yes'/'no'.
1313
+ *
1314
+ * @example
1315
+ * const validate = parseBool();
1316
+ * validate('yes'); // ok(true)
1317
+ * validate('false'); // ok(false)
1318
+ * validate(1); // ok(true)
1319
+ * validate('maybe'); // err([{ path: [], message: 'Must be a valid boolean value' }])
1320
+ *
1321
+ * @param message - Custom error message
1322
+ * @returns A validator that parses and validates booleans
1323
+ */
809
1324
  function parseBool(message = "Must be a valid boolean value") {
810
- return (value, path = []) => {
811
- if (typeof value === "boolean") {
812
- return ok(value);
813
- }
814
- if (typeof value === "string") {
815
- const normalized = value.toLowerCase().trim();
816
- if (["true", "1", "yes"].includes(normalized)) {
817
- return ok(true);
818
- }
819
- if (["false", "0", "no"].includes(normalized)) {
820
- return ok(false);
821
- }
822
- }
823
- if (typeof value === "number") {
824
- if (value === 1) return ok(true);
825
- if (value === 0) return ok(false);
826
- }
827
- return err([{ path, message }]);
828
- };
829
- }
1325
+ return (value, path = []) => {
1326
+ if (typeof value === "boolean") return ok(value);
1327
+ if (typeof value === "string") {
1328
+ const normalized = value.toLowerCase().trim();
1329
+ if ([
1330
+ "true",
1331
+ "1",
1332
+ "yes"
1333
+ ].includes(normalized)) return ok(true);
1334
+ if ([
1335
+ "false",
1336
+ "0",
1337
+ "no"
1338
+ ].includes(normalized)) return ok(false);
1339
+ }
1340
+ if (typeof value === "number") {
1341
+ if (value === 1) return ok(true);
1342
+ if (value === 0) return ok(false);
1343
+ }
1344
+ return err([{
1345
+ path,
1346
+ message
1347
+ }]);
1348
+ };
1349
+ }
1350
+ /**
1351
+ * Create a validator that parses input into a string.
1352
+ * Accepts strings and any value convertible to string, except null and undefined.
1353
+ *
1354
+ * @example
1355
+ * const validate = parseString();
1356
+ * validate(12345); // ok("12345")
1357
+ * validate('hello'); // ok("hello")
1358
+ * validate(null); // err([{ path: [], message: 'Must be convertible to string' }])
1359
+ *
1360
+ * @param message - Custom error message
1361
+ * @returns A validator that parses and validates strings
1362
+ */
830
1363
  function parseString(message = "Must be convertible to string") {
831
- return (value, path = []) => {
832
- if (typeof value === "string") {
833
- return ok(value);
834
- }
835
- if (value === null || value === void 0) {
836
- return err([{ path, message }]);
837
- }
838
- return ok(String(value));
839
- };
840
- }
1364
+ return (value, path = []) => {
1365
+ if (typeof value === "string") return ok(value);
1366
+ if (value === null || value === void 0) return err([{
1367
+ path,
1368
+ message
1369
+ }]);
1370
+ return ok(String(value));
1371
+ };
1372
+ }
1373
+ /**
1374
+ * Create a validator that parses JSON strings into objects.
1375
+ * Accepts JSON strings or already-parsed objects.
1376
+ *
1377
+ * @example
1378
+ * const validate = parseJSON();
1379
+ * validate('{"name":"John"}'); // ok({ name: "John" })
1380
+ * validate({ name: 'John' }); // ok({ name: "John" })
1381
+ * validate('{invalid}'); // err([{ path: [], message: 'Must be valid JSON' }])
1382
+ *
1383
+ * @param message - Custom error message
1384
+ * @returns A validator that parses and validates JSON
1385
+ */
841
1386
  function parseJSON(message = "Must be valid JSON") {
842
- return (value, path = []) => {
843
- if (typeof value === "string") {
844
- return mapErr(
845
- fromTry(() => JSON.parse(value)),
846
- () => [{ path, message }]
847
- );
848
- }
849
- if (typeof value === "object" && value !== null) {
850
- return ok(value);
851
- }
852
- return err([{ path, message }]);
853
- };
854
- }
1387
+ return (value, path = []) => {
1388
+ if (typeof value === "string") return mapErr(fromTry(() => JSON.parse(value)), () => [{
1389
+ path,
1390
+ message
1391
+ }]);
1392
+ if (typeof value === "object" && value !== null) return ok(value);
1393
+ return err([{
1394
+ path,
1395
+ message
1396
+ }]);
1397
+ };
1398
+ }
1399
+ /**
1400
+ * Create a validator that parses ISO date strings (YYYY-MM-DD) into Date objects.
1401
+ * Performs strict validation of the date format and validity.
1402
+ *
1403
+ * @example
1404
+ * const validate = parseISODate();
1405
+ * validate('2021-05-15'); // ok(Date)
1406
+ * validate('15/05/2021'); // err([{ path: [], message: 'Must be a valid ISO date string' }])
1407
+ * validate('2021-02-30'); // err(...) — invalid calendar date
1408
+ *
1409
+ * @param message - Custom error message
1410
+ * @returns A validator that parses and validates ISO date strings
1411
+ */
855
1412
  function parseISODate(message = "Must be a valid ISO date string") {
856
- return (value, path = []) => {
857
- if (typeof value !== "string") {
858
- return err([{ path, message }]);
859
- }
860
- if (!/^\d{4}-\d{2}-\d{2}/.test(value)) {
861
- return err([{ path, message }]);
862
- }
863
- const date2 = new Date(value);
864
- if (Number.isNaN(date2.getTime())) {
865
- return err([{ path, message }]);
866
- }
867
- const originalMonth = value.slice(5, 7);
868
- const originalDay = value.slice(8, 10);
869
- const parsedMonth = String(date2.getUTCMonth() + 1).padStart(2, "0");
870
- const parsedDay = String(date2.getUTCDate()).padStart(2, "0");
871
- if (originalMonth !== parsedMonth || originalDay !== parsedDay) {
872
- return err([{ path, message }]);
873
- }
874
- return ok(date2);
875
- };
876
- }
1413
+ return (value, path = []) => {
1414
+ if (typeof value !== "string") return err([{
1415
+ path,
1416
+ message
1417
+ }]);
1418
+ if (!/^\d{4}-\d{2}-\d{2}/.test(value)) return err([{
1419
+ path,
1420
+ message
1421
+ }]);
1422
+ const date = new Date(value);
1423
+ if (Number.isNaN(date.getTime())) return err([{
1424
+ path,
1425
+ message
1426
+ }]);
1427
+ const originalMonth = value.slice(5, 7);
1428
+ const originalDay = value.slice(8, 10);
1429
+ const parsedMonth = String(date.getUTCMonth() + 1).padStart(2, "0");
1430
+ const parsedDay = String(date.getUTCDate()).padStart(2, "0");
1431
+ if (originalMonth !== parsedMonth || originalDay !== parsedDay) return err([{
1432
+ path,
1433
+ message
1434
+ }]);
1435
+ return ok(date);
1436
+ };
1437
+ }
1438
+ /**
1439
+ * Create a validator that parses string URLs into URL objects.
1440
+ *
1441
+ * @example
1442
+ * const validate = parseURL();
1443
+ * validate('https://example.com'); // ok(URL)
1444
+ * validate('not-a-url'); // err([{ path: [], message: 'Must be a valid URL' }])
1445
+ *
1446
+ * @param message - Custom error message
1447
+ * @returns A validator that parses and validates URLs
1448
+ */
877
1449
  function parseURL(message = "Must be a valid URL") {
878
- return (value, path = []) => {
879
- if (typeof value !== "string") {
880
- return err([{ path, message }]);
881
- }
882
- try {
883
- return ok(new URL(value));
884
- } catch {
885
- return err([{ path, message }]);
886
- }
887
- };
1450
+ return (value, path = []) => {
1451
+ if (typeof value !== "string") return err([{
1452
+ path,
1453
+ message
1454
+ }]);
1455
+ try {
1456
+ return ok(new URL(value));
1457
+ } catch {
1458
+ return err([{
1459
+ path,
1460
+ message
1461
+ }]);
1462
+ }
1463
+ };
888
1464
  }
889
-
890
1465
  // src/schema/date.ts
1466
+ /**
1467
+ * Create a validator that ensures a value is a valid Date object.
1468
+ *
1469
+ * @example
1470
+ * const validate = date();
1471
+ * validate(new Date()); // ok(Date)
1472
+ * validate('not a date'); // err([{ path: [], message: 'Must be a Date object' }])
1473
+ *
1474
+ * @param message - Custom error message
1475
+ * @returns A validator that checks if value is a valid Date
1476
+ */
891
1477
  function date(message = "Must be a Date object") {
892
- return (value, path = []) => {
893
- if (!(value instanceof Date)) {
894
- return err([{ path, message }]);
895
- }
896
- if (Number.isNaN(value.getTime())) {
897
- return err([
898
- {
899
- path,
900
- message: "Invalid Date"
901
- }
902
- ]);
903
- }
904
- return ok(value);
905
- };
906
- }
907
- function dateRange(min2, max2, message = `Must be between ${min2.toISOString().split("T", 1)[0]} and ${max2.toISOString().split("T", 1)[0]}`) {
908
- return (value, path = []) => {
909
- if (value < min2 || value > max2) {
910
- return err([{ path, message }]);
911
- }
912
- return ok(value);
913
- };
914
- }
1478
+ return (value, path = []) => {
1479
+ if (!(value instanceof Date)) return err([{
1480
+ path,
1481
+ message
1482
+ }]);
1483
+ if (Number.isNaN(value.getTime())) return err([{
1484
+ path,
1485
+ message: "Invalid Date"
1486
+ }]);
1487
+ return ok(value);
1488
+ };
1489
+ }
1490
+ /**
1491
+ * Create a validator that ensures a Date is within a specified range.
1492
+ *
1493
+ * @example
1494
+ * const validate = dateRange(new Date('2023-01-01'), new Date('2023-12-31'));
1495
+ * validate(new Date('2023-06-15')); // ok(Date)
1496
+ * validate(new Date('2024-01-01')); // err(...)
1497
+ *
1498
+ * @param min - The minimum valid date (inclusive)
1499
+ * @param max - The maximum valid date (inclusive)
1500
+ * @param message - Custom error message
1501
+ * @returns A validator that checks if a date is between min and max
1502
+ */
1503
+ function dateRange(min, max, message = `Must be between ${min.toISOString().split("T", 1)[0]} and ${max.toISOString().split("T", 1)[0]}`) {
1504
+ return (value, path = []) => {
1505
+ if (value < min || value > max) return err([{
1506
+ path,
1507
+ message
1508
+ }]);
1509
+ return ok(value);
1510
+ };
1511
+ }
1512
+ /**
1513
+ * Create a validator that ensures a Date is in the past.
1514
+ *
1515
+ * @example
1516
+ * const validate = pastDate();
1517
+ * validate(new Date('1990-01-01')); // ok(Date)
1518
+ *
1519
+ * @param message - Custom error message
1520
+ * @returns A validator that checks if a date is in the past
1521
+ */
915
1522
  function pastDate(message = "Must be a date in the past") {
916
- return (value, path = []) => {
917
- if (value >= /* @__PURE__ */ new Date()) {
918
- return err([{ path, message }]);
919
- }
920
- return ok(value);
921
- };
922
- }
1523
+ return (value, path = []) => {
1524
+ if (value >= /* @__PURE__ */ new Date()) return err([{
1525
+ path,
1526
+ message
1527
+ }]);
1528
+ return ok(value);
1529
+ };
1530
+ }
1531
+ /**
1532
+ * Create a validator that ensures a Date is in the future.
1533
+ *
1534
+ * @example
1535
+ * const validate = futureDate();
1536
+ * const nextYear = new Date();
1537
+ * nextYear.setFullYear(nextYear.getFullYear() + 1);
1538
+ * validate(nextYear); // ok(Date)
1539
+ *
1540
+ * @param message - Custom error message
1541
+ * @returns A validator that checks if a date is in the future
1542
+ */
923
1543
  function futureDate(message = "Must be a date in the future") {
924
- return (value, path = []) => {
925
- if (value <= /* @__PURE__ */ new Date()) {
926
- return err([{ path, message }]);
927
- }
928
- return ok(value);
929
- };
930
- }
1544
+ return (value, path = []) => {
1545
+ if (value <= /* @__PURE__ */ new Date()) return err([{
1546
+ path,
1547
+ message
1548
+ }]);
1549
+ return ok(value);
1550
+ };
1551
+ }
1552
+ /**
1553
+ * Create a validator that ensures a Date is today or in the future.
1554
+ * Uses calendar date comparison (ignoring time portions).
1555
+ *
1556
+ * @example
1557
+ * const validate = todayOrFuture();
1558
+ * validate(new Date()); // ok(Date)
1559
+ *
1560
+ * @param message - Custom error message
1561
+ * @returns A validator that checks if a date is today or in the future
1562
+ */
931
1563
  function todayOrFuture(message = "Must be today or a future date") {
932
- const today = /* @__PURE__ */ new Date();
933
- today.setHours(0, 0, 0, 0);
934
- return (value, path = []) => {
935
- if (value < today) {
936
- return err([{ path, message }]);
937
- }
938
- return ok(value);
939
- };
1564
+ const today = /* @__PURE__ */ new Date();
1565
+ today.setHours(0, 0, 0, 0);
1566
+ return (value, path = []) => {
1567
+ if (value < today) return err([{
1568
+ path,
1569
+ message
1570
+ }]);
1571
+ return ok(value);
1572
+ };
940
1573
  }
941
-
942
1574
  // src/schema/boolean.ts
1575
+ /**
1576
+ * Create a validator that ensures a value is a boolean.
1577
+ *
1578
+ * @example
1579
+ * const validate = boolean();
1580
+ * validate(true); // ok(true)
1581
+ * validate('not a boolean'); // err([{ path: [], message: 'Must be a boolean' }])
1582
+ *
1583
+ * @param message - Custom error message
1584
+ * @returns A validator that checks if a value is a boolean
1585
+ */
943
1586
  function boolean(message = "Must be a boolean") {
944
- return (value, path = []) => {
945
- if (typeof value !== "boolean") {
946
- return err([{ path, message }]);
947
- }
948
- return ok(value);
949
- };
950
- }
1587
+ return (value, path = []) => {
1588
+ if (typeof value !== "boolean") return err([{
1589
+ path,
1590
+ message
1591
+ }]);
1592
+ return ok(value);
1593
+ };
1594
+ }
1595
+ /**
1596
+ * Create a validator that ensures a boolean matches the expected value.
1597
+ *
1598
+ * @example
1599
+ * const validate = matches(true);
1600
+ * validate(true); // ok(true)
1601
+ * validate(false); // err([{ path: [], message: 'Value must be true' }])
1602
+ *
1603
+ * @param expected - The expected boolean value
1604
+ * @param message - Custom error message
1605
+ * @returns A validator that confirms the value matches the expected boolean
1606
+ */
951
1607
  function matches(expected, message = `Value must be ${expected}`) {
952
- return (value, path = []) => {
953
- if (value !== expected) {
954
- return err([{ path, message }]);
955
- }
956
- return ok(value);
957
- };
1608
+ return (value, path = []) => {
1609
+ if (value !== expected) return err([{
1610
+ path,
1611
+ message
1612
+ }]);
1613
+ return ok(value);
1614
+ };
958
1615
  }
959
-
960
1616
  // src/schema/union.ts
961
1617
  function union(validators, options) {
962
- const { collectAllErrors = true, errorPrefix } = options || {};
963
- const buildError = (allErrors) => err(
964
- allErrors.flat().map((error) => ({
965
- path: error.path,
966
- message: errorPrefix ? `${errorPrefix}: ${error.message}` : error.message
967
- }))
968
- );
969
- return (value, parentPath = []) => {
970
- if (validators.length === 0) {
971
- return err([{ path: parentPath, message: "No validators provided to union" }]);
972
- }
973
- const allErrors = [];
974
- for (let i = 0; i < validators.length; i++) {
975
- const result = validators[i](value, parentPath);
976
- if (result instanceof Promise) {
977
- return (async () => {
978
- const asyncResult = await result;
979
- if (isOk(asyncResult)) return asyncResult;
980
- allErrors.push(asyncResult.error);
981
- if (!collectAllErrors) return buildError(allErrors);
982
- for (let j = i + 1; j < validators.length; j++) {
983
- const r = await validators[j](value, parentPath);
984
- if (isOk(r)) return r;
985
- allErrors.push(r.error);
986
- if (!collectAllErrors) break;
987
- }
988
- return buildError(allErrors);
989
- })();
990
- }
991
- if (isOk(result)) {
992
- return result;
993
- }
994
- allErrors.push(result.error);
995
- if (!collectAllErrors) {
996
- break;
997
- }
998
- }
999
- return buildError(allErrors);
1000
- };
1618
+ const { collectAllErrors = true, errorPrefix } = options || {};
1619
+ const buildError = (allErrors) => err(allErrors.flat().map((error) => ({
1620
+ path: error.path,
1621
+ message: errorPrefix ? `${errorPrefix}: ${error.message}` : error.message
1622
+ })));
1623
+ return (value, parentPath = []) => {
1624
+ if (validators.length === 0) return err([{
1625
+ path: parentPath,
1626
+ message: "No validators provided to union"
1627
+ }]);
1628
+ const allErrors = [];
1629
+ for (let i = 0; i < validators.length; i++) {
1630
+ const result = validators[i](value, parentPath);
1631
+ if (result instanceof Promise) return (async () => {
1632
+ const asyncResult = await result;
1633
+ if (isOk(asyncResult)) return asyncResult;
1634
+ allErrors.push(asyncResult.error);
1635
+ if (!collectAllErrors) return buildError(allErrors);
1636
+ for (let j = i + 1; j < validators.length; j++) {
1637
+ const r = await validators[j](value, parentPath);
1638
+ if (isOk(r)) return r;
1639
+ allErrors.push(r.error);
1640
+ if (!collectAllErrors) break;
1641
+ }
1642
+ return buildError(allErrors);
1643
+ })();
1644
+ if (isOk(result)) return result;
1645
+ allErrors.push(result.error);
1646
+ if (!collectAllErrors) break;
1647
+ }
1648
+ return buildError(allErrors);
1649
+ };
1001
1650
  }
1002
1651
  function discriminatedUnion(discriminantField, validatorMap, fallbackMessage = `Invalid discriminant value for '${discriminantField}'`) {
1003
- return (value, parentPath = []) => {
1004
- if (value === null || typeof value !== "object") {
1005
- return err([{ path: parentPath, message: "Expected an object" }]);
1006
- }
1007
- const discriminantValue = value[discriminantField];
1008
- if (typeof discriminantValue !== "string") {
1009
- return err([
1010
- {
1011
- path: [...parentPath, discriminantField],
1012
- message: `Missing or invalid discriminant field '${discriminantField}'`
1013
- }
1014
- ]);
1015
- }
1016
- const validator = validatorMap[discriminantValue];
1017
- if (!validator) {
1018
- return err([
1019
- {
1020
- path: [...parentPath, discriminantField],
1021
- message: `${fallbackMessage}: '${discriminantValue}'`
1022
- }
1023
- ]);
1024
- }
1025
- const result = validator(value, parentPath);
1026
- if (result instanceof Promise) {
1027
- return result.then((r) => r);
1028
- }
1029
- return result;
1030
- };
1652
+ return (value, parentPath = []) => {
1653
+ if (value === null || typeof value !== "object") return err([{
1654
+ path: parentPath,
1655
+ message: "Expected an object"
1656
+ }]);
1657
+ const discriminantValue = value[discriminantField];
1658
+ if (typeof discriminantValue !== "string") return err([{
1659
+ path: [...parentPath, discriminantField],
1660
+ message: `Missing or invalid discriminant field '${discriminantField}'`
1661
+ }]);
1662
+ const validator = validatorMap[discriminantValue];
1663
+ if (!validator) return err([{
1664
+ path: [...parentPath, discriminantField],
1665
+ message: `${fallbackMessage}: '${discriminantValue}'`
1666
+ }]);
1667
+ const result = validator(value, parentPath);
1668
+ if (result instanceof Promise) return result.then((r) => r);
1669
+ return result;
1670
+ };
1031
1671
  }
1032
-
1033
1672
  // src/schema/enum.ts
1673
+ /**
1674
+ * Create a validator for TypeScript enum values.
1675
+ * Works with both string and numeric enums.
1676
+ *
1677
+ * @example
1678
+ * enum Status { Pending = "PENDING", Approved = "APPROVED" }
1679
+ * const validate = enumValue(Status);
1680
+ * validate("PENDING"); // ok("PENDING")
1681
+ * validate("INVALID"); // err([{ path: [], message: 'Value must be one of: PENDING, APPROVED' }])
1682
+ *
1683
+ * @example
1684
+ * // With excluded values
1685
+ * const validate = enumValue(Status, "Not allowed", [Status.Pending]);
1686
+ * validate("PENDING"); // err(...)
1687
+ *
1688
+ * @param enumObject - The enum object to validate against
1689
+ * @param message - Custom error message
1690
+ * @param excludedValues - Values to exclude from the valid set
1691
+ * @returns A validator that ensures the value is a valid enum value
1692
+ */
1034
1693
  function enumValue(enumObject, message, excludedValues) {
1035
- return (value, path = []) => {
1036
- const enumValues = Object.values(enumObject);
1037
- if (!enumValues.includes(value)) {
1038
- const defaultMessage = `Value must be one of: ${enumValues.join(", ")}`;
1039
- return err([{ path, message: message || defaultMessage }]);
1040
- }
1041
- if (excludedValues && excludedValues.includes(value)) {
1042
- const defaultMessage = `Selected value is excluded from valid enum values`;
1043
- return err([{ path, message: `${message || defaultMessage}` }]);
1044
- }
1045
- return ok(value);
1046
- };
1694
+ return (value, path = []) => {
1695
+ const enumValues = Object.values(enumObject);
1696
+ if (!enumValues.includes(value)) {
1697
+ const defaultMessage = `Value must be one of: ${enumValues.join(", ")}`;
1698
+ return err([{
1699
+ path,
1700
+ message: message || defaultMessage
1701
+ }]);
1702
+ }
1703
+ if (excludedValues && excludedValues.includes(value)) return err([{
1704
+ path,
1705
+ message: `${message || `Selected value is excluded from valid enum values`}`
1706
+ }]);
1707
+ return ok(value);
1708
+ };
1047
1709
  }
1048
-
1049
1710
  // src/schema/bigint.ts
1711
+ /**
1712
+ * Create a validator that ensures a value is a bigint.
1713
+ *
1714
+ * @example
1715
+ * const validate = bigint();
1716
+ * validate(9007199254740993n); // ok(9007199254740993n)
1717
+ * validate(123); // err([{ path: [], message: 'Must be a bigint' }])
1718
+ *
1719
+ * @param message - Custom error message
1720
+ * @returns A validator that checks if the value is a bigint
1721
+ */
1050
1722
  function bigint(message = "Must be a bigint") {
1051
- return (value, path = []) => {
1052
- if (typeof value !== "bigint") {
1053
- return err([{ path, message }]);
1054
- }
1055
- return ok(value);
1056
- };
1723
+ return (value, path = []) => {
1724
+ if (typeof value !== "bigint") return err([{
1725
+ path,
1726
+ message
1727
+ }]);
1728
+ return ok(value);
1729
+ };
1057
1730
  }
1058
-
1059
1731
  // src/schema/standard.ts
1060
1732
  function mapErrors(errors) {
1061
- return errors.map((e) => ({ message: e.message, path: e.path }));
1733
+ return errors.map((e) => ({
1734
+ message: e.message,
1735
+ path: e.path
1736
+ }));
1062
1737
  }
1063
1738
  function toStandardSchema(validator) {
1064
- return {
1065
- "~standard": {
1066
- version: 1,
1067
- vendor: "railway-ts",
1068
- validate(value) {
1069
- try {
1070
- const result = validator(value);
1071
- if (result instanceof Promise) {
1072
- return result.then((r) => isOk(r) ? { value: r.value } : { issues: mapErrors(r.error) }).catch((error) => ({
1073
- issues: [{ message: error instanceof Error ? error.message : String(error) }]
1074
- }));
1075
- }
1076
- return isOk(result) ? { value: result.value } : { issues: mapErrors(result.error) };
1077
- } catch (error) {
1078
- return { issues: [{ message: error instanceof Error ? error.message : String(error) }] };
1079
- }
1080
- },
1081
- types: void 0
1082
- }
1083
- };
1739
+ return { "~standard": {
1740
+ version: 1,
1741
+ vendor: "railway-ts",
1742
+ validate(value) {
1743
+ try {
1744
+ const result = validator(value);
1745
+ if (result instanceof Promise) return result.then((r) => isOk(r) ? { value: r.value } : { issues: mapErrors(r.error) }).catch((error) => ({ issues: [{ message: error instanceof Error ? error.message : String(error) }] }));
1746
+ return isOk(result) ? { value: result.value } : { issues: mapErrors(result.error) };
1747
+ } catch (error) {
1748
+ return { issues: [{ message: error instanceof Error ? error.message : String(error) }] };
1749
+ }
1750
+ },
1751
+ types: void 0
1752
+ } };
1084
1753
  }
1085
-
1086
1754
  export { ROOT_ERROR_KEY, _getAbortEarly, _withAbortEarly, 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 };
1087
- //# sourceMappingURL=index.mjs.map
1755
+
1088
1756
  //# sourceMappingURL=index.mjs.map