@railway-ts/pipelines 0.1.21 → 0.1.22

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,24 @@ 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[]>>;
234
249
  /**
235
250
  * Format validation errors into a user-friendly object.
236
251
  * Converts array paths to dot/bracket notation strings.
@@ -259,8 +274,8 @@ declare function formatErrors(errors: ValidationError[]): Record<string, string>
259
274
  * @param schema - The validator/schema to validate against
260
275
  * @returns An object with either `{ valid: true, data }` or `{ valid: false, errors }`
261
276
  */
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>>;
277
+ declare function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>, options?: ValidateOptions): ValidationResult<T>;
278
+ declare function validateAndFormatResult<T>(input: unknown, schema: MaybeAsyncValidator<unknown, T>, options?: ValidateOptions): ValidationResult<T> | Promise<ValidationResult<T>>;
264
279
  /**
265
280
  * Create a validator that transforms a value during validation.
266
281
  * The transformer function must be pure and not throw exceptions.
@@ -1128,4 +1143,4 @@ declare namespace StandardSchemaV1 {
1128
1143
  declare function toStandardSchema<O>(validator: Validator<unknown, O>): StandardSchemaV1<unknown, O>;
1129
1144
  declare function toStandardSchema<O>(validator: MaybeAsyncValidator<unknown, O>): StandardSchemaV1<unknown, O>;
1130
1145
 
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 };
1146
+ 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, 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,24 @@ 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[]>>;
234
249
  /**
235
250
  * Format validation errors into a user-friendly object.
236
251
  * Converts array paths to dot/bracket notation strings.
@@ -259,8 +274,8 @@ declare function formatErrors(errors: ValidationError[]): Record<string, string>
259
274
  * @param schema - The validator/schema to validate against
260
275
  * @returns An object with either `{ valid: true, data }` or `{ valid: false, errors }`
261
276
  */
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>>;
277
+ declare function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>, options?: ValidateOptions): ValidationResult<T>;
278
+ declare function validateAndFormatResult<T>(input: unknown, schema: MaybeAsyncValidator<unknown, T>, options?: ValidateOptions): ValidationResult<T> | Promise<ValidationResult<T>>;
264
279
  /**
265
280
  * Create a validator that transforms a value during validation.
266
281
  * The transformer function must be pure and not throw exceptions.
@@ -1128,4 +1143,4 @@ declare namespace StandardSchemaV1 {
1128
1143
  declare function toStandardSchema<O>(validator: Validator<unknown, O>): StandardSchemaV1<unknown, O>;
1129
1144
  declare function toStandardSchema<O>(validator: MaybeAsyncValidator<unknown, O>): StandardSchemaV1<unknown, O>;
1130
1145
 
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 };
1146
+ 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, 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,7 +175,12 @@ 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
  }
160
186
  function formatErrors(errors) {
@@ -173,20 +199,26 @@ function formatErrors(errors) {
173
199
  {}
174
200
  );
175
201
  }
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
- );
202
+ function validateAndFormatResult(input, schema, options) {
203
+ const run = () => {
204
+ const result = schema(input);
205
+ if (result instanceof Promise) {
206
+ return result.then(
207
+ (r) => match(r, {
208
+ ok: (data) => ({ valid: true, data }),
209
+ err: (errors) => ({ valid: false, errors: formatErrors(errors) })
210
+ })
211
+ );
212
+ }
213
+ return match(result, {
214
+ ok: (data) => ({ valid: true, data }),
215
+ err: (errors) => ({ valid: false, errors: formatErrors(errors) })
216
+ });
217
+ };
218
+ if (options?.abortEarly) {
219
+ return _withAbortEarly(true, run);
185
220
  }
186
- return match(result, {
187
- ok: (data) => ({ valid: true, data }),
188
- err: (errors) => ({ valid: false, errors: formatErrors(errors) })
189
- });
221
+ return run();
190
222
  }
191
223
  function transform(transformer) {
192
224
  return (value) => ok(transformer(value));
@@ -298,13 +330,16 @@ function array(itemValidator) {
298
330
  if (!Array.isArray(value)) {
299
331
  return err([{ path: parentPath, message: "Expected an array" }]);
300
332
  }
333
+ const abortEarly = _getAbortEarly();
301
334
  const allErrors = [];
302
335
  const validatedItems = Array.from({ length: value.length });
303
336
  const pendingResults = [];
304
337
  for (const [i, item] of value.entries()) {
338
+ if (abortEarly && allErrors.length > 0) break;
305
339
  const itemPath = [...parentPath, i.toString()];
306
340
  const result = itemValidator(item, itemPath);
307
341
  if (result instanceof Promise) {
342
+ if (abortEarly && allErrors.length > 0) continue;
308
343
  const index = i;
309
344
  pendingResults.push(
310
345
  result.then((r) => {
@@ -319,6 +354,7 @@ function array(itemValidator) {
319
354
  validatedItems[i] = result.value;
320
355
  } else {
321
356
  allErrors.push(...result.error);
357
+ if (abortEarly) break;
322
358
  }
323
359
  }
324
360
  if (pendingResults.length > 0) {
@@ -399,14 +435,17 @@ function tuple(validators) {
399
435
  }
400
436
  ]);
401
437
  }
438
+ const abortEarly = _getAbortEarly();
402
439
  const allErrors = [];
403
440
  const validatedItems = Array.from({ length: validators.length });
404
441
  const pendingResults = [];
405
442
  for (const [i, validator] of validators.entries()) {
443
+ if (abortEarly && allErrors.length > 0) break;
406
444
  const itemPath = [...parentPath, i.toString()];
407
445
  const item = value.at(i);
408
446
  const result = validator(item, itemPath);
409
447
  if (result instanceof Promise) {
448
+ if (abortEarly && allErrors.length > 0) continue;
410
449
  const index = i;
411
450
  pendingResults.push(
412
451
  result.then((r) => {
@@ -421,6 +460,7 @@ function tuple(validators) {
421
460
  validatedItems[i] = result.value;
422
461
  } else {
423
462
  allErrors.push(...result.error);
463
+ if (abortEarly) break;
424
464
  }
425
465
  }
426
466
  if (pendingResults.length > 0) {
@@ -446,13 +486,16 @@ function tupleOf(elementValidator, length) {
446
486
  }
447
487
  ]);
448
488
  }
489
+ const abortEarly = _getAbortEarly();
449
490
  const allErrors = [];
450
491
  const validatedItems = Array.from({ length });
451
492
  const pendingResults = [];
452
493
  for (const [i, item] of value.entries()) {
494
+ if (abortEarly && allErrors.length > 0) break;
453
495
  const itemPath = [...parentPath, i.toString()];
454
496
  const result = elementValidator(item, itemPath);
455
497
  if (result instanceof Promise) {
498
+ if (abortEarly && allErrors.length > 0) continue;
456
499
  const index = i;
457
500
  pendingResults.push(
458
501
  result.then((r) => {
@@ -467,6 +510,7 @@ function tupleOf(elementValidator, length) {
467
510
  validatedItems[i] = result.value;
468
511
  } else {
469
512
  allErrors.push(...result.error);
513
+ if (abortEarly) break;
470
514
  }
471
515
  }
472
516
  if (pendingResults.length > 0) {
@@ -943,6 +987,6 @@ function toStandardSchema(validator) {
943
987
  };
944
988
  }
945
989
 
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 };
990
+ export { ROOT_ERROR_KEY, _getAbortEarly, _withAbortEarly, 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 };
947
991
  //# sourceMappingURL=index.mjs.map
948
992
  //# sourceMappingURL=index.mjs.map