runcheck 1.12.0 → 1.13.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,8 +1,19 @@
1
1
  import { StandardSchemaV1 } from '@standard-schema/spec';
2
2
 
3
3
  /**
4
- * If the schema key value is undefined uses a value from the fallback key as a safe value
5
- * Can be used to rename keys from input
4
+ * Creates a type that uses a fallback key when the primary key is undefined.
5
+ * Can be used to rename keys from input or provide alternative key names.
6
+ * @param fallbackKey - The alternative key to use when the primary key is undefined
7
+ * @param type - The type to validate the value against
8
+ * @returns A runcheck type that supports fallback key lookup
9
+ * @example
10
+ * ```typescript
11
+ * const userSchema = rc_object({
12
+ * name: rc_get_from_key_as_fallback('username', rc_string)
13
+ * })
14
+ * // Will look for 'name' first, then 'username' if 'name' is undefined
15
+ * const result = userSchema.parse({ username: 'john' }) // valid
16
+ * ```
6
17
  */
7
18
  declare function rc_get_from_key_as_fallback<T extends RcType<any>>(fallbackKey: string, type: T): RcType<RcInferType<T>>;
8
19
  type RcObject = {
@@ -25,23 +36,137 @@ type Flatten<T> = Identity<{
25
36
  }>;
26
37
  type ObjOptions = {
27
38
  normalizeKeysFrom?: 'snake_case';
39
+ /** excess keys are not removed if extends is true */
40
+ extends?: boolean;
28
41
  };
29
- declare function rc_object<T extends RcObject>(shape: T, { normalizeKeysFrom }?: ObjOptions): RcObjTypeReturn<T>;
30
- declare function rc_obj_extends<T extends RcObject>(shape: T, options?: ObjOptions): RcObjTypeReturn<T>;
42
+ /**
43
+ * Creates an object type validator with specified shape and options.
44
+ * @param shape - The object shape defining the expected properties and their types
45
+ * @param options - Configuration options for the object validator
46
+ * @param options.normalizeKeysFrom - If 'snake_case', automatically converts camelCase keys to snake_case for lookup
47
+ * @param options.extends - If true, allows excess properties in the input object
48
+ * @returns A runcheck type that validates objects with the specified shape
49
+ * @example
50
+ * ```typescript
51
+ * const userSchema = rc_object({
52
+ * name: rc_string,
53
+ * age: rc_number,
54
+ * email: rc_string.optional()
55
+ * })
56
+ * const result = userSchema.parse({ name: 'John', age: 30 }) // valid
57
+ * ```
58
+ */
59
+ declare function rc_object<T extends RcObject>(shape: T, { normalizeKeysFrom, extends: extendsObj }?: ObjOptions): RcObjTypeReturn<T>;
60
+ type ExtendsOptions = Omit<ObjOptions, 'extends'>;
61
+ /**
62
+ * Creates an object type that extends the input with additional properties.
63
+ * Unlike strict objects, this allows excess properties from the input to be preserved.
64
+ * @param shapeOrSchema - Either an object shape or an existing object type
65
+ * @param options - Configuration options (excluding 'extends' which is always true)
66
+ * @returns A runcheck type that validates and extends objects
67
+ * @example
68
+ * ```typescript
69
+ * const baseSchema = rc_obj_extends({
70
+ * name: rc_string
71
+ * })
72
+ * // Input: { name: 'John', extra: 'data' }
73
+ * // Output: { name: 'John', extra: 'data' } (preserves extra properties)
74
+ * ```
75
+ */
76
+ declare function rc_obj_extends<T extends RcObject>(shape: T, options?: ExtendsOptions): RcObjTypeReturn<T>;
77
+ declare function rc_obj_extends<T extends Record<string, any>>(schema: RcType<T>, options?: ExtendsOptions): RcType<T>;
78
+ /**
79
+ * Extracts the object shape from an object type for inspection or manipulation.
80
+ * @param type - The object type to extract the shape from
81
+ * @returns The object shape containing the property types
82
+ * @throws Error if the type is not an object type
83
+ * @example
84
+ * ```typescript
85
+ * const userSchema = rc_object({ name: rc_string, age: rc_number })
86
+ * const shape = rc_get_obj_shape(userSchema)
87
+ * // shape = { name: RcType<string>, age: RcType<number> }
88
+ * ```
89
+ */
31
90
  declare function rc_get_obj_shape<T extends Record<string, any>>(type: RcType<T>): {
32
91
  [K in keyof T]: RcType<T[K]>;
33
92
  };
34
- /** return an error if the obj has more keys than the expected type */
93
+ /**
94
+ * Creates a strict object type that rejects input with excess properties.
95
+ * @param shape - The object shape defining the expected properties and their types
96
+ * @param options - Configuration options for the object validator
97
+ * @returns A runcheck type that validates objects strictly (no excess properties allowed)
98
+ * @example
99
+ * ```typescript
100
+ * const strictUser = rc_obj_strict({
101
+ * name: rc_string,
102
+ * age: rc_number
103
+ * })
104
+ * const result = strictUser.parse({ name: 'John', age: 30 }) // valid
105
+ * const result2 = strictUser.parse({ name: 'John', age: 30, extra: 'data' }) // invalid
106
+ * ```
107
+ */
35
108
  declare function rc_obj_strict<T extends RcObject>(shape: T, options?: ObjOptions): RcObjTypeReturn<T>;
109
+ /**
110
+ * Enables strict object validation for a type, rejecting excess properties.
111
+ * @param type - The type to make strict
112
+ * @param options - Configuration options
113
+ * @param options.nonRecursive - If true, only affects the immediate object type, not nested objects
114
+ * @returns The type with strict object validation enabled
115
+ * @example
116
+ * ```typescript
117
+ * const userSchema = rc_object({ name: rc_string, age: rc_number })
118
+ * const strictUser = rc_enable_obj_strict(userSchema)
119
+ * // Now rejects objects with excess properties
120
+ * ```
121
+ */
36
122
  declare function rc_enable_obj_strict<T extends RcType<any>>(type: T, { nonRecursive, }?: {
37
123
  nonRecursive?: boolean;
38
124
  }): T;
39
125
  type AnyObj = Record<string, unknown>;
40
126
  type Extends<T extends AnyObj, W extends AnyObj> = Omit<T, keyof W> & W;
127
+ /**
128
+ * Merges multiple object types into a single object type.
129
+ * Later objects override properties from earlier objects.
130
+ * @param objs - The object types to merge (2-4 objects supported)
131
+ * @returns A runcheck type representing the merged object
132
+ * @example
133
+ * ```typescript
134
+ * const base = rc_object({ name: rc_string, age: rc_number })
135
+ * const extended = rc_object({ email: rc_string, age: rc_string }) // age overrides
136
+ * const merged = rc_obj_merge(base, extended)
137
+ * // Result: { name: string, age: string, email: string }
138
+ * ```
139
+ */
41
140
  declare function rc_obj_merge<A extends AnyObj, B extends AnyObj>(...objs: [RcType<A>, RcType<B>]): RcType<Extends<A, B>>;
42
141
  declare function rc_obj_merge<A extends AnyObj, B extends AnyObj, C extends AnyObj>(...objs: [RcType<A>, RcType<B>, RcType<C>]): RcType<Extends<Extends<A, B>, C>>;
43
142
  declare function rc_obj_merge<A extends AnyObj, B extends AnyObj, C extends AnyObj, D extends AnyObj>(...objs: [RcType<A>, RcType<B>, RcType<C>, RcType<D>]): RcType<Extends<Extends<Extends<A, B>, C>, D>>;
143
+ /**
144
+ * Creates a new object type with only the specified properties from the original.
145
+ * @param obj - The object type to pick properties from
146
+ * @param keys - The keys to pick from the object
147
+ * @returns A runcheck type containing only the picked properties
148
+ * @throws Error if the input is not an object type
149
+ * @example
150
+ * ```typescript
151
+ * const userSchema = rc_object({ name: rc_string, age: rc_number, email: rc_string })
152
+ * const nameAndAge = rc_obj_pick(userSchema, ['name', 'age'])
153
+ * // Result: { name: string, age: number }
154
+ * ```
155
+ */
44
156
  declare function rc_obj_pick<O extends AnyObj, K extends keyof O>(obj: RcType<O>, keys: K[]): RcType<Pick<O, K>>;
157
+ /**
158
+ * Creates a new object type without the specified properties from the original.
159
+ * @param obj - The object type to omit properties from
160
+ * @param keys - The keys to omit from the object
161
+ * @returns A runcheck type without the omitted properties
162
+ * @throws Error if the input is not an object type
163
+ * @example
164
+ * ```typescript
165
+ * const userSchema = rc_object({ name: rc_string, age: rc_number, email: rc_string })
166
+ * const withoutEmail = rc_obj_omit(userSchema, ['email'])
167
+ * // Result: { name: string, age: number }
168
+ * ```
169
+ */
45
170
  declare function rc_obj_omit<O extends AnyObj, K extends keyof O>(obj: RcType<O>, keys: K[]): RcType<Omit<O, K>>;
46
171
  type ExpectedSchema<T> = (t: T) => T;
47
172
  type RcTypeWithSchemaEqualTo<T> = {
@@ -71,16 +196,88 @@ type StrictTypeToRcType<T> = [
71
196
  type StrictTypeToRcTypeBase<T extends Record<string, any>> = {
72
197
  [K in keyof T]-?: StrictTypeToRcType<T[K]>;
73
198
  };
199
+ /**
200
+ * Creates a type-safe object builder that enforces the structure matches a TypeScript type.
201
+ * Useful for creating schemas that must conform to existing TypeScript interfaces.
202
+ * @returns A builder function that takes a schema matching the specified TypeScript type
203
+ * @example
204
+ * ```typescript
205
+ * interface User {
206
+ * name: string
207
+ * age: number
208
+ * email?: string
209
+ * }
210
+ *
211
+ * const userBuilder = rc_obj_builder<User>()
212
+ * const userSchema = userBuilder({
213
+ * name: rc_string,
214
+ * age: rc_number,
215
+ * email: ['optional', rc_string]
216
+ * })
217
+ * ```
218
+ */
74
219
  declare function rc_obj_builder<T extends Record<string, any>>(): <S extends StrictTypeToRcTypeBase<T>>(schema: { [K in keyof S]: K extends keyof T ? S[K] : never; }, options?: ObjOptions) => RcType<T>;
75
220
 
221
+ /**
222
+ * Creates a discriminated union type validator.
223
+ * Uses a discriminator key to determine which schema to validate against.
224
+ * @param discriminatorKey - The property name used to discriminate between union members
225
+ * @param types - An object mapping discriminator values to their corresponding schemas
226
+ * @returns A runcheck type that validates discriminated union objects
227
+ * @example
228
+ * ```typescript
229
+ * const shapeSchema = rc_discriminated_union('type', {
230
+ * circle: { radius: rc_number },
231
+ * rectangle: { width: rc_number, height: rc_number }
232
+ * })
233
+ *
234
+ * const result1 = shapeSchema.parse({ type: 'circle', radius: 5 }) // valid
235
+ * const result2 = shapeSchema.parse({ type: 'rectangle', width: 10, height: 20 }) // valid
236
+ * const result3 = shapeSchema.parse({ type: 'triangle', sides: 3 }) // invalid - unknown discriminator
237
+ * ```
238
+ */
76
239
  declare function rc_discriminated_union<K extends string, T extends Record<string, RcObject | RcBase<any, any>>>(discriminatorKey: K, types: T): RcType<Prettify<{
77
240
  [P in keyof T]: {
78
241
  [Q in K]: P;
79
242
  } & (T[P] extends RcType<infer U> ? U : T[P] extends RcObject ? TypeOfObjectType<T[P]> : never);
80
243
  }[keyof T]>>;
81
244
  type OmitDiscriminator<K, D extends Record<string, unknown>> = D extends any ? Omit<D, K & string> : never;
245
+ /**
246
+ * Creates a type-safe discriminated union builder that enforces the structure matches a TypeScript type.
247
+ * @param discriminatorKey - The property name used to discriminate between union members
248
+ * @returns A builder function that takes a schema mapping matching the specified TypeScript discriminated union
249
+ * @example
250
+ * ```typescript
251
+ * type Shape =
252
+ * | { type: 'circle', radius: number }
253
+ * | { type: 'rectangle', width: number, height: number }
254
+ *
255
+ * const shapeBuilder = rc_discriminated_union_builder<Shape, 'type'>('type')
256
+ * const shapeSchema = shapeBuilder({
257
+ * circle: { radius: rc_number },
258
+ * rectangle: { width: rc_number, height: rc_number }
259
+ * })
260
+ * ```
261
+ */
82
262
  declare function rc_discriminated_union_builder<D extends Record<string, unknown>, K extends keyof D>(discriminatorKey: K): (schema: { [P in D[K] & string]: StrictTypeToRcTypeBase<OmitDiscriminator<K, D & { [Q in K]: P; }>>; }) => RcType<D>;
83
263
 
264
+ /**
265
+ * Creates an intersection type validator that requires input to satisfy all provided types.
266
+ * For object types, merges the properties from all types.
267
+ * For non-object types, input must be valid for all types simultaneously.
268
+ * @param types - The types to intersect (2-4 types supported)
269
+ * @returns A runcheck type representing the intersection of all input types
270
+ * @example
271
+ * ```typescript
272
+ * const userBase = rc_object({ name: rc_string })
273
+ * const userMeta = rc_object({ createdAt: rc_date })
274
+ * const fullUser = rc_intersection(userBase, userMeta)
275
+ * // Result: { name: string, createdAt: Date }
276
+ *
277
+ * const result = fullUser.parse({ name: 'John', createdAt: new Date() }) // valid
278
+ * const result2 = fullUser.parse({ name: 'John' }) // invalid - missing createdAt
279
+ * ```
280
+ */
84
281
  declare function rc_intersection<A, B>(a: RcType<A>, b: RcType<B>): RcType<A & B>;
85
282
  declare function rc_intersection<A, B, C>(a: RcType<A>, b: RcType<B>, c: RcType<C>): RcType<A & B & C>;
86
283
  declare function rc_intersection<A, B, C, D>(a: RcType<A>, b: RcType<B>, c: RcType<C>, d: RcType<D>): RcType<A & B & C & D>;
@@ -179,29 +376,53 @@ type IsValid<T> = boolean | {
179
376
  };
180
377
  declare function parse<T>(type: RcType<T>, input: unknown, ctx: ParseResultCtx, checkIfIsValid: () => IsValid<T>): InternalParseResult<T>;
181
378
  declare const defaultProps: Omit<RcType<any>, '_parse_' | '_kind_'>;
379
+ /** Equivalent to ts type: `undefined`. */
182
380
  declare const rc_undefined: RcType<undefined>;
381
+ /** Equivalent to ts type: `null`. */
183
382
  declare const rc_null: RcType<null>;
383
+ /** Equivalent to ts type: `any`. */
184
384
  declare const rc_any: RcType<any>;
385
+ /** Equivalent to ts type: `unknown`. */
185
386
  declare const rc_unknown: RcType<unknown>;
387
+ /** Equivalent to ts type: `boolean`. */
186
388
  declare const rc_boolean: RcType<boolean>;
389
+ /** Equivalent to ts type: `string`. */
187
390
  declare const rc_string: RcType<string>;
391
+ /** Equivalent to ts type: `number`. Excludes `NaN`. */
188
392
  declare const rc_number: RcType<number>;
393
+ /** Equivalent to ts type: `Date`. Excludes invalid dates. */
189
394
  declare const rc_date: RcType<Date>;
190
- declare function rc_instanceof<T extends Function>(classToCheck: T): RcType<T>;
395
+ /** Validates class instances using `instanceof` checks.
396
+ *
397
+ * @example
398
+ * ```typescript
399
+ * const userSchema = rc_instanceof(User) // schema is equivalent to `User` type
400
+ * const result = userSchema.parse(new User('John', 30)) // valid
401
+ * const result2 = userSchema.parse(new Admin('John', 30)) // invalid
402
+ * ```
403
+ */
404
+ declare function rc_instanceof<T extends new (...args: any[]) => any>(classToCheck: T): RcType<InstanceType<T>>;
405
+ /** Validates literal values like `'hello' | true | 1`. */
191
406
  declare function rc_literals<T extends (string | number | boolean)[]>(...literals: T): RcType<T[number]>;
407
+ /** Validates union types like `string | number`. */
192
408
  declare function rc_union<T extends RcType<any>[]>(...types: T): RcType<RcInferType<T[number]>>;
193
409
  type NotUndefined<T> = Exclude<T, undefined>;
194
410
  /** Generate a schema with valid fallback value for undefined inputs */
411
+ /** Provides default value for `undefined` inputs. */
195
412
  declare function rc_default<T>(schema: RcType<T>, defaultValue: NotUndefined<T> | (() => NotUndefined<T>)): RcType<NotUndefined<T>>;
196
413
  type NotNullish<T> = Exclude<T, null | undefined>;
414
+ /** Provides default value for `null | undefined` inputs. */
197
415
  declare function rc_nullish_default<T>(schema: RcType<T>, defaultValue: NotNullish<T> | (() => NotNullish<T>)): RcType<NotNullish<T>>;
198
416
  /** returns a fallback in case of wrong inputs without adding a warning */
417
+ /** Provides fallback value for invalid inputs without warnings. */
199
418
  declare function rc_safe_fallback<T>(schema: RcType<T>, fallback: NoInfer<T> | (() => NoInfer<T>)): RcType<T>;
419
+ /** Validates `Record<string, T>`. Supports key validation and loose checking. */
200
420
  declare function rc_record<V>(valueType: RcType<V>, { checkKey, looseCheck, }?: {
201
421
  checkKey?: (key: string) => boolean;
202
422
  looseCheck?: boolean;
203
423
  }): RcType<Record<string, V>>;
204
424
  /** instead of returning a general error, rejects invalid keys and returns warnings for these items */
425
+ /** Validates `Record<string, T>`. Filters out invalid values instead of rejecting. */
205
426
  declare function rc_loose_record<V>(valueType: RcType<V>, { checkKey }?: {
206
427
  checkKey?: (key: string) => boolean;
207
428
  }): RcType<Record<string, V>>;
@@ -211,13 +432,53 @@ type ArrayOptions<T extends RcType<any>> = {
211
432
  errors: ErrorWithPath[];
212
433
  };
213
434
  };
435
+ /** Validates arrays of type `T[]`. Supports unique value checking. */
214
436
  declare function rc_array<T extends RcType<any>>(type: T, options?: ArrayOptions<T>): RcType<RcInferType<T>[]>;
437
+ /**
438
+ * Extracts the item type from an array type.
439
+ * @param type - The array type to extract the item type from
440
+ * @returns The item type of the array
441
+ * @example
442
+ * ```typescript
443
+ * const stringArray = rc_array(rc_string)
444
+ * const itemType = rc_get_array_item_type(stringArray) // rc_string
445
+ * ```
446
+ */
215
447
  declare function rc_get_array_item_type<T>(type: RcType<T[]>): RcType<T>;
448
+ /**
449
+ * Disables loose array validation for a type.
450
+ * @param type - The type to modify
451
+ * @param options - Configuration options
452
+ * @param options.nonRecursive - If true, only affects the immediate array type
453
+ * @returns The modified type with loose array validation disabled
454
+ * @example
455
+ * ```typescript
456
+ * const strictArray = rc_disable_loose_array(rc_array(rc_string))
457
+ * ```
458
+ */
216
459
  declare function rc_disable_loose_array<T extends RcType<any>>(type: T, { nonRecursive }?: {
217
460
  nonRecursive?: boolean;
218
461
  }): T;
219
462
  /** instead of returning a general error, rejects invalid array items and returns warnings for these items */
463
+ /** Validates arrays of type `T[]`. Filters out invalid elements instead of rejecting the array. */
220
464
  declare function rc_loose_array<T extends RcType<any>>(type: T, options?: ArrayOptions<T>): RcType<RcInferType<T>[]>;
465
+ /**
466
+ * Creates an array validator with schema-based filtering.
467
+ * @param filterSchema - The schema to validate items before filtering
468
+ * @param filterFn - The function to determine if validated items should be included
469
+ * @param type - The type to validate for included array elements
470
+ * @param options - Configuration options
471
+ * @returns A runcheck type that validates and filters arrays based on the schema
472
+ * @example
473
+ * ```typescript
474
+ * const evenNumbers = rc_array_filter_from_schema(
475
+ * rc_number,
476
+ * (n) => n % 2 === 0,
477
+ * rc_number
478
+ * )
479
+ * const result = evenNumbers.parse([1, 2, 3, 4]) // returns [2, 4]
480
+ * ```
481
+ */
221
482
  declare function rc_array_filter_from_schema<B, T>(filterSchema: RcType<B>, filterFn: (item: B) => boolean, type: RcType<T>, options?: Omit<ArrayOptions<RcType<any>>, 'filter'> & {
222
483
  loose?: boolean;
223
484
  }): RcType<T[]>;
@@ -229,6 +490,7 @@ type MapTupleToTypes<T extends readonly [...any[]]> = {
229
490
  *
230
491
  * TS equivalent example: [string, number, boolean]
231
492
  */
493
+ /** Validates tuples like `[T, T]` with fixed length. */
232
494
  declare function rc_tuple<const T extends readonly RcType<any>[]>(types: T): RcType<MapTupleToTypes<T>>;
233
495
  type ParseOptions = {
234
496
  /** ignore fallback and autofix */
@@ -238,9 +500,37 @@ type ParseOptions = {
238
500
  * Parse a runcheck type. If valid return the valid input, with warning for autofix
239
501
  * and fallback, or the errors if invalid
240
502
  */
503
+ /**
504
+ * Parses and validates input against a runcheck type schema.
505
+ * @param input - The input value to validate
506
+ * @param type - The runcheck type schema to validate against
507
+ * @param options - Parse options
508
+ * @param options.noWarnings - If true, disables fallback and autofix warnings
509
+ * @returns The parse result containing either the validated value or errors
510
+ * @example
511
+ * ```typescript
512
+ * const result = rc_parse('hello', rc_string)
513
+ * if (result.ok) {
514
+ * console.log(result.value) // 'hello'
515
+ * } else {
516
+ * console.log(result.errors) // validation errors
517
+ * }
518
+ * ```
519
+ */
241
520
  declare function rc_parse<S>(input: any, type: RcType<S>, { noWarnings }?: ParseOptions): RcParseResult<S>;
242
521
  type RcParser<T> = (input: any) => RcParseResult<T>;
243
522
  /** create a reusable parser for a certain type */
523
+ /**
524
+ * Creates a reusable parser function for a runcheck type.
525
+ * @param type - The runcheck type to create a parser for
526
+ * @returns A parser function that can be called with input values
527
+ * @example
528
+ * ```typescript
529
+ * const parseString = rc_parser(rc_string)
530
+ * const result1 = parseString('hello')
531
+ * const result2 = parseString(123)
532
+ * ```
533
+ */
244
534
  declare function rc_parser<S>(type: RcType<S>): RcParser<S>;
245
535
  /** @deprecated use rc_unwrap_or_null instead */
246
536
  declare function rc_loose_parse<S>(input: any, type: RcType<S>, options?: ParseOptions): {
@@ -270,8 +560,53 @@ declare function rc_unwrap<R>(result: RcParseResult<R>): {
270
560
  value: R;
271
561
  warnings: string[] | false;
272
562
  };
563
+ /**
564
+ * Type guard function that checks if input is valid for a given type.
565
+ * @param input - The input value to validate
566
+ * @param type - The runcheck type to validate against
567
+ * @returns True if input is valid, false otherwise (with type narrowing)
568
+ * @example
569
+ * ```typescript
570
+ * if (rc_is_valid(input, rc_string)) {
571
+ * // input is now typed as string
572
+ * console.log(input.toUpperCase())
573
+ * }
574
+ * ```
575
+ */
273
576
  declare function rc_is_valid<S>(input: any, type: RcType<S>): input is S;
577
+ /**
578
+ * Creates a validator function that acts as a type guard.
579
+ * @param type - The runcheck type to create a validator for
580
+ * @returns A validator function that can be used as a type guard
581
+ * @example
582
+ * ```typescript
583
+ * const isString = rc_validator(rc_string)
584
+ * if (isString(input)) {
585
+ * // input is now typed as string
586
+ * console.log(input.length)
587
+ * }
588
+ * ```
589
+ */
274
590
  declare function rc_validator<S>(type: RcType<S>): (input: any) => input is S;
591
+ /**
592
+ * Creates a recursive type definition for self-referencing data structures.
593
+ * @param type - A function that returns the recursive type definition
594
+ * @returns A runcheck type that can handle recursive structures
595
+ * @example
596
+ * ```typescript
597
+ * type TreeNode = {
598
+ * value: string
599
+ * children?: TreeNode[]
600
+ * }
601
+ *
602
+ * const TreeNode: RcType<TreeNode> = rc_recursive(() =>
603
+ * rc_object({
604
+ * value: rc_string,
605
+ * children: rc_array(TreeNode).optional(),
606
+ * })
607
+ * )
608
+ * ```
609
+ */
275
610
  declare function rc_recursive<T extends RcBase<any, any>>(type: () => T): T;
276
611
  type TransformOptions<T> = {
277
612
  /**
@@ -285,10 +620,62 @@ type TransformOptions<T> = {
285
620
  disableStrictOutputSchema?: boolean;
286
621
  };
287
622
  /** validate a input or subset of input and transform the valid result */
623
+ /**
624
+ * Creates a type that validates input and transforms the result.
625
+ * @param type - The input type to validate against
626
+ * @param transform - Function to transform the validated input
627
+ * @param options - Transform options
628
+ * @param options.outputSchema - Optional schema to validate the transformed output
629
+ * @param options.disableStrictOutputSchema - If true, allows loose validation of output
630
+ * @returns A runcheck type that validates input and applies transformation
631
+ * @example
632
+ * ```typescript
633
+ * const upperCaseString = rc_transform(
634
+ * rc_string,
635
+ * (str) => str.toUpperCase()
636
+ * )
637
+ * const result = upperCaseString.parse('hello') // returns 'HELLO'
638
+ * ```
639
+ */
288
640
  declare function rc_transform<Input, Transformed>(type: RcType<Input>, transform: (input: Input, inputSchema: RcType<Input>) => Transformed, { outputSchema, disableStrictOutputSchema, }?: TransformOptions<Transformed>): RcType<Transformed>;
289
641
  /** Create transforms which result can be validated with the same schema */
642
+ /**
643
+ * Creates a narrowing transformation that refines the input type.
644
+ * @param type - The input type to validate against
645
+ * @param narrow - Function to narrow the validated input to a more specific type
646
+ * @returns A runcheck type that validates and narrows the input
647
+ * @example
648
+ * ```typescript
649
+ * const positiveNumber = rc_narrow(
650
+ * rc_number,
651
+ * (n) => n > 0 ? n : 0
652
+ * )
653
+ * ```
654
+ */
290
655
  declare function rc_narrow<Input, Narrowed extends Input>(type: RcType<Input>, narrow: (input: Input, inputSchema: RcType<Input>) => Narrowed): RcType<Narrowed>;
291
656
  /** Allows the transform function to return a error if transformation is invalid */
657
+ /**
658
+ * Creates a transformation that can fail with custom error messages.
659
+ * @param type - The input type to validate against
660
+ * @param transform - Function that returns either transformed data or errors
661
+ * @param options - Transform options
662
+ * @param options.outputSchema - Optional schema to validate the transformed output
663
+ * @param options.disableStrictOutputSchema - If true, allows loose validation of output
664
+ * @returns A runcheck type that validates input and applies fallible transformation
665
+ * @example
666
+ * ```typescript
667
+ * const parseJson = rc_unsafe_transform(
668
+ * rc_string,
669
+ * (str) => {
670
+ * try {
671
+ * return { ok: true, data: JSON.parse(str) }
672
+ * } catch {
673
+ * return { ok: false, errors: 'Invalid JSON' }
674
+ * }
675
+ * }
676
+ * )
677
+ * ```
678
+ */
292
679
  declare function rc_unsafe_transform<Input, Transformed>(type: RcType<Input>, transform: (input: Input, inputSchema: RcType<Input>) => {
293
680
  ok: true;
294
681
  data: Transformed;
@@ -297,6 +684,18 @@ declare function rc_unsafe_transform<Input, Transformed>(type: RcType<Input>, tr
297
684
  errors: string | string[];
298
685
  }, { outputSchema, disableStrictOutputSchema, }?: TransformOptions<Transformed>): RcType<Transformed>;
299
686
  declare function normalizedTypeOf(input: unknown, showValueInError: boolean): string;
687
+ /**
688
+ * Assertion function that throws if the parse result contains errors.
689
+ * @param result - The parse result to assert validity for
690
+ * @throws Error if the result contains validation errors
691
+ * @example
692
+ * ```typescript
693
+ * const result = rc_parse(input, rc_string)
694
+ * rc_assert_is_valid(result)
695
+ * // result is now typed as successful result
696
+ * console.log(result.value)
697
+ * ```
698
+ */
300
699
  declare function rc_assert_is_valid<S>(result: RcParseResult<S>): asserts result is {
301
700
  ok: true;
302
701
  error: false;
@@ -308,19 +707,86 @@ declare function rc_assert_is_valid<S>(result: RcParseResult<S>): asserts result
308
707
  unwrapOr: (defaultValue: S) => S;
309
708
  unwrapOrNull: () => S | null;
310
709
  };
710
+ /**
711
+ * Parses a JSON string and validates it against a schema.
712
+ * @param jsonString - The JSON string to parse
713
+ * @param schema - The runcheck type to validate the parsed JSON against
714
+ * @param options - Parse options
715
+ * @returns The parse result containing either the validated JSON value or errors
716
+ * @example
717
+ * ```typescript
718
+ * const userSchema = rc_object({ name: rc_string, age: rc_number })
719
+ * const result = rc_parse_json('{"name":"John","age":30}', userSchema)
720
+ * ```
721
+ */
311
722
  declare function rc_parse_json<T>(jsonString: unknown, schema: RcType<T>, options?: ParseOptions): RcParseResult<T>;
312
723
  type Prettify<T> = T extends Record<string, any> ? {
313
724
  [K in keyof T]: Prettify<T[K]>;
314
725
  } : T;
315
726
  type RcPrettyInferType<T extends RcType<any>> = Prettify<RcInferType<T>>;
727
+ /**
728
+ * Type guard function that checks if a value is a runcheck type.
729
+ * @param value - The value to check
730
+ * @returns True if the value is a runcheck type, false otherwise
731
+ * @example
732
+ * ```typescript
733
+ * if (isRcType(someValue)) {
734
+ * // someValue is now typed as RcType<any>
735
+ * const result = someValue.parse(input)
736
+ * }
737
+ * ```
738
+ */
316
739
  declare function isRcType(value: any): value is RcType<any>;
317
740
  /** workaround for the typescript limitation: https://github.com/microsoft/TypeScript/issues/52295 */
741
+ /**
742
+ * Workaround for TypeScript limitation with union types.
743
+ * @param type - The type to cast as a union type
744
+ * @returns The type cast as a proper runcheck union type
745
+ * @example
746
+ * ```typescript
747
+ * const unionType = joinAsRcTypeUnion(someComplexUnionType)
748
+ * ```
749
+ */
318
750
  declare function joinAsRcTypeUnion<T>(type: T): RcType<T extends RcType<infer U> ? U : never>;
751
+ /**
752
+ * Gets the kind/name of a runcheck schema for debugging purposes.
753
+ * @param schema - The runcheck type to get the kind from
754
+ * @returns The string representation of the schema kind
755
+ * @example
756
+ * ```typescript
757
+ * const kind = getSchemaKind(rc_string) // returns 'string'
758
+ * const kind2 = getSchemaKind(rc_array(rc_number)) // returns 'number[]'
759
+ * ```
760
+ */
319
761
  declare function getSchemaKind(schema: RcType<any>): string;
762
+ /**
763
+ * Converts a runcheck type or parse result to a Standard Schema V1.
764
+ * @param schemaOrResult - The runcheck type or parse result to convert
765
+ * @param options - Conversion options
766
+ * @param options.errorOnWarnings - If true, treat warnings as errors
767
+ * @param options.onWarnings - Callback function to handle warnings
768
+ * @returns A Standard Schema V1 compatible object
769
+ * @example
770
+ * ```typescript
771
+ * const standardSchema = rc_to_standard(rc_string)
772
+ * const result = standardSchema['~standard'].validate('hello')
773
+ * ```
774
+ */
320
775
  declare function rc_to_standard<T>(schemaOrResult: RcType<T> | RcParseResult<T>, { errorOnWarnings, onWarnings, }?: {
321
776
  errorOnWarnings?: boolean;
322
777
  onWarnings?: (warnings: string[]) => void;
323
778
  }): StandardSchemaV1<T>;
779
+ /**
780
+ * Converts a Standard Schema V1 to a runcheck type.
781
+ * @param standardSchema - The Standard Schema V1 to convert
782
+ * @param kind - Optional custom kind name for error messages
783
+ * @returns A runcheck type that wraps the standard schema
784
+ * @example
785
+ * ```typescript
786
+ * const rcType = rc_from_standard(someStandardSchema)
787
+ * const result = rcType.parse(input)
788
+ * ```
789
+ */
324
790
  declare function rc_from_standard<T>(standardSchema: StandardSchemaV1<any, T>,
325
791
  /** use this kind instead of the default one in error messages (standard_schema_${standard.vendor}@${standard.version}) */
326
792
  kind?: string): RcType<T>;
package/dist/runcheck.js CHANGED
@@ -1,2 +1,2 @@
1
- import{$,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,_,a,aa,b,ba,c,ca,d,da,e,ea,f,fa,g,ga,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-QNKGO7DW.js";export{R as RcValidationError,p as defaultProps,ea as getSchemaKind,n as getWarningOrErrorWithPath,$ as isObject,ca as isRcType,da as joinAsRcTypeUnion,Z as normalizedTypeOf,o as parse,s as rc_any,G as rc_array,K as rc_array_filter_from_schema,_ as rc_assert_is_valid,u as rc_boolean,x as rc_date,B as rc_default,I as rc_disable_loose_array,k as rc_discriminated_union,l as rc_discriminated_union_builder,f as rc_enable_obj_strict,ga as rc_from_standard,H as rc_get_array_item_type,a as rc_get_from_key_as_fallback,d as rc_get_obj_shape,y as rc_instanceof,m as rc_intersection,T as rc_is_valid,z as rc_literals,J as rc_loose_array,O as rc_loose_parse,F as rc_loose_record,X as rc_narrow,r as rc_null,C as rc_nullish_default,w as rc_number,j as rc_obj_builder,c as rc_obj_extends,g as rc_obj_merge,i as rc_obj_omit,h as rc_obj_pick,e as rc_obj_strict,b as rc_object,M as rc_parse,ba as rc_parse_json,N as rc_parser,E as rc_record,V as rc_recursive,D as rc_safe_fallback,v as rc_string,fa as rc_to_standard,W as rc_transform,L as rc_tuple,q as rc_undefined,A as rc_union,t as rc_unknown,Y as rc_unsafe_transform,S as rc_unwrap,Q as rc_unwrap_or,P as rc_unwrap_or_null,U as rc_validator,aa as snakeCase};
1
+ import{$,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,_,a,aa,b,ba,c,ca,d,da,e,ea,f,fa,g,ga,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-WENGZHOX.js";export{R as RcValidationError,p as defaultProps,ea as getSchemaKind,n as getWarningOrErrorWithPath,$ as isObject,ca as isRcType,da as joinAsRcTypeUnion,Z as normalizedTypeOf,o as parse,s as rc_any,G as rc_array,K as rc_array_filter_from_schema,_ as rc_assert_is_valid,u as rc_boolean,x as rc_date,B as rc_default,I as rc_disable_loose_array,k as rc_discriminated_union,l as rc_discriminated_union_builder,f as rc_enable_obj_strict,ga as rc_from_standard,H as rc_get_array_item_type,a as rc_get_from_key_as_fallback,d as rc_get_obj_shape,y as rc_instanceof,m as rc_intersection,T as rc_is_valid,z as rc_literals,J as rc_loose_array,O as rc_loose_parse,F as rc_loose_record,X as rc_narrow,r as rc_null,C as rc_nullish_default,w as rc_number,j as rc_obj_builder,c as rc_obj_extends,g as rc_obj_merge,i as rc_obj_omit,h as rc_obj_pick,e as rc_obj_strict,b as rc_object,M as rc_parse,ba as rc_parse_json,N as rc_parser,E as rc_record,V as rc_recursive,D as rc_safe_fallback,v as rc_string,fa as rc_to_standard,W as rc_transform,L as rc_tuple,q as rc_undefined,A as rc_union,t as rc_unknown,Y as rc_unsafe_transform,S as rc_unwrap,Q as rc_unwrap_or,P as rc_unwrap_or_null,U as rc_validator,aa as snakeCase};
2
2
  //# sourceMappingURL=runcheck.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "runcheck",
3
3
  "description": "A tiny (less than 2 KiB Gzipped) and treeshakable! lib for typescript runtime type checks with autofix support",
4
- "version": "1.12.0",
4
+ "version": "1.13.0",
5
5
  "license": "MIT",
6
6
  "files": [
7
7
  "dist"