@railway-ts/pipelines 0.1.21 → 0.1.23

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.
@@ -171,6 +171,12 @@ declare function emptyAsOptional<I, O>(validator: MaybeAsyncValidator<I, O>): Ma
171
171
  */
172
172
  declare function literal<T>(expectedValue: T, message?: string): Validator<unknown, T>;
173
173
 
174
+ /**
175
+ * Options for controlling validation behavior.
176
+ */
177
+ type ValidateOptions = {
178
+ abortEarly?: boolean;
179
+ };
174
180
  /**
175
181
  * The key used in formatted error objects for root-level validation errors (i.e. errors with an empty path).
176
182
  */
@@ -222,15 +228,39 @@ declare function chainAsync<A, B, C, D, E, F, G, H, I, J, K>(v1: MaybeAsyncValid
222
228
  * const result = validate(10, chain(number(), min(5)));
223
229
  * // ok(10)
224
230
  *
231
+ * @example
232
+ * // With abortEarly option — stops on first error
233
+ * const result = validate(input, userSchema, { abortEarly: true });
234
+ *
225
235
  * @param value - The value to validate
226
236
  * @param validator - The validator to apply
227
- * @param path - Optional base path for error reporting
237
+ * @param pathOrOptions - Optional base path for error reporting, or options object
238
+ * @param maybeOptions - Options object when path is also provided
228
239
  * @returns A Result containing either the validated value or validation errors
229
240
  */
230
241
  declare function validate<T>(value: unknown, validator: Validator<unknown, T>): Result<T, ValidationError[]>;
231
242
  declare function validate<T>(value: unknown, validator: Validator<unknown, T>, path: string[]): Result<T, ValidationError[]>;
243
+ declare function validate<T>(value: unknown, validator: Validator<unknown, T>, options: ValidateOptions): Result<T, ValidationError[]>;
244
+ declare function validate<T>(value: unknown, validator: Validator<unknown, T>, path: string[], options: ValidateOptions): Result<T, ValidationError[]>;
232
245
  declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
233
246
  declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, path: string[]): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
247
+ declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, options: ValidateOptions): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
248
+ declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, path: string[], options: ValidateOptions): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
249
+ /**
250
+ * Check whether a value satisfies a validator, returning a boolean.
251
+ * Always short-circuits on first error for maximum performance.
252
+ *
253
+ * @example
254
+ * is('hello', string()); // true
255
+ * is(42, string()); // false
256
+ * is(input, asyncValidator()); // Promise<boolean>
257
+ *
258
+ * @param value - The value to check
259
+ * @param validator - The validator to apply
260
+ * @returns `true` if valid, `false` otherwise (or a Promise for async validators)
261
+ */
262
+ declare function is(value: unknown, validator: Validator<unknown, unknown>): boolean;
263
+ declare function is(value: unknown, validator: MaybeAsyncValidator<unknown, unknown>): boolean | Promise<boolean>;
234
264
  /**
235
265
  * Format validation errors into a user-friendly object.
236
266
  * Converts array paths to dot/bracket notation strings.
@@ -259,8 +289,8 @@ declare function formatErrors(errors: ValidationError[]): Record<string, string>
259
289
  * @param schema - The validator/schema to validate against
260
290
  * @returns An object with either `{ valid: true, data }` or `{ valid: false, errors }`
261
291
  */
262
- declare function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>): ValidationResult<T>;
263
- declare function validateAndFormatResult<T>(input: unknown, schema: MaybeAsyncValidator<unknown, T>): ValidationResult<T> | Promise<ValidationResult<T>>;
292
+ declare function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>, options?: ValidateOptions): ValidationResult<T>;
293
+ declare function validateAndFormatResult<T>(input: unknown, schema: MaybeAsyncValidator<unknown, T>, options?: ValidateOptions): ValidationResult<T> | Promise<ValidationResult<T>>;
264
294
  /**
265
295
  * Create a validator that transforms a value during validation.
266
296
  * The transformer function must be pure and not throw exceptions.
@@ -1128,4 +1158,4 @@ declare namespace StandardSchemaV1 {
1128
1158
  declare function toStandardSchema<O>(validator: Validator<unknown, O>): StandardSchemaV1<unknown, O>;
1129
1159
  declare function toStandardSchema<O>(validator: MaybeAsyncValidator<unknown, O>): StandardSchemaV1<unknown, O>;
1130
1160
 
1131
- export { type AsyncValidator, type InferSchemaType, type MaybeAsyncValidator, ROOT_ERROR_KEY, type Schema, StandardSchemaV1, type SyncSchema, type ValidationError, type ValidationResult, type Validator, type ValidatorMapOutput, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, 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, validate, validateAndFormatResult };
1161
+ export { type AsyncValidator, type InferSchemaType, type MaybeAsyncValidator, ROOT_ERROR_KEY, type Schema, StandardSchemaV1, type SyncSchema, type ValidateOptions, type ValidationError, type ValidationResult, type Validator, type ValidatorMapOutput, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, is, 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, validate, validateAndFormatResult };
@@ -171,6 +171,12 @@ declare function emptyAsOptional<I, O>(validator: MaybeAsyncValidator<I, O>): Ma
171
171
  */
