is-kit 1.12.1 → 1.14.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.
package/README.md CHANGED
@@ -36,8 +36,8 @@ It helps you write small `isFoo` functions, compose them into **richer runtime c
36
36
  - **Validate object** shapes and collections
37
37
  - **Parse or assert** `unknown` values without a large schema framework
38
38
 
39
- [📚 Documentation Site](https://is-kit-docs.vercel.app/) ·
40
- [🧭 Practical Guides](https://is-kit-docs.vercel.app/guides)
39
+ [📚 Documentation Site](https://is-kit.dev/) ·
40
+ [🧭 Practical Guides](https://is-kit.dev/guides)
41
41
 
42
42
  > Best for **app-internal narrowing, filtering, and reusable guards**.
43
43
 
@@ -79,6 +79,14 @@ vlt install is-kit
79
79
  ```
80
80
 
81
81
  ESM and CJS builds are available for npm consumers, and bundled types are included.
82
+ The published declarations support TypeScript 5.7 and newer. CI compiles the
83
+ packed package against every TypeScript minor from 5.7 through the current
84
+ stable release.
85
+
86
+ TypeScript 7 can type-check is-kit declarations, but TypeScript 7.0 does not
87
+ ship the legacy JavaScript Compiler API. Tools that need that API can follow
88
+ the official [TypeScript 7 side-by-side guidance](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6-0)
89
+ and use `@typescript/typescript6` for programmatic access.
82
90
 
83
91
  vlt requires registry configuration before installing a package by name. Run
84
92
  `vlt setup` once if a registry has not been configured yet.
@@ -227,6 +235,7 @@ If you are new to the library, these are the pieces to remember:
227
235
  - `define<T>(fn)` turns a boolean check into a typed guard.
228
236
  - `lazy(factory)` defers a guard definition so recursive structures can refer to themselves.
229
237
  - `predicateToRefine(fn)` upgrades an existing predicate so it can participate in narrowing chains.
238
+ - `refineKey(key, guard)` carries a child refinement back onto its parent type.
230
239
  - `struct({...})` builds an object-shape guard.
231
240
  - `safeParse(guard, value)` gives you a small tagged result object.
232
241
  - `assert(guard, value)` throws if the value does not match.
@@ -358,7 +367,32 @@ const isTree: Predicate<Tree> = lazy(() =>
358
367
 
359
368
  `lazy` does not detect circular references in the input value.
360
369
 
361
- ### 7. Handle null and undefined explicitly
370
+ ### 7. Refine properties on existing types
371
+
372
+ Use the property helpers when an object is already typed and one child value
373
+ needs additional narrowing.
374
+
375
+ ```ts
376
+ import { isString, refineDefinedKey, refineIndex, refineKey } from 'is-kit';
377
+
378
+ const hasStringValue = refineKey('value', isString);
379
+ const hasDefinedStringLabel = refineDefinedKey('label', isString);
380
+ const hasStringAtZero = refineIndex(0, isString);
381
+ ```
382
+
383
+ - `refineKey` refines one required property using normal property access.
384
+ - `refineDefinedKey` returns `false` for a missing or `undefined` property.
385
+ - `refineIndex` returns `false` for an out-of-bounds, sparse, or `undefined`
386
+ own element.
387
+
388
+ The property helpers accept inherited values and accessors. The index helper
389
+ requires an own element so a sparse hole cannot pass through an inherited
390
+ numeric property.
391
+
392
+ Each key or index must identify one concrete runtime location. This keeps one
393
+ successful lookup from incorrectly narrowing multiple properties.
394
+
395
+ ### 8. Handle null and undefined explicitly
362
396
 
363
397
  Use the nullish helpers to say exactly what is allowed.
364
398
 
@@ -392,7 +426,7 @@ Use `isNil` for a direct nullish check instead of hand-rolling
392
426
  `isNull(x) || isUndefined(x)`. Use `isNotNil` for the inverse check or to
393
427
  remove nullish values while preserving `Array.prototype.filter` narrowing.
394
428
 
395
- ### 8. Parse or assert unknown input
429
+ ### 9. Parse or assert unknown input
396
430
 
397
431
  Use `safeParse` when you want a result object, and `assert` when invalid data should stop execution.
398
432
 
@@ -411,7 +445,7 @@ assert(isString, input, 'Expected a string');
411
445
  input.toUpperCase();
412
446
  ```
413
447
 
414
- ### 9. Decode and validate JSON input
448
+ ### 10. Decode and validate JSON input
415
449
 
416
450
  Use `safeJsonParse` at a JSON text boundary. It decodes the text, treats the
417
451
  result as `unknown`, and only returns the value after the guard accepts it.
@@ -443,7 +477,7 @@ if (result.valid) {
443
477
  coercion and does not depend on a transport or schema format such as HTTP or
444
478
  OpenAPI.
445
479
 
446
- ### 10. Narrow object keys
480
+ ### 11. Narrow object keys
447
481
 
448
482
  Use key helpers when the important part of a value is one property.
449
483
 
@@ -486,6 +520,11 @@ if (isAdmin(value)) {
486
520
  }
487
521
  ```
488
522
 
523
+ Singleton literal keys preserve key-specific narrowing. Union, broad, patterned,
524
+ or branded key domains remain usable as runtime checks, but they narrow only to
525
+ an object—or to the base guard type for `narrowKeyTo`—because one runtime key
526
+ cannot prove that every possible key was checked.
527
+
489
528
  ## 🌍 Real-world use cases
490
529
 
491
530
  Here are the kinds of problems `is-kit` is especially good at solving:
@@ -521,7 +560,9 @@ if (parsed.valid) {
521
560
  sync with an existing object type. Optional keys in `T` must still be declared
522
561
  with `optionalKey(...)`; this makes drift visible when the target type changes.
523
562
  OpenAPI-generated response types are one useful case, but the helper is not an
524
- OpenAPI validator or schema generator.
563
+ OpenAPI validator or schema generator. Drift detection is limited to
564
+ string-keyed properties; numeric and symbol properties are excluded from the
565
+ checked shape and cannot be validated by the resulting guard.
525
566
 
526
567
  ### Safe array filtering
527
568
 
@@ -553,7 +594,7 @@ The library is organized around a few small building blocks:
553
594
 
554
595
  - **Primitives**: `isString`, `isNumber`, `isBoolean`, `isInteger`, ...
555
596
  - **Composition**: `define`, `and`, `andAll`, `or`, `not`, `oneOf`
556
- - **Object shapes**: `struct`, `optionalKey`, `hasKey`, `hasKeys`, `narrowKeyTo`
597
+ - **Object shapes**: `struct`, `optionalKey`, `hasKey`, `hasKeys`, `narrowKeyTo`, `refineKey`, `refineDefinedKey`, `refineIndex`
557
598
  - **Collections**: `arrayOf`, `nonEmptyArrayOf`, `tupleOf`, `setOf`, `mapOf`, `recordOf`
558
599
  - **Literals**: `oneOfValues`, `equals`, `equalsBy`, `equalsKey`
559
600
  - **Nullish handling**: `isNil`, `isNotNil`, `nullable`, `nonNull`, `nullish`, `optional`, `required`
@@ -599,12 +640,15 @@ public root exports are planned for removal.
599
640
 
600
641
  For detailed API pages and more examples, see:
601
642
 
602
- - [Practical guides](https://is-kit-docs.vercel.app/guides)
603
- - [API reference](https://is-kit-docs.vercel.app/api-reference)
604
- - [Documentation home](https://is-kit-docs.vercel.app/)
643
+ - [Practical guides](https://is-kit.dev/guides)
644
+ - [Keep hand-written type guards in sync with TypeScript types](https://is-kit.dev/guides/keep-type-guards-in-sync)
645
+ - [Use is-kit with the TypeScript Compiler API](https://is-kit.dev/guides/typescript-compiler-api)
646
+ - [Validate unknown without a schema library](https://is-kit.dev/guides/validate-unknown-without-schema-library)
647
+ - [API reference](https://is-kit.dev/api-reference)
648
+ - [Documentation home](https://is-kit.dev/)
605
649
 
606
650
  Start with [How to safely filter null and undefined from arrays in
607
- TypeScript](https://is-kit-docs.vercel.app/guides/filter-null-and-undefined).
651
+ TypeScript](https://is-kit.dev/guides/filter-null-and-undefined).
608
652
 
609
653
  ## 👨‍💻 Development
610
654
 
package/dist/index.d.mts CHANGED
@@ -6,10 +6,10 @@
6
6
  * - Use nullable, optional, or nullish to widen guards for nullish values.
7
7
  * - Use struct or typedStruct for object-shape guards.
8
8
  */
9
- /** Predicate that accepts an unknown value and narrows it to `T`. */
10
- type Predicate<T> = (value: unknown) => value is T;
11
9
  /** Refinement that narrows a known input type `A` to its subtype `B`. */
12
10
  type Refinement<A, B extends A> = (value: A) => value is B;
11
+ /** Predicate that accepts an unknown value and narrows it to `T`. */
12
+ type Predicate<T> = Refinement<unknown, T>;
13
13
  /** Readability alias for {@link Predicate}. */
14
14
  type Guard<T> = Predicate<T>;
15
15
  /** Readability alias for {@link Refinement}. */
@@ -27,8 +27,8 @@ type ParseResult<T> = {
27
27
  } | {
28
28
  valid: false;
29
29
  };
30
- /** Extracts the narrowed output type from a predicate. */
31
- type GuardedOf<F> = F extends ((value: unknown) => value is infer G) ? G : never;
30
+ /** Extracts the narrowed output type from a predicate or refinement. */
31
+ type GuardedOf<F> = F extends Refinement<infer A, infer B> ? B : never;
32
32
  /** Extracts guard outputs that remain assignable to a known input type. */
33
33
  type GuardedWithin<Fs, A> = Extract<Fs extends readonly unknown[] ? GuardedOf<Fs[number]> : never, A>;
34
34
 
@@ -92,7 +92,8 @@ type OptionalObjectKeys<T> = {
92
92
  */
93
93
  type RequiredObjectKeys<T> = Exclude<keyof T, OptionalObjectKeys<T>>;
94
94
  /**
95
- * Schema shape checked against an existing object type by `typedStruct`.
95
+ * String-keyed schema shape checked against an existing object type by
96
+ * `typedStruct`. Numeric and symbol properties are excluded.
96
97
  */
97
98
  type TypedStructShape<T extends object> = {
98
99
  readonly [K in Extract<RequiredObjectKeys<T>, string>]-?: Predicate<T[K]>;
@@ -139,6 +140,26 @@ declare function assert<A, B extends A>(refine: Refine<A, B>, value: A, message?
139
140
  declare function define<T>(fn: (value: unknown) => value is T): Predicate<T>;
140
141
  declare function define<T>(fn: (value: unknown) => boolean): Predicate<T>;
141
142
 
143
+ /** Detects whether a type represents more than one possible value. */
144
+ type IsUnion<Value, Whole = Value> = Value extends Whole ? [Whole] extends [Value] ? false : true : never;
145
+ /** Keeps only one literal property key so one lookup cannot narrow other keys. */
146
+ type SinglePropertyKey<Key extends PropertyKey> = [Key] extends [never] ? never : true extends IsUnion<Key> ? never : {} extends Record<Key, never> ? never : Key;
147
+ /** Applies the singleton-key constraint to every member of a key tuple. */
148
+ type SinglePropertyKeys<Keys extends readonly PropertyKey[]> = {
149
+ [Index in keyof Keys]: Keys[Index] & SinglePropertyKey<Keys[Index]>;
150
+ };
151
+ /** Narrows one concrete key, or only object-ness for a multi-value key domain. */
152
+ type KeyPresence<Key extends PropertyKey> = [
153
+ SinglePropertyKey<Key>
154
+ ] extends [never] ? object : Record<Key, unknown>;
155
+ /** Narrows concrete key arguments, or only object-ness when any may vary. */
156
+ type KeyPresences<Keys extends readonly PropertyKey[]> = true extends IsUnion<Keys> ? object : [Keys] extends [SinglePropertyKeys<Keys>] ? Record<Keys[number], unknown> : object;
157
+ /** Keeps only one non-negative integer literal that identifies an array index. */
158
+ type ArrayIndex<Index extends number> = SinglePropertyKey<Index> extends never ? never : `${Index}` extends `-${string}` ? never : `${Index}` extends `${bigint}` ? Index : never;
159
+
160
+ type EqualsKeyPredicate<K extends PropertyKey, T> = [
161
+ SinglePropertyKey<K>
162
+ ] extends [never] ? Predicate<object> : <A extends Record<K, unknown>>(input: unknown) => input is A & Record<K, T>;
142
163
  /**
143
164
  * Creates a guard that matches values equal to the provided target using `Object.is` semantics.
144
165
  *
@@ -159,26 +180,32 @@ declare function equalsBy<F extends Predicate<unknown>, K>(guard: F, selector: (
159
180
  /**
160
181
  * Creates a guard that matches objects having a key equal to the target value.
161
182
  *
162
- * @param key Property key to compare.
183
+ * @param key Property key to compare; singleton literals narrow that property.
163
184
  * @param target Value to compare using `Object.is`.
164
- * @returns Predicate narrowing to objects where `key` exists and equals `target`.
185
+ * @returns Predicate with key-specific narrowing for a singleton literal key,
186
+ * or object-only narrowing for a multi-value key domain.
165
187
  */
166
- declare function equalsKey<K extends PropertyKey, const T>(key: K, target: T): <A extends Record<K, unknown>>(input: unknown) => input is A & Record<K, T>;
188
+ declare function equalsKey<const K extends PropertyKey, const T>(key: K, target: T): EqualsKeyPredicate<K, T>;
167
189
 
190
+ type NarrowKeyPredicate<A, K extends PropertyKey, T> = [
191
+ SinglePropertyKey<K>
192
+ ] extends [never] ? Predicate<A> : Predicate<A & Record<K, T>>;
168
193
  /**
169
194
  * Checks whether a value has the specified own key.
170
195
  *
171
196
  * @param key Property key to check.
172
- * @returns Predicate narrowing to an object with the key present.
197
+ * @returns Predicate with key-specific narrowing for a singleton literal key,
198
+ * or object-only narrowing for a multi-value key domain.
173
199
  */
174
- declare const hasKey: <K extends PropertyKey>(key: K) => Predicate<Record<K, unknown>>;
200
+ declare function hasKey<const K extends PropertyKey>(key: K): Predicate<KeyPresence<K>>;
175
201
  /**
176
202
  * Checks whether a value has all specified own keys.
177
203
  *
178
204
  * @param keys Property keys to check.
179
- * @returns Predicate narrowing to an object with all keys present.
205
+ * @returns Predicate with key-specific narrowing when every argument is a
206
+ * singleton literal key, or object-only narrowing otherwise.
180
207
  */
181
- declare const hasKeys: <const KS extends readonly [PropertyKey, ...PropertyKey[]]>(...keys: KS) => Predicate<Record<KS[number], unknown>>;
208
+ declare function hasKeys<const KS extends readonly [PropertyKey, ...PropertyKey[]]>(...keys: KS): Predicate<KeyPresences<KS>>;
182
209
  /**
183
210
  * Builds a guard that narrows a specific key to the provided literal value.
184
211
  *
@@ -187,11 +214,45 @@ declare const hasKeys: <const KS extends readonly [PropertyKey, ...PropertyKey[]
187
214
  * `{ [key]: target }`.
188
215
  *
189
216
  * @param guard Base guard for objects that include `key`.
190
- * @param key Property key to narrow.
217
+ * @param key Property key to compare; singleton literals narrow that property.
191
218
  * @returns Builder that takes a literal `target` and returns a guard that
192
- * narrows `key` to that literal.
219
+ * narrows a singleton `key` to that literal. Multi-value key domains preserve
220
+ * only the base guard's type.
221
+ */
222
+ declare function narrowKeyTo<A, const K extends keyof A & PropertyKey>(guard: Guard<A>, key: K): <const T extends A[K]>(target: T) => NarrowKeyPredicate<A, K, T>;
223
+
224
+ /**
225
+ * Lifts a required-property refinement to its parent object.
226
+ * @param key Single literal key of the required property to refine.
227
+ * @param refinement Refinement applied to the property value.
228
+ * @returns Refinement that preserves the parent type and narrows the property.
229
+ * @example
230
+ * const hasIdentifierExpression = refineKey('expression', ts.isIdentifier);
231
+ */
232
+ declare function refineKey<const K extends PropertyKey, PropertyInput, PropertyOutput extends PropertyInput>(key: K & SinglePropertyKey<K>, refinement: Refinement<PropertyInput, PropertyOutput>): <ObjectType extends Record<K, PropertyInput>>(value: ObjectType) => value is ObjectType & Record<K, PropertyOutput>;
233
+ /**
234
+ * Lifts a defined optional-property refinement to its parent object.
235
+ * @param key Single literal key of the optional property to refine when defined.
236
+ * @param refinement Refinement applied only to a defined property value.
237
+ * @returns Refinement that requires and narrows the property.
238
+ * @example
239
+ * const hasCallInitializer = refineDefinedKey(
240
+ * 'initializer',
241
+ * ts.isCallExpression
242
+ * );
243
+ */
244
+ declare function refineDefinedKey<const K extends PropertyKey, PropertyInput, PropertyOutput extends PropertyInput>(key: K & SinglePropertyKey<K>, refinement: Refinement<PropertyInput, PropertyOutput>): <ObjectType extends Partial<Record<K, PropertyInput | undefined>>>(value: ObjectType) => value is ObjectType & Record<K, Exclude<PropertyOutput, undefined>>;
245
+ /**
246
+ * Refines one defined own element of a readonly array.
247
+ * @param index Non-negative integer literal identifying the own element.
248
+ * @param refinement Refinement applied only to a defined element.
249
+ * @returns Refinement that narrows the selected index.
250
+ * @example
251
+ * const hasStringFirstArgument = refineIndex(0, ts.isStringLiteral);
193
252
  */
194
- declare function narrowKeyTo<A, K extends keyof A>(guard: Guard<A>, key: K): <const T extends A[K]>(target: T) => Predicate<A & Record<K, T>>;
253
+ declare function refineIndex<const Index extends number, ElementInput, ElementOutput extends ElementInput>(index: ArrayIndex<Index>, refinement: Refinement<ElementInput, ElementOutput>): Refinement<readonly ElementInput[], readonly ElementInput[] & {
254
+ readonly [K in Index]: Exclude<ElementOutput, undefined>;
255
+ }>;
195
256
 
196
257
  /**
197
258
  * Creates a predicate whose implementation is initialized on first use.
@@ -204,14 +265,28 @@ declare function narrowKeyTo<A, K extends keyof A>(guard: Guard<A>, key: K): <co
204
265
  */
205
266
  declare function lazy<T>(factory: () => Predicate<T>): Predicate<T>;
206
267
 
268
+ type RefinementInputs<In, Outputs extends readonly unknown[]> = readonly [
269
+ In,
270
+ ...Outputs
271
+ ];
272
+ /** Builds an ordered refinement tuple from its initial input and output tuple. */
273
+ type RefinementsFromOutputs<In, Outputs extends readonly unknown[]> = {
274
+ [K in keyof Outputs]: Refinement<RefinementInputs<In, Outputs>[K & keyof RefinementInputs<In, Outputs>], Outputs[K] & RefinementInputs<In, Outputs>[K & keyof RefinementInputs<In, Outputs>]>;
275
+ };
276
+ /** Returns the last tuple member, or a fallback for an empty tuple. */
277
+ type LastOr<Default, T extends readonly unknown[]> = T extends readonly [
278
+ ...unknown[],
279
+ infer Tail
280
+ ] ? Tail : Default;
281
+
207
282
  /**
208
- * Combines a precondition guard with an additional refinement to narrow the type.
283
+ * Combines a precondition refinement with an additional refinement.
209
284
  * Prefer this over hand-written `precondition(x) && condition(x)` when the
210
- * composed predicate should be reused as a guard.
285
+ * composed refinement should be reused.
211
286
  *
212
287
  * @param precondition Broad guard evaluated first; short-circuits on failure.
213
288
  * @param condition Refinement evaluated only when `precondition` passes.
214
- * @returns Predicate that narrows the input to a subtype.
289
+ * @returns Refinement that preserves the precondition's input domain.
215
290
  * @example
216
291
  * const isPositiveNumber = and(
217
292
  * isNumber,
@@ -220,14 +295,16 @@ declare function lazy<T>(factory: () => Predicate<T>): Predicate<T>;
220
295
  * @see andAll
221
296
  */
222
297
  declare function and<A, B extends A>(precondition: Guard<A>, condition: Refine<A, B>): Predicate<B>;
298
+ declare function and<A, B extends A, C extends B>(precondition: Refinement<A, B>, condition: Refine<NoInfer<B>, C>): Refinement<A, C>;
223
299
  /**
224
- * Chains a sequence of refinements after a precondition, returning the final guard type.
300
+ * Chains refinements while preserving the precondition's input domain.
225
301
  * Use this instead of nested `&&` checks when each step should keep narrowing
226
302
  * the next refinement.
303
+ * Pass a generic readonly chain as one tuple to preserve its final narrowing.
227
304
  *
228
305
  * @param precondition Initial guard applied first.
229
306
  * @param steps Subsequent refinements applied in order.
230
- * @returns Guard reflecting the result of the refinement chain.
307
+ * @returns Refinement reflecting the final result of the chain.
231
308
  * @example
232
309
  * const isPublicTitle = andAll(isString, minLength(4), startsWithPublic);
233
310
  * @see and
@@ -235,18 +312,27 @@ declare function and<A, B extends A>(precondition: Guard<A>, condition: Refine<A
235
312
  declare function andAll<A>(precondition: Guard<A>): Guard<A>;
236
313
  declare function andAll<A, B extends A>(precondition: Guard<A>, step1: Refine<A, B>): Guard<B>;
237
314
  declare function andAll<A, B extends A, C extends B>(precondition: Guard<A>, step1: Refine<A, B>, step2: Refine<B, C>): Guard<C>;
238
- /**
239
- * Logical OR over multiple guards.
240
- * Prefer this over hand-written `guardA(x) || guardB(x)` when the composed
241
- * predicate should be reused as a guard.
242
- *
243
- * @param guards Guards to evaluate; passes if any guard passes.
244
- * @returns Guard for the union of all guarded types.
315
+ declare function andAll<A, Chain extends readonly Refine<unknown, unknown>[]>(precondition: Guard<A>, ...steps: Chain & RefineChain<A, Chain>): Guard<ChainResult<A, Chain>>;
316
+ declare function andAll<A, B extends A>(precondition: Refinement<A, B>): Refinement<A, B>;
317
+ declare function andAll<A, B extends A, C extends B>(precondition: Refinement<A, B>, step1: Refine<NoInfer<B>, C>): Refinement<A, C>;
318
+ declare function andAll<A, B extends A, C extends B, D extends C>(precondition: Refinement<A, B>, step1: Refine<NoInfer<B>, C>, step2: Refine<NoInfer<C>, D>): Refinement<A, D>;
319
+ declare function andAll<A, B extends A, Chain extends readonly unknown[]>(precondition: Refinement<A, B>, ...steps: Chain & RefineChain<NoInfer<B>, Chain>): Refinement<A, ChainResult<B, Chain>>;
320
+ declare function andAll<A, B extends A, Outputs extends readonly B[]>(precondition: Refinement<A, B>, steps: RefinementsFromOutputs<NoInfer<B>, Outputs>): Refinement<A, LastOr<B, Outputs>>;
321
+ declare function andAll<A, B extends A, Outputs extends B[]>(precondition: Refinement<A, B>, ...steps: readonly unknown[] & RefinementsFromOutputs<B, Outputs>): Refinement<A, LastOr<B, Outputs>>;
322
+ declare function andAll<A, B extends A>(precondition: Refinement<A, B>, ...steps: readonly Refine<NoInfer<B>, NoInfer<B>>[]): Refinement<A, B>;
323
+ /**
324
+ * Logical OR over refinements sharing an input domain.
325
+ * Prefer this over hand-written `refineA(x) || refineB(x)` when the composed
326
+ * refinement should be reused.
327
+ *
328
+ * @param refinements Refinements to evaluate; passes if any refinement passes.
329
+ * @returns Refinement for the union of all narrowed types.
245
330
  * @example
246
331
  * const isId = or(isString, isNumber);
247
332
  * @see oneOf
248
333
  */
249
334
  declare function or<P extends readonly Guard<unknown>[]>(...guards: P): Guard<OutOfGuards<P>>;
335
+ declare function or<A, B extends A, Rest extends readonly Refinement<A, A>[]>(first: Refinement<A, B>, ...rest: Rest): Refinement<A, B | GuardedOf<Rest[number]>>;
250
336
  /**
251
337
  * Adapts a guard so it can be used as a refinement within a known supertype.
252
338
  *
@@ -661,13 +747,14 @@ declare function nonEmptyArrayOf<F extends Predicate<unknown>>(elementGuard: F):
661
747
  declare function mapOf<KF extends Predicate<unknown>, VF extends Predicate<unknown>>(keyGuard: KF, valueGuard: VF): Predicate<ReadonlyMap<GuardedOf<KF>, GuardedOf<VF>>>;
662
748
 
663
749
  /**
664
- * Combines multiple guards; passes when any one guard matches.
750
+ * Combines refinements sharing an input domain.
665
751
  *
666
- * @param guards One or more type guards/refinements to try.
667
- * @returns Predicate that narrows to the union of guarded types.
752
+ * @param refinements One or more refinements to try.
753
+ * @returns Refinement that narrows to the union of matching types.
668
754
  */
669
755
  declare function oneOf<Fs extends readonly Predicate<unknown>[]>(...guards: Fs): Predicate<GuardedOf<Fs[number]>>;
670
756
  declare function oneOf<A, Fs extends readonly Predicate<A>[]>(...guards: Fs): (input: A) => input is GuardedWithin<Fs, A>;
757
+ declare function oneOf<A, B extends A, Rest extends readonly Refinement<A, A>[]>(first: Refinement<A, B>, ...rest: Rest): Refinement<A, B | GuardedOf<Rest[number]>>;
671
758
 
672
759
  /**
673
760
  * Creates a guard that matches when the input is one of the provided literal values.
@@ -721,7 +808,9 @@ declare function optionalKey<G extends Predicate<unknown>>(guard: G): OptionalSc
721
808
  declare function struct<const S extends SchemaShape<S>>(schema: S, options?: StructOptions): Predicate<InferSchema<S>>;
722
809
 
723
810
  /**
724
- * Creates a `struct` builder checked against an existing object type.
811
+ * Creates a `struct` builder checked against an existing string-keyed object
812
+ * type. Numeric and symbol properties are excluded from the checked shape and
813
+ * cannot be validated by the resulting guard.
725
814
  * Optional target keys must also be declared with `optionalKey` so type drift
726
815
  * stays visible when the target type changes.
727
816
  *
@@ -807,4 +896,4 @@ declare const everyOwnEnumerableEntry: (values: Record<string, unknown>, keyPred
807
896
  */
808
897
  declare const toBooleanPredicates: <A>(predicates: readonly ((value: A) => boolean)[]) => ReadonlyArray<(value: A) => boolean>;
809
898
 
810
- export { type ChainResult, type Guard, type GuardedOf, type GuardedWithin, type InferSchema, type NoExtraKeys, type OptionalObjectKeys, type OptionalSchemaField, type OutOfGuards, type ParseResult, type Predicate, type Primitive, type Refine, type RefineChain, type Refinement, type RequiredObjectKeys, type Schema, type SchemaField, type StructOptions, type TypedStructFields, type TypedStructShape, and, andAll, arrayOf, assert, define, equals, equalsBy, equalsKey, everyArrayValue, everyMapEntry, everyOwnEnumerableEntry, everySetValue, everyTupleValue, guardIn, hasKey, hasKeys, isArray, isArrayBuffer, isAsyncIterable, isBigInt, isBlob, isBoolean, isDataView, isDate, isError, isFile, isFiniteNumber, isFunction, isInfiniteNumber, isInstanceOf, isInteger, isIterable, isMap, isNaN, isNegative, isNil, isNotNil, isNull, isNumber, isNumberPrimitive, isObject, isPlainObject, isPositive, isPrimitive, isPromiseLike, isRegExp, isSafeInteger, isSet, isString, isSymbol, isTypedArray, isURL, isUndefined, isWeakMap, isWeakSet, isZero, lazy, mapOf, narrowKeyTo, nonEmptyArrayOf, nonNull, not, nullable, nullish, oneOf, oneOfValues, optional, optionalKey, or, predicateToRefine, recordOf, required, safeJsonParse, safeParse, safeParseWith, setOf, struct, toBooleanPredicates, tupleOf, typedStruct };
899
+ export { type ChainResult, type Guard, type GuardedOf, type GuardedWithin, type InferSchema, type NoExtraKeys, type OptionalObjectKeys, type OptionalSchemaField, type OutOfGuards, type ParseResult, type Predicate, type Primitive, type Refine, type RefineChain, type Refinement, type RequiredObjectKeys, type Schema, type SchemaField, type StructOptions, type TypedStructFields, type TypedStructShape, and, andAll, arrayOf, assert, define, equals, equalsBy, equalsKey, everyArrayValue, everyMapEntry, everyOwnEnumerableEntry, everySetValue, everyTupleValue, guardIn, hasKey, hasKeys, isArray, isArrayBuffer, isAsyncIterable, isBigInt, isBlob, isBoolean, isDataView, isDate, isError, isFile, isFiniteNumber, isFunction, isInfiniteNumber, isInstanceOf, isInteger, isIterable, isMap, isNaN, isNegative, isNil, isNotNil, isNull, isNumber, isNumberPrimitive, isObject, isPlainObject, isPositive, isPrimitive, isPromiseLike, isRegExp, isSafeInteger, isSet, isString, isSymbol, isTypedArray, isURL, isUndefined, isWeakMap, isWeakSet, isZero, lazy, mapOf, narrowKeyTo, nonEmptyArrayOf, nonNull, not, nullable, nullish, oneOf, oneOfValues, optional, optionalKey, or, predicateToRefine, recordOf, refineDefinedKey, refineIndex, refineKey, required, safeJsonParse, safeParse, safeParseWith, setOf, struct, toBooleanPredicates, tupleOf, typedStruct };
package/dist/index.d.ts CHANGED
@@ -6,10 +6,10 @@
6
6
  * - Use nullable, optional, or nullish to widen guards for nullish values.
7
7
  * - Use struct or typedStruct for object-shape guards.
8
8
  */
9
- /** Predicate that accepts an unknown value and narrows it to `T`. */
10
- type Predicate<T> = (value: unknown) => value is T;
11
9
  /** Refinement that narrows a known input type `A` to its subtype `B`. */
12
10
  type Refinement<A, B extends A> = (value: A) => value is B;
11
+ /** Predicate that accepts an unknown value and narrows it to `T`. */
12
+ type Predicate<T> = Refinement<unknown, T>;
13
13
  /** Readability alias for {@link Predicate}. */
14
14
  type Guard<T> = Predicate<T>;
15
15
  /** Readability alias for {@link Refinement}. */
@@ -27,8 +27,8 @@ type ParseResult<T> = {
27
27
  } | {
28
28
  valid: false;
29
29
  };
30
- /** Extracts the narrowed output type from a predicate. */
31
- type GuardedOf<F> = F extends ((value: unknown) => value is infer G) ? G : never;
30
+ /** Extracts the narrowed output type from a predicate or refinement. */
31
+ type GuardedOf<F> = F extends Refinement<infer A, infer B> ? B : never;
32
32
  /** Extracts guard outputs that remain assignable to a known input type. */
33
33
  type GuardedWithin<Fs, A> = Extract<Fs extends readonly unknown[] ? GuardedOf<Fs[number]> : never, A>;
34
34
 
@@ -92,7 +92,8 @@ type OptionalObjectKeys<T> = {
92
92
  */
93
93
  type RequiredObjectKeys<T> = Exclude<keyof T, OptionalObjectKeys<T>>;
94
94
  /**
95
- * Schema shape checked against an existing object type by `typedStruct`.
95
+ * String-keyed schema shape checked against an existing object type by
96
+ * `typedStruct`. Numeric and symbol properties are excluded.
96
97
  */
97
98
  type TypedStructShape<T extends object> = {
98
99
  readonly [K in Extract<RequiredObjectKeys<T>, string>]-?: Predicate<T[K]>;
@@ -139,6 +140,26 @@ declare function assert<A, B extends A>(refine: Refine<A, B>, value: A, message?
139
140
  declare function define<T>(fn: (value: unknown) => value is T): Predicate<T>;
140
141
  declare function define<T>(fn: (value: unknown) => boolean): Predicate<T>;
141
142
 
143
+ /** Detects whether a type represents more than one possible value. */
144
+ type IsUnion<Value, Whole = Value> = Value extends Whole ? [Whole] extends [Value] ? false : true : never;
145
+ /** Keeps only one literal property key so one lookup cannot narrow other keys. */
146
+ type SinglePropertyKey<Key extends PropertyKey> = [Key] extends [never] ? never : true extends IsUnion<Key> ? never : {} extends Record<Key, never> ? never : Key;
147
+ /** Applies the singleton-key constraint to every member of a key tuple. */
148
+ type SinglePropertyKeys<Keys extends readonly PropertyKey[]> = {
149
+ [Index in keyof Keys]: Keys[Index] & SinglePropertyKey<Keys[Index]>;
150
+ };
151
+ /** Narrows one concrete key, or only object-ness for a multi-value key domain. */
152
+ type KeyPresence<Key extends PropertyKey> = [
153
+ SinglePropertyKey<Key>
154
+ ] extends [never] ? object : Record<Key, unknown>;
155
+ /** Narrows concrete key arguments, or only object-ness when any may vary. */
156
+ type KeyPresences<Keys extends readonly PropertyKey[]> = true extends IsUnion<Keys> ? object : [Keys] extends [SinglePropertyKeys<Keys>] ? Record<Keys[number], unknown> : object;
157
+ /** Keeps only one non-negative integer literal that identifies an array index. */
158
+ type ArrayIndex<Index extends number> = SinglePropertyKey<Index> extends never ? never : `${Index}` extends `-${string}` ? never : `${Index}` extends `${bigint}` ? Index : never;
159
+
160
+ type EqualsKeyPredicate<K extends PropertyKey, T> = [
161
+ SinglePropertyKey<K>
162
+ ] extends [never] ? Predicate<object> : <A extends Record<K, unknown>>(input: unknown) => input is A & Record<K, T>;
142
163
  /**
143
164
  * Creates a guard that matches values equal to the provided target using `Object.is` semantics.
144
165
  *
@@ -159,26 +180,32 @@ declare function equalsBy<F extends Predicate<unknown>, K>(guard: F, selector: (
159
180
  /**
160
181
  * Creates a guard that matches objects having a key equal to the target value.
161
182
  *
162
- * @param key Property key to compare.
183
+ * @param key Property key to compare; singleton literals narrow that property.
163
184
  * @param target Value to compare using `Object.is`.
164
- * @returns Predicate narrowing to objects where `key` exists and equals `target`.
185
+ * @returns Predicate with key-specific narrowing for a singleton literal key,
186
+ * or object-only narrowing for a multi-value key domain.
165
187
  */
166
- declare function equalsKey<K extends PropertyKey, const T>(key: K, target: T): <A extends Record<K, unknown>>(input: unknown) => input is A & Record<K, T>;
188
+ declare function equalsKey<const K extends PropertyKey, const T>(key: K, target: T): EqualsKeyPredicate<K, T>;
167
189
 
190
+ type NarrowKeyPredicate<A, K extends PropertyKey, T> = [
191
+ SinglePropertyKey<K>
192
+ ] extends [never] ? Predicate<A> : Predicate<A & Record<K, T>>;
168
193
  /**
169
194
  * Checks whether a value has the specified own key.
170
195
  *
171
196
  * @param key Property key to check.
172
- * @returns Predicate narrowing to an object with the key present.
197
+ * @returns Predicate with key-specific narrowing for a singleton literal key,
198
+ * or object-only narrowing for a multi-value key domain.
173
199
  */
174
- declare const hasKey: <K extends PropertyKey>(key: K) => Predicate<Record<K, unknown>>;
200
+ declare function hasKey<const K extends PropertyKey>(key: K): Predicate<KeyPresence<K>>;
175
201
  /**
176
202
  * Checks whether a value has all specified own keys.
177
203
  *
178
204
  * @param keys Property keys to check.
179
- * @returns Predicate narrowing to an object with all keys present.
205
+ * @returns Predicate with key-specific narrowing when every argument is a
206
+ * singleton literal key, or object-only narrowing otherwise.
180
207
  */
181
- declare const hasKeys: <const KS extends readonly [PropertyKey, ...PropertyKey[]]>(...keys: KS) => Predicate<Record<KS[number], unknown>>;
208
+ declare function hasKeys<const KS extends readonly [PropertyKey, ...PropertyKey[]]>(...keys: KS): Predicate<KeyPresences<KS>>;
182
209
  /**
183
210
  * Builds a guard that narrows a specific key to the provided literal value.
184
211
  *
@@ -187,11 +214,45 @@ declare const hasKeys: <const KS extends readonly [PropertyKey, ...PropertyKey[]
187
214
  * `{ [key]: target }`.
188
215
  *
189
216
  * @param guard Base guard for objects that include `key`.
190
- * @param key Property key to narrow.
217
+ * @param key Property key to compare; singleton literals narrow that property.
191
218
  * @returns Builder that takes a literal `target` and returns a guard that
192
- * narrows `key` to that literal.
219
+ * narrows a singleton `key` to that literal. Multi-value key domains preserve
220
+ * only the base guard's type.
221
+ */
222
+ declare function narrowKeyTo<A, const K extends keyof A & PropertyKey>(guard: Guard<A>, key: K): <const T extends A[K]>(target: T) => NarrowKeyPredicate<A, K, T>;
223
+
224
+ /**
225
+ * Lifts a required-property refinement to its parent object.
226
+ * @param key Single literal key of the required property to refine.
227
+ * @param refinement Refinement applied to the property value.
228
+ * @returns Refinement that preserves the parent type and narrows the property.
229
+ * @example
230
+ * const hasIdentifierExpression = refineKey('expression', ts.isIdentifier);
231
+ */
232
+ declare function refineKey<const K extends PropertyKey, PropertyInput, PropertyOutput extends PropertyInput>(key: K & SinglePropertyKey<K>, refinement: Refinement<PropertyInput, PropertyOutput>): <ObjectType extends Record<K, PropertyInput>>(value: ObjectType) => value is ObjectType & Record<K, PropertyOutput>;
233
+ /**
234
+ * Lifts a defined optional-property refinement to its parent object.
235
+ * @param key Single literal key of the optional property to refine when defined.
236
+ * @param refinement Refinement applied only to a defined property value.
237
+ * @returns Refinement that requires and narrows the property.
238
+ * @example
239
+ * const hasCallInitializer = refineDefinedKey(
240
+ * 'initializer',
241
+ * ts.isCallExpression
242
+ * );
243
+ */
244
+ declare function refineDefinedKey<const K extends PropertyKey, PropertyInput, PropertyOutput extends PropertyInput>(key: K & SinglePropertyKey<K>, refinement: Refinement<PropertyInput, PropertyOutput>): <ObjectType extends Partial<Record<K, PropertyInput | undefined>>>(value: ObjectType) => value is ObjectType & Record<K, Exclude<PropertyOutput, undefined>>;
245
+ /**
246
+ * Refines one defined own element of a readonly array.
247
+ * @param index Non-negative integer literal identifying the own element.
248
+ * @param refinement Refinement applied only to a defined element.
249
+ * @returns Refinement that narrows the selected index.
250
+ * @example
251
+ * const hasStringFirstArgument = refineIndex(0, ts.isStringLiteral);
193
252
  */
194
- declare function narrowKeyTo<A, K extends keyof A>(guard: Guard<A>, key: K): <const T extends A[K]>(target: T) => Predicate<A & Record<K, T>>;
253
+ declare function refineIndex<const Index extends number, ElementInput, ElementOutput extends ElementInput>(index: ArrayIndex<Index>, refinement: Refinement<ElementInput, ElementOutput>): Refinement<readonly ElementInput[], readonly ElementInput[] & {
254
+ readonly [K in Index]: Exclude<ElementOutput, undefined>;
255
+ }>;
195
256
 
196
257
  /**
197
258
  * Creates a predicate whose implementation is initialized on first use.
@@ -204,14 +265,28 @@ declare function narrowKeyTo<A, K extends keyof A>(guard: Guard<A>, key: K): <co
204
265
  */
205
266
  declare function lazy<T>(factory: () => Predicate<T>): Predicate<T>;
206
267
 
268
+ type RefinementInputs<In, Outputs extends readonly unknown[]> = readonly [
269
+ In,
270
+ ...Outputs
271
+ ];
272
+ /** Builds an ordered refinement tuple from its initial input and output tuple. */
273
+ type RefinementsFromOutputs<In, Outputs extends readonly unknown[]> = {
274
+ [K in keyof Outputs]: Refinement<RefinementInputs<In, Outputs>[K & keyof RefinementInputs<In, Outputs>], Outputs[K] & RefinementInputs<In, Outputs>[K & keyof RefinementInputs<In, Outputs>]>;
275
+ };
276
+ /** Returns the last tuple member, or a fallback for an empty tuple. */
277
+ type LastOr<Default, T extends readonly unknown[]> = T extends readonly [
278
+ ...unknown[],
279
+ infer Tail
280
+ ] ? Tail : Default;
281
+
207
282
  /**
208
- * Combines a precondition guard with an additional refinement to narrow the type.
283
+ * Combines a precondition refinement with an additional refinement.
209
284
  * Prefer this over hand-written `precondition(x) && condition(x)` when the
210
- * composed predicate should be reused as a guard.
285
+ * composed refinement should be reused.
211
286
  *
212
287
  * @param precondition Broad guard evaluated first; short-circuits on failure.
213
288
  * @param condition Refinement evaluated only when `precondition` passes.
214
- * @returns Predicate that narrows the input to a subtype.
289
+ * @returns Refinement that preserves the precondition's input domain.
215
290
  * @example
216
291
  * const isPositiveNumber = and(
217
292
  * isNumber,
@@ -220,14 +295,16 @@ declare function lazy<T>(factory: () => Predicate<T>): Predicate<T>;
220
295
  * @see andAll
221
296
  */
222
297
  declare function and<A, B extends A>(precondition: Guard<A>, condition: Refine<A, B>): Predicate<B>;
298
+ declare function and<A, B extends A, C extends B>(precondition: Refinement<A, B>, condition: Refine<NoInfer<B>, C>): Refinement<A, C>;
223
299
  /**
224
- * Chains a sequence of refinements after a precondition, returning the final guard type.
300
+ * Chains refinements while preserving the precondition's input domain.
225
301
  * Use this instead of nested `&&` checks when each step should keep narrowing
226
302
  * the next refinement.
303
+ * Pass a generic readonly chain as one tuple to preserve its final narrowing.
227
304
  *
228
305
  * @param precondition Initial guard applied first.
229
306
  * @param steps Subsequent refinements applied in order.
230
- * @returns Guard reflecting the result of the refinement chain.
307
+ * @returns Refinement reflecting the final result of the chain.
231
308
  * @example
232
309
  * const isPublicTitle = andAll(isString, minLength(4), startsWithPublic);
233
310
  * @see and
@@ -235,18 +312,27 @@ declare function and<A, B extends A>(precondition: Guard<A>, condition: Refine<A
235
312
  declare function andAll<A>(precondition: Guard<A>): Guard<A>;
236
313
  declare function andAll<A, B extends A>(precondition: Guard<A>, step1: Refine<A, B>): Guard<B>;
237
314
  declare function andAll<A, B extends A, C extends B>(precondition: Guard<A>, step1: Refine<A, B>, step2: Refine<B, C>): Guard<C>;
238
- /**
239
- * Logical OR over multiple guards.
240
- * Prefer this over hand-written `guardA(x) || guardB(x)` when the composed
241
- * predicate should be reused as a guard.
242
- *
243
- * @param guards Guards to evaluate; passes if any guard passes.
244
- * @returns Guard for the union of all guarded types.
315
+ declare function andAll<A, Chain extends readonly Refine<unknown, unknown>[]>(precondition: Guard<A>, ...steps: Chain & RefineChain<A, Chain>): Guard<ChainResult<A, Chain>>;
316
+ declare function andAll<A, B extends A>(precondition: Refinement<A, B>): Refinement<A, B>;
317
+ declare function andAll<A, B extends A, C extends B>(precondition: Refinement<A, B>, step1: Refine<NoInfer<B>, C>): Refinement<A, C>;
318
+ declare function andAll<A, B extends A, C extends B, D extends C>(precondition: Refinement<A, B>, step1: Refine<NoInfer<B>, C>, step2: Refine<NoInfer<C>, D>): Refinement<A, D>;
319
+ declare function andAll<A, B extends A, Chain extends readonly unknown[]>(precondition: Refinement<A, B>, ...steps: Chain & RefineChain<NoInfer<B>, Chain>): Refinement<A, ChainResult<B, Chain>>;
320
+ declare function andAll<A, B extends A, Outputs extends readonly B[]>(precondition: Refinement<A, B>, steps: RefinementsFromOutputs<NoInfer<B>, Outputs>): Refinement<A, LastOr<B, Outputs>>;
321
+ declare function andAll<A, B extends A, Outputs extends B[]>(precondition: Refinement<A, B>, ...steps: readonly unknown[] & RefinementsFromOutputs<B, Outputs>): Refinement<A, LastOr<B, Outputs>>;
322
+ declare function andAll<A, B extends A>(precondition: Refinement<A, B>, ...steps: readonly Refine<NoInfer<B>, NoInfer<B>>[]): Refinement<A, B>;
323
+ /**
324
+ * Logical OR over refinements sharing an input domain.
325
+ * Prefer this over hand-written `refineA(x) || refineB(x)` when the composed
326
+ * refinement should be reused.
327
+ *
328
+ * @param refinements Refinements to evaluate; passes if any refinement passes.
329
+ * @returns Refinement for the union of all narrowed types.
245
330
  * @example
246
331
  * const isId = or(isString, isNumber);
247
332
  * @see oneOf
248
333
  */
249
334
  declare function or<P extends readonly Guard<unknown>[]>(...guards: P): Guard<OutOfGuards<P>>;
335
+ declare function or<A, B extends A, Rest extends readonly Refinement<A, A>[]>(first: Refinement<A, B>, ...rest: Rest): Refinement<A, B | GuardedOf<Rest[number]>>;
250
336
  /**
251
337
  * Adapts a guard so it can be used as a refinement within a known supertype.
252
338
  *
@@ -661,13 +747,14 @@ declare function nonEmptyArrayOf<F extends Predicate<unknown>>(elementGuard: F):
661
747
  declare function mapOf<KF extends Predicate<unknown>, VF extends Predicate<unknown>>(keyGuard: KF, valueGuard: VF): Predicate<ReadonlyMap<GuardedOf<KF>, GuardedOf<VF>>>;
662
748
 
663
749
  /**
664
- * Combines multiple guards; passes when any one guard matches.
750
+ * Combines refinements sharing an input domain.
665
751
  *
666
- * @param guards One or more type guards/refinements to try.
667
- * @returns Predicate that narrows to the union of guarded types.
752
+ * @param refinements One or more refinements to try.
753
+ * @returns Refinement that narrows to the union of matching types.
668
754
  */
669
755
  declare function oneOf<Fs extends readonly Predicate<unknown>[]>(...guards: Fs): Predicate<GuardedOf<Fs[number]>>;
670
756
  declare function oneOf<A, Fs extends readonly Predicate<A>[]>(...guards: Fs): (input: A) => input is GuardedWithin<Fs, A>;
757
+ declare function oneOf<A, B extends A, Rest extends readonly Refinement<A, A>[]>(first: Refinement<A, B>, ...rest: Rest): Refinement<A, B | GuardedOf<Rest[number]>>;
671
758
 
672
759
  /**
673
760
  * Creates a guard that matches when the input is one of the provided literal values.
@@ -721,7 +808,9 @@ declare function optionalKey<G extends Predicate<unknown>>(guard: G): OptionalSc
721
808
  declare function struct<const S extends SchemaShape<S>>(schema: S, options?: StructOptions): Predicate<InferSchema<S>>;
722
809
 
723
810
  /**
724
- * Creates a `struct` builder checked against an existing object type.
811
+ * Creates a `struct` builder checked against an existing string-keyed object
812
+ * type. Numeric and symbol properties are excluded from the checked shape and
813
+ * cannot be validated by the resulting guard.
725
814
  * Optional target keys must also be declared with `optionalKey` so type drift
726
815
  * stays visible when the target type changes.
727
816
  *
@@ -807,4 +896,4 @@ declare const everyOwnEnumerableEntry: (values: Record<string, unknown>, keyPred
807
896
  */
808
897
  declare const toBooleanPredicates: <A>(predicates: readonly ((value: A) => boolean)[]) => ReadonlyArray<(value: A) => boolean>;
809
898
 
810
- export { type ChainResult, type Guard, type GuardedOf, type GuardedWithin, type InferSchema, type NoExtraKeys, type OptionalObjectKeys, type OptionalSchemaField, type OutOfGuards, type ParseResult, type Predicate, type Primitive, type Refine, type RefineChain, type Refinement, type RequiredObjectKeys, type Schema, type SchemaField, type StructOptions, type TypedStructFields, type TypedStructShape, and, andAll, arrayOf, assert, define, equals, equalsBy, equalsKey, everyArrayValue, everyMapEntry, everyOwnEnumerableEntry, everySetValue, everyTupleValue, guardIn, hasKey, hasKeys, isArray, isArrayBuffer, isAsyncIterable, isBigInt, isBlob, isBoolean, isDataView, isDate, isError, isFile, isFiniteNumber, isFunction, isInfiniteNumber, isInstanceOf, isInteger, isIterable, isMap, isNaN, isNegative, isNil, isNotNil, isNull, isNumber, isNumberPrimitive, isObject, isPlainObject, isPositive, isPrimitive, isPromiseLike, isRegExp, isSafeInteger, isSet, isString, isSymbol, isTypedArray, isURL, isUndefined, isWeakMap, isWeakSet, isZero, lazy, mapOf, narrowKeyTo, nonEmptyArrayOf, nonNull, not, nullable, nullish, oneOf, oneOfValues, optional, optionalKey, or, predicateToRefine, recordOf, required, safeJsonParse, safeParse, safeParseWith, setOf, struct, toBooleanPredicates, tupleOf, typedStruct };
899
+ export { type ChainResult, type Guard, type GuardedOf, type GuardedWithin, type InferSchema, type NoExtraKeys, type OptionalObjectKeys, type OptionalSchemaField, type OutOfGuards, type ParseResult, type Predicate, type Primitive, type Refine, type RefineChain, type Refinement, type RequiredObjectKeys, type Schema, type SchemaField, type StructOptions, type TypedStructFields, type TypedStructShape, and, andAll, arrayOf, assert, define, equals, equalsBy, equalsKey, everyArrayValue, everyMapEntry, everyOwnEnumerableEntry, everySetValue, everyTupleValue, guardIn, hasKey, hasKeys, isArray, isArrayBuffer, isAsyncIterable, isBigInt, isBlob, isBoolean, isDataView, isDate, isError, isFile, isFiniteNumber, isFunction, isInfiniteNumber, isInstanceOf, isInteger, isIterable, isMap, isNaN, isNegative, isNil, isNotNil, isNull, isNumber, isNumberPrimitive, isObject, isPlainObject, isPositive, isPrimitive, isPromiseLike, isRegExp, isSafeInteger, isSet, isString, isSymbol, isTypedArray, isURL, isUndefined, isWeakMap, isWeakSet, isZero, lazy, mapOf, narrowKeyTo, nonEmptyArrayOf, nonNull, not, nullable, nullish, oneOf, oneOfValues, optional, optionalKey, or, predicateToRefine, recordOf, refineDefinedKey, refineIndex, refineKey, required, safeJsonParse, safeParse, safeParseWith, setOf, struct, toBooleanPredicates, tupleOf, typedStruct };
package/dist/index.js CHANGED
@@ -91,6 +91,9 @@ __export(index_exports, {
91
91
  or: () => or,
92
92
  predicateToRefine: () => predicateToRefine,
93
93
  recordOf: () => recordOf,
94
+ refineDefinedKey: () => refineDefinedKey,
95
+ refineIndex: () => refineIndex,
96
+ refineKey: () => refineKey,
94
97
  required: () => required,
95
98
  safeJsonParse: () => safeJsonParse,
96
99
  safeParse: () => safeParse,
@@ -241,22 +244,25 @@ function equalsBy(guard, selector) {
241
244
  return (selectorFn) => createComparator(selectorFn);
242
245
  }
243
246
  function equalsKey(key, target) {
244
- const hasMatchingKey = define((input) => {
247
+ return define((input) => {
245
248
  return isObject(input) && hasOwnPropertyKey(input, key) && Object.is(input[key], target);
246
249
  });
247
- return (input) => hasMatchingKey(input);
248
250
  }
249
251
 
250
- // src/core/key.ts
251
- var hasKey = (key) => define((input) => isObject(input) && hasOwnPropertyKey(input, key));
252
- var hasKeys = (...keys) => {
252
+ // src/core/key-guards.ts
253
+ function hasKey(key) {
254
+ return define(
255
+ (input) => isObject(input) && hasOwnPropertyKey(input, key)
256
+ );
257
+ }
258
+ function hasKeys(...keys) {
253
259
  if (keys.length === 0) {
254
260
  return define(() => false);
255
261
  }
256
262
  return define(
257
263
  (input) => isObject(input) && hasOwnPropertyKeys(input, keys)
258
264
  );
259
- };
265
+ }
260
266
  function narrowKeyTo(guard, key) {
261
267
  return (target) => {
262
268
  const keyEquals = equalsKey(key, target);
@@ -266,6 +272,24 @@ function narrowKeyTo(guard, key) {
266
272
  };
267
273
  }
268
274
 
275
+ // src/core/property-refinement.ts
276
+ function refineKey(key, refinement) {
277
+ return (value) => refinement(value[key]);
278
+ }
279
+ function refineDefinedKey(key, refinement) {
280
+ return (value) => {
281
+ const property = value[key];
282
+ return property !== void 0 && refinement(property);
283
+ };
284
+ }
285
+ function refineIndex(index, refinement) {
286
+ return (value) => {
287
+ if (!hasOwnPropertyKey(value, index)) return false;
288
+ const element = value[index];
289
+ return element !== void 0 && refinement(element);
290
+ };
291
+ }
292
+
269
293
  // src/core/lazy.ts
270
294
  function lazy(factory) {
271
295
  let predicate;
@@ -275,29 +299,19 @@ function lazy(factory) {
275
299
  };
276
300
  }
277
301
 
278
- // src/utils/to-boolean-predicates.ts
279
- var toBooleanPredicates = (predicates) => predicates;
280
-
281
302
  // src/core/logic.ts
282
303
  function and(precondition, condition) {
283
- return define((input) => {
284
- if (precondition(input)) {
285
- return condition(input);
286
- }
287
- return false;
288
- });
304
+ return (input) => !!(precondition(input) && condition(input));
289
305
  }
290
- function andAll(precondition, ...steps) {
291
- return define((input) => {
306
+ function andAll(precondition, stepOrSteps, ...remainingSteps) {
307
+ const steps = stepOrSteps === void 0 ? remainingSteps : isFunction(stepOrSteps) ? [stepOrSteps, ...remainingSteps] : [...stepOrSteps, ...remainingSteps];
308
+ return (input) => {
292
309
  if (!precondition(input)) return false;
293
- return applyRefinements(input, steps);
294
- });
310
+ return steps.every((step) => step(input));
311
+ };
295
312
  }
296
- function or(...guards) {
297
- const predicates = toBooleanPredicates(guards);
298
- return define(
299
- (input) => predicates.some((guard) => guard(input))
300
- );
313
+ function or(...refinements) {
314
+ return (input) => refinements.some((refinement) => refinement(input));
301
315
  }
302
316
  function guardIn() {
303
317
  return (guard) => (input) => guard(input);
@@ -305,13 +319,6 @@ function guardIn() {
305
319
  function not(fn) {
306
320
  return (input) => !fn(input);
307
321
  }
308
- function applyRefinements(value, steps) {
309
- if (!steps || steps.length === 0) return true;
310
- for (const step of steps) {
311
- if (!step(value)) return false;
312
- }
313
- return true;
314
- }
315
322
 
316
323
  // src/core/nullish.ts
317
324
  var allowWhen = (acceptedValue, predicate) => (value) => acceptedValue(value) || predicate(value);
@@ -455,8 +462,8 @@ function mapOf(keyGuard, valueGuard) {
455
462
  }
456
463
 
457
464
  // src/core/combinators/one-of.ts
458
- function oneOf(...guards) {
459
- return or(...guards);
465
+ function oneOf(...refinements) {
466
+ return (input) => refinements.some((refinement) => refinement(input));
460
467
  }
461
468
 
462
469
  // src/core/combinators/one-of-values.ts
@@ -572,6 +579,9 @@ function tupleOf(...guards) {
572
579
  (input) => Array.isArray(input) && everyTupleValue(input, guards)
573
580
  );
574
581
  }
582
+
583
+ // src/utils/to-boolean-predicates.ts
584
+ var toBooleanPredicates = (predicates) => predicates;
575
585
  // Annotate the CommonJS export names for ESM import in node:
576
586
  0 && (module.exports = {
577
587
  and,
@@ -645,6 +655,9 @@ function tupleOf(...guards) {
645
655
  or,
646
656
  predicateToRefine,
647
657
  recordOf,
658
+ refineDefinedKey,
659
+ refineIndex,
660
+ refineKey,
648
661
  required,
649
662
  safeJsonParse,
650
663
  safeParse,
package/dist/index.mjs CHANGED
@@ -136,22 +136,25 @@ function equalsBy(guard, selector) {
136
136
  return (selectorFn) => createComparator(selectorFn);
137
137
  }
138
138
  function equalsKey(key, target) {
139
- const hasMatchingKey = define((input) => {
139
+ return define((input) => {
140
140
  return isObject(input) && hasOwnPropertyKey(input, key) && Object.is(input[key], target);
141
141
  });
142
- return (input) => hasMatchingKey(input);
143
142
  }
144
143
 
145
- // src/core/key.ts
146
- var hasKey = (key) => define((input) => isObject(input) && hasOwnPropertyKey(input, key));
147
- var hasKeys = (...keys) => {
144
+ // src/core/key-guards.ts
145
+ function hasKey(key) {
146
+ return define(
147
+ (input) => isObject(input) && hasOwnPropertyKey(input, key)
148
+ );
149
+ }
150
+ function hasKeys(...keys) {
148
151
  if (keys.length === 0) {
149
152
  return define(() => false);
150
153
  }
151
154
  return define(
152
155
  (input) => isObject(input) && hasOwnPropertyKeys(input, keys)
153
156
  );
154
- };
157
+ }
155
158
  function narrowKeyTo(guard, key) {
156
159
  return (target) => {
157
160
  const keyEquals = equalsKey(key, target);
@@ -161,6 +164,24 @@ function narrowKeyTo(guard, key) {
161
164
  };
162
165
  }
163
166
 
167
+ // src/core/property-refinement.ts
168
+ function refineKey(key, refinement) {
169
+ return (value) => refinement(value[key]);
170
+ }
171
+ function refineDefinedKey(key, refinement) {
172
+ return (value) => {
173
+ const property = value[key];
174
+ return property !== void 0 && refinement(property);
175
+ };
176
+ }
177
+ function refineIndex(index, refinement) {
178
+ return (value) => {
179
+ if (!hasOwnPropertyKey(value, index)) return false;
180
+ const element = value[index];
181
+ return element !== void 0 && refinement(element);
182
+ };
183
+ }
184
+
164
185
  // src/core/lazy.ts
165
186
  function lazy(factory) {
166
187
  let predicate;
@@ -170,29 +191,19 @@ function lazy(factory) {
170
191
  };
171
192
  }
172
193
 
173
- // src/utils/to-boolean-predicates.ts
174
- var toBooleanPredicates = (predicates) => predicates;
175
-
176
194
  // src/core/logic.ts
177
195
  function and(precondition, condition) {
178
- return define((input) => {
179
- if (precondition(input)) {
180
- return condition(input);
181
- }
182
- return false;
183
- });
196
+ return (input) => !!(precondition(input) && condition(input));
184
197
  }
185
- function andAll(precondition, ...steps) {
186
- return define((input) => {
198
+ function andAll(precondition, stepOrSteps, ...remainingSteps) {
199
+ const steps = stepOrSteps === void 0 ? remainingSteps : isFunction(stepOrSteps) ? [stepOrSteps, ...remainingSteps] : [...stepOrSteps, ...remainingSteps];
200
+ return (input) => {
187
201
  if (!precondition(input)) return false;
188
- return applyRefinements(input, steps);
189
- });
202
+ return steps.every((step) => step(input));
203
+ };
190
204
  }
191
- function or(...guards) {
192
- const predicates = toBooleanPredicates(guards);
193
- return define(
194
- (input) => predicates.some((guard) => guard(input))
195
- );
205
+ function or(...refinements) {
206
+ return (input) => refinements.some((refinement) => refinement(input));
196
207
  }
197
208
  function guardIn() {
198
209
  return (guard) => (input) => guard(input);
@@ -200,13 +211,6 @@ function guardIn() {
200
211
  function not(fn) {
201
212
  return (input) => !fn(input);
202
213
  }
203
- function applyRefinements(value, steps) {
204
- if (!steps || steps.length === 0) return true;
205
- for (const step of steps) {
206
- if (!step(value)) return false;
207
- }
208
- return true;
209
- }
210
214
 
211
215
  // src/core/nullish.ts
212
216
  var allowWhen = (acceptedValue, predicate) => (value) => acceptedValue(value) || predicate(value);
@@ -350,8 +354,8 @@ function mapOf(keyGuard, valueGuard) {
350
354
  }
351
355
 
352
356
  // src/core/combinators/one-of.ts
353
- function oneOf(...guards) {
354
- return or(...guards);
357
+ function oneOf(...refinements) {
358
+ return (input) => refinements.some((refinement) => refinement(input));
355
359
  }
356
360
 
357
361
  // src/core/combinators/one-of-values.ts
@@ -467,6 +471,9 @@ function tupleOf(...guards) {
467
471
  (input) => Array.isArray(input) && everyTupleValue(input, guards)
468
472
  );
469
473
  }
474
+
475
+ // src/utils/to-boolean-predicates.ts
476
+ var toBooleanPredicates = (predicates) => predicates;
470
477
  export {
471
478
  and,
472
479
  andAll,
@@ -539,6 +546,9 @@ export {
539
546
  or,
540
547
  predicateToRefine,
541
548
  recordOf,
549
+ refineDefinedKey,
550
+ refineIndex,
551
+ refineKey,
542
552
  required,
543
553
  safeJsonParse,
544
554
  safeParse,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "is-kit",
3
- "version": "1.12.1",
3
+ "version": "1.14.0",
4
4
  "description": "Zero-dependency TypeScript runtime validation toolkit for composable type guards and natural type narrowing.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -15,6 +15,18 @@
15
15
  "bin": {
16
16
  "is-kit": "./bin/is-kit.mjs"
17
17
  },
18
+ "scripts": {
19
+ "test": "jest",
20
+ "test:types": "tsd && tsc -p tests-d/tsconfig.property-refinement.json",
21
+ "test:typescript-compat": "node tests/typescript-compatibility.mjs",
22
+ "test:package": "node tests/package-smoke.mjs",
23
+ "test:package:vlt": "node tests/vlt-package-smoke.mjs",
24
+ "lint": "oxlint .",
25
+ "format": "oxfmt .",
26
+ "format:check": "oxfmt --check .",
27
+ "build": "tsup",
28
+ "typedoc": "typedoc --out docs/public/api"
29
+ },
18
30
  "keywords": [
19
31
  "typescript",
20
32
  "type-guard",
@@ -43,9 +55,10 @@
43
55
  "bugs": {
44
56
  "url": "https://github.com/nyaomaru/is-kit/issues"
45
57
  },
46
- "homepage": "https://is-kit-docs.vercel.app/",
58
+ "homepage": "https://is-kit.dev/",
47
59
  "author": "nyaomaru",
48
60
  "license": "MIT",
61
+ "packageManager": "pnpm@11.2.2",
49
62
  "devDependencies": {
50
63
  "@types/jest": "^30.0.0",
51
64
  "jest": "^30.4.2",
@@ -64,16 +77,5 @@
64
77
  "baseUrl": ".",
65
78
  "ignoreDeprecations": "6.0"
66
79
  }
67
- },
68
- "scripts": {
69
- "test": "jest",
70
- "test:types": "tsd",
71
- "test:package": "node tests/package-smoke.mjs",
72
- "test:package:vlt": "node tests/vlt-package-smoke.mjs",
73
- "lint": "oxlint .",
74
- "format": "oxfmt .",
75
- "format:check": "oxfmt --check .",
76
- "build": "tsup",
77
- "typedoc": "typedoc --out docs/public/api"
78
80
  }
79
- }
81
+ }