172
172
  declare function literal<T>(expectedValue: T, message?: string): Validator<unknown, T>;
173
173
 
174
+ /**
175
+ * Options for controlling validation behavior.
176
+ */
177
+ type ValidateOptions = {
178
+ abortEarly?: boolean;
179
+ };
174
180
  /**
175
181
  * The key used in formatted error objects for root-level validation errors (i.e. errors with an empty path).
176
182
  */
@@ -222,15 +228,39 @@ declare function chainAsync<A, B, C, D, E, F, G, H, I, J, K>(v1: MaybeAsyncValid
222
228
  * const result = validate(10, chain(number(), min(5)));
223
229
  * // ok(10)
224
230
  *
231
+ * @example
232
+ * // With abortEarly option — stops on first error
233
+ * const result = validate(input, userSchema, { abortEarly: true });
234
+ *
225
235
  * @param value - The value to validate
226
236
  * @param validator - The validator to apply
227
- * @param path - Optional base path for error reporting
237
+ * @param pathOrOptions - Optional base path for error reporting, or options object
238
+ * @param maybeOptions - Options object when path is also provided
228
239
  * @returns A Result containing either the validated value or validation errors
229
240
  */
230
241
  declare function validate<T>(value: unknown, validator: Validator<unknown, T>): Result<T, ValidationError[]>;
231
242
  declare function validate<T>(value: unknown, validator: Validator<unknown, T>, path: string[]): Result<T, ValidationError[]>;
243
+ declare function validate<T>(value: unknown, validator: Validator<unknown, T>, options: ValidateOptions): Result<T, ValidationError[]>;
244
+ declare function validate<T>(value: unknown, validator: Validator<unknown, T>, path: string[], options: ValidateOptions): Result<T, ValidationError[]>;
232
245
  declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
233
246
  declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, path: string[]): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
247
+ declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, options: ValidateOptions): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
248
+ declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, path: string[], options: ValidateOptions): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
249
+ /**
250
+ * Check whether a value satisfies a validator, returning a boolean.
251
+ * Always short-circuits on first error for maximum performance.
252
+ *
253
+ * @example
254
+ * is('hello', string()); // true
255
+ * is(42, string()); // false
256
+ * is(input, asyncValidator()); // Promise<boolean>
257
+ *
258
+ * @param value - The value to check
259
+ * @param validator - The validator to apply
260
+ * @returns `true` if valid, `false` otherwise (or a Promise for async validators)
261
+ */
262
+ declare function is(value: unknown, validator: Validator<unknown, unknown>): boolean;
263
+ declare function is(value: unknown, validator: MaybeAsyncValidator<unknown, unknown>): boolean | Promise<boolean>;
234
264
  /**
235
265
  * Format validation errors into a user-friendly object.
236
266
  * Converts array paths to dot/bracket notation strings.
@@ -259,8 +289,8 @@ declare function formatErrors(errors: ValidationError[]): Record<string, string>
259
289
  * @param schema - The validator/schema to validate against
260
290
  * @returns An object with either `{ valid: true, data }` or `{ valid: false, errors }`
261
291
  */
262
- declare function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>): ValidationResult<T>;
263
- declare function validateAndFormatResult<T>(input: unknown, schema: MaybeAsyncValidator<unknown, T>): ValidationResult<T> | Promise<ValidationResult<T>>;
292
+ declare function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>, options?: ValidateOptions): ValidationResult<T>;
293
+ declare function validateAndFormatResult<T>(input: unknown, schema: MaybeAsyncValidator<unknown, T>, options?: ValidateOptions): ValidationResult<T> | Promise<ValidationResult<T>>;
264
294
  /**
265
295
  * Create a validator that transforms a value during validation.
266
296
  * The transformer function must be pure and not throw exceptions.
@@ -1128,4 +1158,4 @@ declare namespace StandardSchemaV1 {
1128
1158
  declare function toStandardSchema<O>(validator: Validator<unknown, O>): StandardSchemaV1<unknown, O>;
1129
1159
  declare function toStandardSchema<O>(validator: MaybeAsyncValidator<unknown, O>): StandardSchemaV1<unknown, O>;
1130
1160
 
1131
- export { type AsyncValidator, type InferSchemaType, type MaybeAsyncValidator, ROOT_ERROR_KEY, type Schema, StandardSchemaV1, type SyncSchema, type ValidationError, type ValidationResult, type Validator, type ValidatorMapOutput, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, 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, validate, validateAndFormatResult };
1161
+ export { type AsyncValidator, type InferSchemaType, type MaybeAsyncValidator, ROOT_ERROR_KEY, type Schema, StandardSchemaV1, type SyncSchema, type ValidateOptions, type ValidationError, type ValidationResult, type Validator, type ValidatorMapOutput, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, is, 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, validate, validateAndFormatResult };
@@ -37,16 +37,33 @@ function fromTry(f) {
37
37
  }
38
38
 
39
39
  // src/schema/core.ts
40
+ var _abortEarly = false;
41
+ function _getAbortEarly() {
42
+ return _abortEarly;
43
+ }
44
+ function _withAbortEarly(enabled, fn) {
45
+ const prev = _abortEarly;
46
+ _abortEarly = enabled;
47
+ try {
48
+ return fn();
49
+ } finally {
50
+ _abortEarly = prev;
51
+ }
52
+ }
40
53
  function object(schema, { strict = true } = {}) {
41
54
  return (obj, parentPath = []) => {
42
55
  if (obj === null || typeof obj !== "object") {
43
56
  return err([{ path: parentPath, message: "Expected an object" }]);
44
57
  }
58
+ const abortEarly = _getAbortEarly();
45
59
  const allErrors = [];
46
60
  const validatedObj = {};
47
61
  if (strict !== false) {
48
62
  const extraKeys = Object.keys(obj).filter((key) => !Object.prototype.hasOwnProperty.call(schema, key));
49
63
  if (extraKeys.length > 0) {
64
+ if (abortEarly) {
65
+ return err([{ path: [...parentPath, extraKeys[0]], message: `Unexpected field: '${extraKeys[0]}'` }]);
66
+ }
50
67
  for (const key of extraKeys) {
51
68
  allErrors.push({
52
69
  path: [...parentPath, key],
@@ -55,15 +72,18 @@ function object(schema, { strict = true } = {}) {
55
72
  }
56
73
  }
57
74
  }
75
+ if (abortEarly && allErrors.length > 0) return err(allErrors);
58
76
  const pendingResults = [];
59
77
  for (const key in schema) {
60
78
  if (!Object.prototype.hasOwnProperty.call(schema, key)) continue;
61
79
  const validator = schema[key];
62
80
  if (!validator) continue;
81
+ if (abortEarly && allErrors.length > 0) break;
63
82
  const value = obj[key];
64
83
  const fieldPath = [...parentPath, key];
65
84
  const result = validator(value, fieldPath);
66
85
  if (result instanceof Promise) {
86
+ if (abortEarly && allErrors.length > 0) continue;
67
87
  pendingResults.push(
68
88
  result.then((r) => {
69
89
  if (isOk(r)) {
@@ -77,6 +97,7 @@ function object(schema, { strict = true } = {}) {
77
97
  validatedObj[key] = result.value;
78
98
  } else {
79
99
  allErrors.push(...result.error);
100
+ if (abortEarly) break;
80
101
  }
81
102
  }
82
103
  if (pendingResults.length > 0) {
@@ -154,9 +175,21 @@ function chainAsync(...validators) {
154
175
  return ok(current);
155
176
  };
156
177
  }
157
- function validate(value, validator, path = []) {
178
+ function validate(value, validator, pathOrOptions = [], maybeOptions) {
179
+ const path = Array.isArray(pathOrOptions) ? pathOrOptions : [];
180
+ const options = Array.isArray(pathOrOptions) ? maybeOptions : pathOrOptions;
181
+ if (options?.abortEarly) {
182
+ return _withAbortEarly(true, () => validator(value, path));
183
+ }
158
184
  return validator(value, path);
159
185
  }
186
+ function is(value, validator) {
187
+ const result = _withAbortEarly(true, () => validator(value));
188
+ if (result instanceof Promise) {
189
+ return result.then((r) => r.ok);
190
+ }
191
+ return result.ok;
192
+ }
160
193
  function formatErrors(errors) {
161
194
  return errors.reduce(
162
195
  (acc, error) => {
@@ -173,20 +206,26 @@ function formatErrors(errors) {
173
206
  {}
174
207
  );
175
208
  }
176
- function validateAndFormatResult(input, schema) {
177
- const result = schema(input);
178
- if (result instanceof Promise) {
179
- return result.then(
180
- (r) => match(r, {
181
- ok: (data) => ({ valid: true, data }),
182
- err: (errors) => ({ valid: false, errors: formatErrors(errors) })
183
- })
184
- );
209
+ function validateAndFormatResult(input, schema, options) {
210
+ const run = () => {
211
+ const result = schema(input);
212
+ if (result instanceof Promise) {
213
+ return result.then(
214
+ (r) => match(r, {
215
+ ok: (data) => ({ valid: true, data }),
216
+ err: (errors) => ({ valid: false, errors: formatErrors(errors) })
217
+ })
218
+ );
219
+ }
220
+ return match(result, {
221
+ ok: (data) => ({ valid: true, data }),
222
+ err: (errors) => ({ valid: false, errors: formatErrors(errors) })
223
+ });
224
+ };
225
+ if (options?.abortEarly) {
226
+ return _withAbortEarly(true, run);
185
227
  }
186
- return match(result, {
187
- ok: (data) => ({ valid: true, data }),
188
- err: (errors) => ({ valid: false, errors: formatErrors(errors) })
189
- });
228
+ return run();
190
229
  }
191
230
  function transform(transformer) {
192
231
  return (value) => ok(transformer(value));
@@ -298,13 +337,16 @@ function array(itemValidator) {
298
337
  if (!Array.isArray(value)) {
299
338
  return err([{ path: parentPath, message: "Expected an array" }]);
300
339
  }
340
+ const abortEarly = _getAbortEarly();
301
341
  const allErrors = [];
302
342
  const validatedItems = Array.from({ length: value.length });
303
343
  const pendingResults = [];
304
344
  for (const [i, item] of value.entries()) {
345
+ if (abortEarly && allErrors.length > 0) break;
305
346
  const itemPath = [...parentPath, i.toString()];
306
347
  const result = itemValidator(item, itemPath);
307
348
  if (result instanceof Promise) {
349
+ if (abortEarly && allErrors.length > 0) continue;
308
350
  const index = i;
309
351
  pendingResults.push(
310
352
  result.then((r) => {
@@ -319,6 +361,7 @@ function array(itemValidator) {
319
361
  validatedItems[i] = result.value;
320
362
  } else {
321
363
  allErrors.push(...result.error);
364
+ if (abortEarly) break;
322
365
  }
323
366
  }
324
367
  if (pendingResults.length > 0) {
@@ -399,14 +442,17 @@ function tuple(validators) {
399
442
  }
400
443
  ]);
401
444
  }
445
+ const abortEarly = _getAbortEarly();
402
446
  const allErrors = [];
403
447
  const validatedItems = Array.from({ length: validators.length });
404
448
  const pendingResults = [];
405
449
  for (const [i, validator] of validators.entries()) {
450
+ if (abortEarly && allErrors.length > 0) break;
406
451
  const itemPath = [...parentPath, i.toString()];
407
452
  const item = value.at(i);
408
453
  const result = validator(item, itemPath);
409
454
  if (result instanceof Promise) {
455
+ if (abortEarly && allErrors.length > 0) continue;
410
456
  const index = i;
411
457
  pendingResults.push(
412
458
  result.then((r) => {
@@ -421,6 +467,7 @@ function tuple(validators) {
421
467
  validatedItems[i] = result.value;
422
468
  } else {
423
469
  allErrors.push(...result.error);
470
+ if (abortEarly) break;
424
471
  }
425
472
  }
426
473
  if (pendingResults.length > 0) {
@@ -446,13 +493,16 @@ function tupleOf(elementValidator, length) {
446
493
  }
447
494
  ]);
448
495
  }
496
+ const abortEarly = _getAbortEarly();
449
497
  const allErrors = [];
450
498
  const validatedItems = Array.from({ length });
451
499
  const pendingResults = [];
452
500
  for (const [i, item] of value.entries()) {
501
+ if (abortEarly && allErrors.length > 0) break;
453
502
  const itemPath = [...parentPath, i.toString()];
454
503
  const result = elementValidator(item, itemPath);
455
504
  if (result instanceof Promise) {
505
+ if (abortEarly && allErrors.length > 0) continue;
456
506
  const index = i;
457
507
  pendingResults.push(
458
508
  result.then((r) => {
@@ -467,6 +517,7 @@ function tupleOf(elementValidator, length) {
467
517
  validatedItems[i] = result.value;
468
518
  } else {
469
519
  allErrors.push(...result.error);
520
+ if (abortEarly) break;
470
521
  }
471
522
  }
472
523
  if (pendingResults.length > 0) {
@@ -943,6 +994,6 @@ function toStandardSchema(validator) {
943
994
  };
944
995
  }
945
996
 
946
- export { ROOT_ERROR_KEY, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, 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, validate, validateAndFormatResult };
997
+ export { ROOT_ERROR_KEY, _getAbortEarly, _withAbortEarly, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, is, 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, validate, validateAndFormatResult };
947
998
  //# sourceMappingURL=index.mjs.map
948
999
  //# sourceMappingURL=index.mjs.map